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 PutB(buf []byte) (string, int, 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)
65 // NewLogWriter is a factory function to create a new log writer.
66 type NewLogWriter func(name string) (io.WriteCloser, error)
68 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
70 type MkTempDir func(string, string) (string, error)
72 type PsProcess interface {
73 CmdlineSlice() ([]string, error)
76 // ContainerRunner is the main stateful struct used for a single execution of a
78 type ContainerRunner struct {
79 executor containerExecutor
81 // Dispatcher client is initialized with the Dispatcher token.
82 // This is a privileged token used to manage container status
85 // We have both dispatcherClient and DispatcherArvClient
86 // because there are two different incompatible Arvados Go
87 // SDKs and we have to use both (hopefully this gets fixed in
89 dispatcherClient *arvados.Client
90 DispatcherArvClient IArvadosClient
91 DispatcherKeepClient IKeepClient
93 // Container client is initialized with the Container token
94 // This token controls the permissions of the container, and
95 // must be used for operations such as reading collections.
97 // Same comment as above applies to
98 // containerClient/ContainerArvClient.
99 containerClient *arvados.Client
100 ContainerArvClient IArvadosClient
101 ContainerKeepClient IKeepClient
103 Container arvados.Container
106 NewLogWriter NewLogWriter
107 CrunchLog *ThrottledLogger
108 Stdout io.WriteCloser
109 Stderr io.WriteCloser
112 LogCollection arvados.CollectionFileSystem
114 RunArvMount RunArvMount
119 Volumes map[string]struct{}
121 SigChan chan os.Signal
122 ArvMountExit chan error
123 SecretMounts map[string]arvados.Mount
124 MkArvClient func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error)
128 statLogger io.WriteCloser
129 statReporter *crunchstat.Reporter
130 hoststatLogger io.WriteCloser
131 hoststatReporter *crunchstat.Reporter
132 statInterval time.Duration
134 // What we expect the container's cgroup parent to be.
135 expectCgroupParent string
136 // What we tell docker to use as the container's cgroup
137 // parent. Note: Ideally we would use the same field for both
138 // expectCgroupParent and setCgroupParent, and just make it
139 // default to "docker". However, when using docker < 1.10 with
140 // systemd, specifying a non-empty cgroup parent (even the
141 // default value "docker") hits a docker bug
142 // (https://github.com/docker/docker/issues/17126). Using two
143 // separate fields makes it possible to use the "expect cgroup
144 // parent to be X" feature even on sites where the "specify
145 // cgroup parent" feature breaks.
146 setCgroupParent string
148 cStateLock sync.Mutex
149 cCancelled bool // StopContainer() invoked
151 enableMemoryLimit bool
152 enableNetwork string // one of "default" or "always"
153 networkMode string // "none", "host", or "" -- passed through to executor
154 arvMountLog *ThrottledLogger
156 containerWatchdogInterval time.Duration
161 // setupSignals sets up signal handling to gracefully terminate the
162 // underlying container and update state when receiving a TERM, INT or
164 func (runner *ContainerRunner) setupSignals() {
165 runner.SigChan = make(chan os.Signal, 1)
166 signal.Notify(runner.SigChan, syscall.SIGTERM)
167 signal.Notify(runner.SigChan, syscall.SIGINT)
168 signal.Notify(runner.SigChan, syscall.SIGQUIT)
170 go func(sig chan os.Signal) {
177 // stop the underlying container.
178 func (runner *ContainerRunner) stop(sig os.Signal) {
179 runner.cStateLock.Lock()
180 defer runner.cStateLock.Unlock()
182 runner.CrunchLog.Printf("caught signal: %v", sig)
184 runner.cCancelled = true
185 runner.CrunchLog.Printf("stopping container")
186 err := runner.executor.Stop()
188 runner.CrunchLog.Printf("error stopping container: %s", err)
192 var errorBlacklist = []string{
193 "(?ms).*[Cc]annot connect to the Docker daemon.*",
194 "(?ms).*oci runtime error.*starting container process.*container init.*mounting.*to rootfs.*no such file or directory.*",
195 "(?ms).*grpc: the connection is unavailable.*",
197 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)")
199 func (runner *ContainerRunner) runBrokenNodeHook() {
200 if *brokenNodeHook == "" {
201 path := filepath.Join(lockdir, brokenfile)
202 runner.CrunchLog.Printf("Writing %s to mark node as broken", path)
203 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0700)
205 runner.CrunchLog.Printf("Error writing %s: %s", path, err)
210 runner.CrunchLog.Printf("Running broken node hook %q", *brokenNodeHook)
212 c := exec.Command(*brokenNodeHook)
213 c.Stdout = runner.CrunchLog
214 c.Stderr = runner.CrunchLog
217 runner.CrunchLog.Printf("Error running broken node hook: %v", err)
222 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
223 for _, d := range errorBlacklist {
224 if m, e := regexp.MatchString(d, goterr.Error()); m && e == nil {
225 runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
226 runner.runBrokenNodeHook()
233 // LoadImage determines the docker image id from the container record and
234 // checks if it is available in the local Docker image store. If not, it loads
235 // the image from Keep.
236 func (runner *ContainerRunner) LoadImage() (string, error) {
237 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
239 d, err := os.Open(runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage)
244 allfiles, err := d.Readdirnames(-1)
248 var tarfiles []string
249 for _, fnm := range allfiles {
250 if strings.HasSuffix(fnm, ".tar") {
251 tarfiles = append(tarfiles, fnm)
254 if len(tarfiles) == 0 {
255 return "", fmt.Errorf("image collection does not include a .tar image file")
257 if len(tarfiles) > 1 {
258 return "", fmt.Errorf("cannot choose from multiple tar files in image collection: %v", tarfiles)
260 imageID := tarfiles[0][:len(tarfiles[0])-4]
261 imageFile := runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage + "/" + tarfiles[0]
262 runner.CrunchLog.Printf("Using Docker image id %q", imageID)
264 if !runner.executor.ImageLoaded(imageID) {
265 runner.CrunchLog.Print("Loading Docker image from keep")
266 err = runner.executor.LoadImage(imageFile)
271 runner.CrunchLog.Print("Docker image is available")
276 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
277 c = exec.Command("arv-mount", arvMountCmd...)
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 c.Stdout = runner.arvMountLog
295 c.Stderr = io.MultiWriter(runner.arvMountLog, os.Stderr)
297 runner.CrunchLog.Printf("Running %v", c.Args)
304 statReadme := make(chan bool)
305 runner.ArvMountExit = make(chan error)
310 time.Sleep(100 * time.Millisecond)
311 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
323 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
325 runner.ArvMountExit <- mnterr
326 close(runner.ArvMountExit)
332 case err := <-runner.ArvMountExit:
333 runner.ArvMount = nil
341 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
342 if runner.ArvMountPoint == "" {
343 runner.ArvMountPoint, err = runner.MkTempDir(runner.parentTemp, prefix)
348 func copyfile(src string, dst string) (err error) {
349 srcfile, err := os.Open(src)
354 os.MkdirAll(path.Dir(dst), 0777)
356 dstfile, err := os.Create(dst)
360 _, err = io.Copy(dstfile, srcfile)
365 err = srcfile.Close()
366 err2 := dstfile.Close()
379 func (runner *ContainerRunner) SetupMounts() (map[string]bindmount, error) {
380 bindmounts := map[string]bindmount{}
381 err := runner.SetupArvMountPoint("keep")
383 return nil, fmt.Errorf("While creating keep mount temp dir: %v", err)
386 token, err := runner.ContainerToken()
388 return nil, fmt.Errorf("could not get container token: %s", err)
390 runner.CrunchLog.Printf("container token %q", token)
394 arvMountCmd := []string{
398 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
400 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
401 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
404 collectionPaths := []string{}
405 needCertMount := true
406 type copyFile struct {
410 var copyFiles []copyFile
413 for bind := range runner.Container.Mounts {
414 binds = append(binds, bind)
416 for bind := range runner.SecretMounts {
417 if _, ok := runner.Container.Mounts[bind]; ok {
418 return nil, fmt.Errorf("secret mount %q conflicts with regular mount", bind)
420 if runner.SecretMounts[bind].Kind != "json" &&
421 runner.SecretMounts[bind].Kind != "text" {
422 return nil, fmt.Errorf("secret mount %q type is %q but only 'json' and 'text' are permitted",
423 bind, runner.SecretMounts[bind].Kind)
425 binds = append(binds, bind)
429 for _, bind := range binds {
430 mnt, ok := runner.Container.Mounts[bind]
432 mnt = runner.SecretMounts[bind]
434 if bind == "stdout" || bind == "stderr" {
435 // Is it a "file" mount kind?
436 if mnt.Kind != "file" {
437 return nil, fmt.Errorf("unsupported mount kind '%s' for %s: only 'file' is supported", mnt.Kind, bind)
440 // Does path start with OutputPath?
441 prefix := runner.Container.OutputPath
442 if !strings.HasSuffix(prefix, "/") {
445 if !strings.HasPrefix(mnt.Path, prefix) {
446 return nil, fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
451 // Is it a "collection" mount kind?
452 if mnt.Kind != "collection" && mnt.Kind != "json" {
453 return nil, fmt.Errorf("unsupported mount kind '%s' for stdin: only 'collection' and 'json' are supported", mnt.Kind)
457 if bind == "/etc/arvados/ca-certificates.crt" {
458 needCertMount = false
461 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
462 if mnt.Kind != "collection" && mnt.Kind != "text" && mnt.Kind != "json" {
463 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)
468 case mnt.Kind == "collection" && bind != "stdin":
470 if mnt.UUID != "" && mnt.PortableDataHash != "" {
471 return nil, fmt.Errorf("cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
475 return nil, fmt.Errorf("writing to existing collections currently not permitted")
478 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
479 } else if mnt.PortableDataHash != "" {
480 if mnt.Writable && !strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
481 return nil, fmt.Errorf("can never write to a collection specified by portable data hash")
483 idx := strings.Index(mnt.PortableDataHash, "/")
485 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
486 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
487 runner.Container.Mounts[bind] = mnt
489 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
490 if mnt.Path != "" && mnt.Path != "." {
491 if strings.HasPrefix(mnt.Path, "./") {
492 mnt.Path = mnt.Path[2:]
493 } else if strings.HasPrefix(mnt.Path, "/") {
494 mnt.Path = mnt.Path[1:]
496 src += "/" + mnt.Path
499 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
500 arvMountCmd = append(arvMountCmd, "--mount-tmp")
501 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
505 if bind == runner.Container.OutputPath {
506 runner.HostOutputDir = src
507 bindmounts[bind] = bindmount{HostPath: src}
508 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
509 copyFiles = append(copyFiles, copyFile{src, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
511 bindmounts[bind] = bindmount{HostPath: src}
514 bindmounts[bind] = bindmount{HostPath: src, ReadOnly: true}
516 collectionPaths = append(collectionPaths, src)
518 case mnt.Kind == "tmp":
520 tmpdir, err = runner.MkTempDir(runner.parentTemp, "tmp")
522 return nil, fmt.Errorf("while creating mount temp dir: %v", err)
524 st, staterr := os.Stat(tmpdir)
526 return nil, fmt.Errorf("while Stat on temp dir: %v", staterr)
528 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
530 return nil, fmt.Errorf("while Chmod temp dir: %v", err)
532 bindmounts[bind] = bindmount{HostPath: tmpdir}
533 if bind == runner.Container.OutputPath {
534 runner.HostOutputDir = tmpdir
537 case mnt.Kind == "json" || mnt.Kind == "text":
539 if mnt.Kind == "json" {
540 filedata, err = json.Marshal(mnt.Content)
542 return nil, fmt.Errorf("encoding json data: %v", err)
545 text, ok := mnt.Content.(string)
547 return nil, fmt.Errorf("content for mount %q must be a string", bind)
549 filedata = []byte(text)
552 tmpdir, err := runner.MkTempDir(runner.parentTemp, mnt.Kind)
554 return nil, fmt.Errorf("creating temp dir: %v", err)
556 tmpfn := filepath.Join(tmpdir, "mountdata."+mnt.Kind)
557 err = ioutil.WriteFile(tmpfn, filedata, 0444)
559 return nil, fmt.Errorf("writing temp file: %v", err)
561 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
562 copyFiles = append(copyFiles, copyFile{tmpfn, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
564 bindmounts[bind] = bindmount{HostPath: tmpfn, ReadOnly: true}
567 case mnt.Kind == "git_tree":
568 tmpdir, err := runner.MkTempDir(runner.parentTemp, "git_tree")
570 return nil, fmt.Errorf("creating temp dir: %v", err)
572 err = gitMount(mnt).extractTree(runner.ContainerArvClient, tmpdir, token)
576 bindmounts[bind] = bindmount{HostPath: tmpdir, ReadOnly: true}
580 if runner.HostOutputDir == "" {
581 return nil, fmt.Errorf("output path does not correspond to a writable mount point")
584 if needCertMount && runner.Container.RuntimeConstraints.API {
585 for _, certfile := range arvadosclient.CertFiles {
586 _, err := os.Stat(certfile)
588 bindmounts["/etc/arvados/ca-certificates.crt"] = bindmount{HostPath: certfile, ReadOnly: true}
595 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
597 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
599 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
601 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
603 return nil, fmt.Errorf("while trying to start arv-mount: %v", err)
606 for _, p := range collectionPaths {
609 return nil, fmt.Errorf("while checking that input files exist: %v", err)
613 for _, cp := range copyFiles {
614 st, err := os.Stat(cp.src)
616 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
619 err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
623 target := path.Join(cp.bind, walkpath[len(cp.src):])
624 if walkinfo.Mode().IsRegular() {
625 copyerr := copyfile(walkpath, target)
629 return os.Chmod(target, walkinfo.Mode()|0777)
630 } else if walkinfo.Mode().IsDir() {
631 mkerr := os.MkdirAll(target, 0777)
635 return os.Chmod(target, walkinfo.Mode()|os.ModeSetgid|0777)
637 return fmt.Errorf("source %q is not a regular file or directory", cp.src)
640 } else if st.Mode().IsRegular() {
641 err = copyfile(cp.src, cp.bind)
643 err = os.Chmod(cp.bind, st.Mode()|0777)
647 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
651 return bindmounts, nil
654 func (runner *ContainerRunner) stopHoststat() error {
655 if runner.hoststatReporter == nil {
658 runner.hoststatReporter.Stop()
659 err := runner.hoststatLogger.Close()
661 return fmt.Errorf("error closing hoststat logs: %v", err)
666 func (runner *ContainerRunner) startHoststat() error {
667 w, err := runner.NewLogWriter("hoststat")
671 runner.hoststatLogger = NewThrottledLogger(w)
672 runner.hoststatReporter = &crunchstat.Reporter{
673 Logger: log.New(runner.hoststatLogger, "", 0),
674 CgroupRoot: runner.cgroupRoot,
675 PollPeriod: runner.statInterval,
677 runner.hoststatReporter.Start()
681 func (runner *ContainerRunner) startCrunchstat() error {
682 w, err := runner.NewLogWriter("crunchstat")
686 runner.statLogger = NewThrottledLogger(w)
687 runner.statReporter = &crunchstat.Reporter{
688 CID: runner.executor.CgroupID(),
689 Logger: log.New(runner.statLogger, "", 0),
690 CgroupParent: runner.expectCgroupParent,
691 CgroupRoot: runner.cgroupRoot,
692 PollPeriod: runner.statInterval,
693 TempDir: runner.parentTemp,
695 runner.statReporter.Start()
699 type infoCommand struct {
704 // LogHostInfo logs info about the current host, for debugging and
705 // accounting purposes. Although it's logged as "node-info", this is
706 // about the environment where crunch-run is actually running, which
707 // might differ from what's described in the node record (see
709 func (runner *ContainerRunner) LogHostInfo() (err error) {
710 w, err := runner.NewLogWriter("node-info")
715 commands := []infoCommand{
717 label: "Host Information",
718 cmd: []string{"uname", "-a"},
721 label: "CPU Information",
722 cmd: []string{"cat", "/proc/cpuinfo"},
725 label: "Memory Information",
726 cmd: []string{"cat", "/proc/meminfo"},
730 cmd: []string{"df", "-m", "/", os.TempDir()},
733 label: "Disk INodes",
734 cmd: []string{"df", "-i", "/", os.TempDir()},
738 // Run commands with informational output to be logged.
739 for _, command := range commands {
740 fmt.Fprintln(w, command.label)
741 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
744 if err := cmd.Run(); err != nil {
745 err = fmt.Errorf("While running command %q: %v", command.cmd, err)
754 return fmt.Errorf("While closing node-info logs: %v", err)
759 // LogContainerRecord gets and saves the raw JSON container record from the API server
760 func (runner *ContainerRunner) LogContainerRecord() error {
761 logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
762 if !logged && err == nil {
763 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
768 // LogNodeRecord logs the current host's InstanceType config entry (or
769 // the arvados#node record, if running via crunch-dispatch-slurm).
770 func (runner *ContainerRunner) LogNodeRecord() error {
771 if it := os.Getenv("InstanceType"); it != "" {
772 // Dispatched via arvados-dispatch-cloud. Save
773 // InstanceType config fragment received from
774 // dispatcher on stdin.
775 w, err := runner.LogCollection.OpenFile("node.json", os.O_CREATE|os.O_WRONLY, 0666)
780 _, err = io.WriteString(w, it)
786 // Dispatched via crunch-dispatch-slurm. Look up
787 // apiserver's node record corresponding to
789 hostname := os.Getenv("SLURMD_NODENAME")
791 hostname, _ = os.Hostname()
793 _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
794 // The "info" field has admin-only info when
795 // obtained with a privileged token, and
796 // should not be logged.
797 node, ok := resp.(map[string]interface{})
805 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
806 writer, err := runner.LogCollection.OpenFile(label+".json", os.O_CREATE|os.O_WRONLY, 0666)
811 ArvClient: runner.DispatcherArvClient,
812 UUID: runner.Container.UUID,
813 loggingStream: label,
817 reader, err := runner.DispatcherArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
819 return false, fmt.Errorf("error getting %s record: %v", label, err)
823 dec := json.NewDecoder(reader)
825 var resp map[string]interface{}
826 if err = dec.Decode(&resp); err != nil {
827 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
829 items, ok := resp["items"].([]interface{})
831 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
832 } else if len(items) < 1 {
838 // Re-encode it using indentation to improve readability
839 enc := json.NewEncoder(w)
840 enc.SetIndent("", " ")
841 if err = enc.Encode(items[0]); err != nil {
842 return false, fmt.Errorf("error logging %s record: %v", label, err)
846 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
851 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
852 stdoutPath := mntPath[len(runner.Container.OutputPath):]
853 index := strings.LastIndex(stdoutPath, "/")
855 subdirs := stdoutPath[:index]
857 st, err := os.Stat(runner.HostOutputDir)
859 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
861 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
862 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
864 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
868 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
870 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
873 return stdoutFile, nil
876 // CreateContainer creates the docker container.
877 func (runner *ContainerRunner) CreateContainer(imageID string, bindmounts map[string]bindmount) error {
878 var stdin io.ReadCloser
879 if mnt, ok := runner.Container.Mounts["stdin"]; ok {
886 collID = mnt.PortableDataHash
888 path := runner.ArvMountPoint + "/by_id/" + collID + "/" + mnt.Path
889 f, err := os.Open(path)
895 j, err := json.Marshal(mnt.Content)
897 return fmt.Errorf("error encoding stdin json data: %v", err)
899 stdin = ioutil.NopCloser(bytes.NewReader(j))
901 return fmt.Errorf("stdin mount has unsupported kind %q", mnt.Kind)
905 var stdout, stderr io.WriteCloser
906 if mnt, ok := runner.Container.Mounts["stdout"]; ok {
907 f, err := runner.getStdoutFile(mnt.Path)
912 } else if w, err := runner.NewLogWriter("stdout"); err != nil {
915 stdout = NewThrottledLogger(w)
918 if mnt, ok := runner.Container.Mounts["stderr"]; ok {
919 f, err := runner.getStdoutFile(mnt.Path)
924 } else if w, err := runner.NewLogWriter("stderr"); err != nil {
927 stderr = NewThrottledLogger(w)
930 env := runner.Container.Environment
931 enableNetwork := runner.enableNetwork == "always"
932 if runner.Container.RuntimeConstraints.API {
934 tok, err := runner.ContainerToken()
938 env = map[string]string{}
939 for k, v := range runner.Container.Environment {
942 env["ARVADOS_API_TOKEN"] = tok
943 env["ARVADOS_API_HOST"] = os.Getenv("ARVADOS_API_HOST")
944 env["ARVADOS_API_HOST_INSECURE"] = os.Getenv("ARVADOS_API_HOST_INSECURE")
946 workdir := runner.Container.Cwd
948 // both "" and "." mean default
951 ram := runner.Container.RuntimeConstraints.RAM
952 if !runner.enableMemoryLimit {
955 return runner.executor.Create(containerSpec{
957 VCPUs: runner.Container.RuntimeConstraints.VCPUs,
961 BindMounts: bindmounts,
962 Command: runner.Container.Command,
963 EnableNetwork: enableNetwork,
964 NetworkMode: runner.networkMode,
965 CgroupParent: runner.setCgroupParent,
972 // StartContainer starts the docker container created by CreateContainer.
973 func (runner *ContainerRunner) StartContainer() error {
974 runner.CrunchLog.Printf("Starting container")
975 runner.cStateLock.Lock()
976 defer runner.cStateLock.Unlock()
977 if runner.cCancelled {
980 err := runner.executor.Start()
983 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
984 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])
986 return fmt.Errorf("could not start container: %v%s", err, advice)
991 // WaitFinish waits for the container to terminate, capture the exit code, and
992 // close the stdout/stderr logging.
993 func (runner *ContainerRunner) WaitFinish() error {
994 runner.CrunchLog.Print("Waiting for container to finish")
995 var timeout <-chan time.Time
996 if s := runner.Container.SchedulingParameters.MaxRunTime; s > 0 {
997 timeout = time.After(time.Duration(s) * time.Second)
999 ctx, cancel := context.WithCancel(context.Background())
1004 runner.CrunchLog.Printf("maximum run time exceeded. Stopping container.")
1006 case <-runner.ArvMountExit:
1007 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
1012 exitcode, err := runner.executor.Wait(ctx)
1014 runner.checkBrokenNode(err)
1017 runner.ExitCode = &exitcode
1019 if runner.statReporter != nil {
1020 runner.statReporter.Stop()
1021 err = runner.statLogger.Close()
1023 runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
1029 func (runner *ContainerRunner) updateLogs() {
1030 ticker := time.NewTicker(crunchLogUpdatePeriod / 360)
1033 sigusr1 := make(chan os.Signal, 1)
1034 signal.Notify(sigusr1, syscall.SIGUSR1)
1035 defer signal.Stop(sigusr1)
1037 saveAtTime := time.Now().Add(crunchLogUpdatePeriod)
1038 saveAtSize := crunchLogUpdateSize
1044 saveAtTime = time.Now()
1046 runner.logMtx.Lock()
1047 done := runner.LogsPDH != nil
1048 runner.logMtx.Unlock()
1052 size := runner.LogCollection.Size()
1053 if size == savedSize || (time.Now().Before(saveAtTime) && size < saveAtSize) {
1056 saveAtTime = time.Now().Add(crunchLogUpdatePeriod)
1057 saveAtSize = runner.LogCollection.Size() + crunchLogUpdateSize
1058 saved, err := runner.saveLogCollection(false)
1060 runner.CrunchLog.Printf("error updating log collection: %s", err)
1064 var updated arvados.Container
1065 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1066 "container": arvadosclient.Dict{"log": saved.PortableDataHash},
1069 runner.CrunchLog.Printf("error updating container log to %s: %s", saved.PortableDataHash, err)
1077 // CaptureOutput saves data from the container's output directory if
1078 // needed, and updates the container output accordingly.
1079 func (runner *ContainerRunner) CaptureOutput(bindmounts map[string]bindmount) error {
1080 if runner.Container.RuntimeConstraints.API {
1081 // Output may have been set directly by the container, so
1082 // refresh the container record to check.
1083 err := runner.DispatcherArvClient.Get("containers", runner.Container.UUID,
1084 nil, &runner.Container)
1088 if runner.Container.Output != "" {
1089 // Container output is already set.
1090 runner.OutputPDH = &runner.Container.Output
1095 txt, err := (&copier{
1096 client: runner.containerClient,
1097 arvClient: runner.ContainerArvClient,
1098 keepClient: runner.ContainerKeepClient,
1099 hostOutputDir: runner.HostOutputDir,
1100 ctrOutputDir: runner.Container.OutputPath,
1101 bindmounts: bindmounts,
1102 mounts: runner.Container.Mounts,
1103 secretMounts: runner.SecretMounts,
1104 logger: runner.CrunchLog,
1109 if n := len(regexp.MustCompile(` [0-9a-f]+\+\S*\+R`).FindAllStringIndex(txt, -1)); n > 0 {
1110 runner.CrunchLog.Printf("Copying %d data blocks from remote input collections...", n)
1111 fs, err := (&arvados.Collection{ManifestText: txt}).FileSystem(runner.containerClient, runner.ContainerKeepClient)
1115 txt, err = fs.MarshalManifest(".")
1120 var resp arvados.Collection
1121 err = runner.ContainerArvClient.Create("collections", arvadosclient.Dict{
1122 "ensure_unique_name": true,
1123 "collection": arvadosclient.Dict{
1125 "name": "output for " + runner.Container.UUID,
1126 "manifest_text": txt,
1130 return fmt.Errorf("error creating output collection: %v", err)
1132 runner.OutputPDH = &resp.PortableDataHash
1136 func (runner *ContainerRunner) CleanupDirs() {
1137 if runner.ArvMount != nil {
1139 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1140 umount.Stdout = runner.CrunchLog
1141 umount.Stderr = runner.CrunchLog
1142 runner.CrunchLog.Printf("Running %v", umount.Args)
1143 umnterr := umount.Start()
1146 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1148 // If arv-mount --unmount gets stuck for any reason, we
1149 // don't want to wait for it forever. Do Wait() in a goroutine
1150 // so it doesn't block crunch-run.
1151 umountExit := make(chan error)
1153 mnterr := umount.Wait()
1155 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1157 umountExit <- mnterr
1160 for again := true; again; {
1166 case <-runner.ArvMountExit:
1168 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1169 runner.CrunchLog.Printf("Timed out waiting for unmount")
1171 umount.Process.Kill()
1173 runner.ArvMount.Process.Kill()
1179 if runner.ArvMountPoint != "" {
1180 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1181 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1185 if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1186 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1190 // CommitLogs posts the collection containing the final container logs.
1191 func (runner *ContainerRunner) CommitLogs() error {
1193 // Hold cStateLock to prevent races on CrunchLog (e.g., stop()).
1194 runner.cStateLock.Lock()
1195 defer runner.cStateLock.Unlock()
1197 runner.CrunchLog.Print(runner.finalState)
1199 if runner.arvMountLog != nil {
1200 runner.arvMountLog.Close()
1202 runner.CrunchLog.Close()
1204 // Closing CrunchLog above allows them to be committed to Keep at this
1205 // point, but re-open crunch log with ArvClient in case there are any
1206 // other further errors (such as failing to write the log to Keep!)
1207 // while shutting down
1208 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{
1209 ArvClient: runner.DispatcherArvClient,
1210 UUID: runner.Container.UUID,
1211 loggingStream: "crunch-run",
1214 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1217 if runner.LogsPDH != nil {
1218 // If we have already assigned something to LogsPDH,
1219 // we must be closing the re-opened log, which won't
1220 // end up getting attached to the container record and
1221 // therefore doesn't need to be saved as a collection
1222 // -- it exists only to send logs to other channels.
1225 saved, err := runner.saveLogCollection(true)
1227 return fmt.Errorf("error saving log collection: %s", err)
1229 runner.logMtx.Lock()
1230 defer runner.logMtx.Unlock()
1231 runner.LogsPDH = &saved.PortableDataHash
1235 func (runner *ContainerRunner) saveLogCollection(final bool) (response arvados.Collection, err error) {
1236 runner.logMtx.Lock()
1237 defer runner.logMtx.Unlock()
1238 if runner.LogsPDH != nil {
1239 // Already finalized.
1242 updates := arvadosclient.Dict{
1243 "name": "logs for " + runner.Container.UUID,
1245 mt, err1 := runner.LogCollection.MarshalManifest(".")
1247 // Only send updated manifest text if there was no
1249 updates["manifest_text"] = mt
1252 // Even if flushing the manifest had an error, we still want
1253 // to update the log record, if possible, to push the trash_at
1254 // and delete_at times into the future. Details on bug
1257 updates["is_trashed"] = true
1259 exp := time.Now().Add(crunchLogUpdatePeriod * 24)
1260 updates["trash_at"] = exp
1261 updates["delete_at"] = exp
1263 reqBody := arvadosclient.Dict{"collection": updates}
1265 if runner.logUUID == "" {
1266 reqBody["ensure_unique_name"] = true
1267 err2 = runner.DispatcherArvClient.Create("collections", reqBody, &response)
1269 err2 = runner.DispatcherArvClient.Update("collections", runner.logUUID, reqBody, &response)
1272 runner.logUUID = response.UUID
1275 if err1 != nil || err2 != nil {
1276 err = fmt.Errorf("error recording logs: %q, %q", err1, err2)
1281 // UpdateContainerRunning updates the container state to "Running"
1282 func (runner *ContainerRunner) UpdateContainerRunning() error {
1283 runner.cStateLock.Lock()
1284 defer runner.cStateLock.Unlock()
1285 if runner.cCancelled {
1288 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID,
1289 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running", "gateway_address": runner.gateway.Address}}, nil)
1292 // ContainerToken returns the api_token the container (and any
1293 // arv-mount processes) are allowed to use.
1294 func (runner *ContainerRunner) ContainerToken() (string, error) {
1295 if runner.token != "" {
1296 return runner.token, nil
1299 var auth arvados.APIClientAuthorization
1300 err := runner.DispatcherArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1304 runner.token = fmt.Sprintf("v2/%s/%s/%s", auth.UUID, auth.APIToken, runner.Container.UUID)
1305 return runner.token, nil
1308 // UpdateContainerFinal updates the container record state on API
1309 // server to "Complete" or "Cancelled"
1310 func (runner *ContainerRunner) UpdateContainerFinal() error {
1311 update := arvadosclient.Dict{}
1312 update["state"] = runner.finalState
1313 if runner.LogsPDH != nil {
1314 update["log"] = *runner.LogsPDH
1316 if runner.finalState == "Complete" {
1317 if runner.ExitCode != nil {
1318 update["exit_code"] = *runner.ExitCode
1320 if runner.OutputPDH != nil {
1321 update["output"] = *runner.OutputPDH
1324 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1327 // IsCancelled returns the value of Cancelled, with goroutine safety.
1328 func (runner *ContainerRunner) IsCancelled() bool {
1329 runner.cStateLock.Lock()
1330 defer runner.cStateLock.Unlock()
1331 return runner.cCancelled
1334 // NewArvLogWriter creates an ArvLogWriter
1335 func (runner *ContainerRunner) NewArvLogWriter(name string) (io.WriteCloser, error) {
1336 writer, err := runner.LogCollection.OpenFile(name+".txt", os.O_CREATE|os.O_WRONLY, 0666)
1340 return &ArvLogWriter{
1341 ArvClient: runner.DispatcherArvClient,
1342 UUID: runner.Container.UUID,
1343 loggingStream: name,
1344 writeCloser: writer,
1348 // Run the full container lifecycle.
1349 func (runner *ContainerRunner) Run() (err error) {
1350 runner.CrunchLog.Printf("crunch-run %s started", cmd.Version.String())
1351 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1353 hostname, hosterr := os.Hostname()
1355 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1357 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1360 runner.finalState = "Queued"
1363 runner.CleanupDirs()
1365 runner.CrunchLog.Printf("crunch-run finished")
1366 runner.CrunchLog.Close()
1369 err = runner.fetchContainerRecord()
1373 if runner.Container.State != "Locked" {
1374 return fmt.Errorf("dispatch error detected: container %q has state %q", runner.Container.UUID, runner.Container.State)
1377 var bindmounts map[string]bindmount
1379 // checkErr prints e (unless it's nil) and sets err to
1380 // e (unless err is already non-nil). Thus, if err
1381 // hasn't already been assigned when Run() returns,
1382 // this cleanup func will cause Run() to return the
1383 // first non-nil error that is passed to checkErr().
1384 checkErr := func(errorIn string, e error) {
1388 runner.CrunchLog.Printf("error in %s: %v", errorIn, e)
1392 if runner.finalState == "Complete" {
1393 // There was an error in the finalization.
1394 runner.finalState = "Cancelled"
1398 // Log the error encountered in Run(), if any
1399 checkErr("Run", err)
1401 if runner.finalState == "Queued" {
1402 runner.UpdateContainerFinal()
1406 if runner.IsCancelled() {
1407 runner.finalState = "Cancelled"
1408 // but don't return yet -- we still want to
1409 // capture partial output and write logs
1412 if bindmounts != nil {
1413 checkErr("CaptureOutput", runner.CaptureOutput(bindmounts))
1415 checkErr("stopHoststat", runner.stopHoststat())
1416 checkErr("CommitLogs", runner.CommitLogs())
1417 checkErr("UpdateContainerFinal", runner.UpdateContainerFinal())
1420 runner.setupSignals()
1421 err = runner.startHoststat()
1426 // set up FUSE mount and binds
1427 bindmounts, err = runner.SetupMounts()
1429 runner.finalState = "Cancelled"
1430 err = fmt.Errorf("While setting up mounts: %v", err)
1434 // check for and/or load image
1435 imageID, err := runner.LoadImage()
1437 if !runner.checkBrokenNode(err) {
1438 // Failed to load image but not due to a "broken node"
1439 // condition, probably user error.
1440 runner.finalState = "Cancelled"
1442 err = fmt.Errorf("While loading container image: %v", err)
1446 err = runner.CreateContainer(imageID, bindmounts)
1450 err = runner.LogHostInfo()
1454 err = runner.LogNodeRecord()
1458 err = runner.LogContainerRecord()
1463 if runner.IsCancelled() {
1467 err = runner.UpdateContainerRunning()
1471 runner.finalState = "Cancelled"
1473 err = runner.startCrunchstat()
1478 err = runner.StartContainer()
1480 runner.checkBrokenNode(err)
1484 err = runner.WaitFinish()
1485 if err == nil && !runner.IsCancelled() {
1486 runner.finalState = "Complete"
1491 // Fetch the current container record (uuid = runner.Container.UUID)
1492 // into runner.Container.
1493 func (runner *ContainerRunner) fetchContainerRecord() error {
1494 reader, err := runner.DispatcherArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1496 return fmt.Errorf("error fetching container record: %v", err)
1498 defer reader.Close()
1500 dec := json.NewDecoder(reader)
1502 err = dec.Decode(&runner.Container)
1504 return fmt.Errorf("error decoding container record: %v", err)
1508 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
1511 containerToken, err := runner.ContainerToken()
1513 return fmt.Errorf("error getting container token: %v", err)
1516 runner.ContainerArvClient, runner.ContainerKeepClient,
1517 runner.containerClient, err = runner.MkArvClient(containerToken)
1519 return fmt.Errorf("error creating container API client: %v", err)
1522 err = runner.ContainerArvClient.Call("GET", "containers", runner.Container.UUID, "secret_mounts", nil, &sm)
1524 if apierr, ok := err.(arvadosclient.APIServerError); !ok || apierr.HttpStatusCode != 404 {
1525 return fmt.Errorf("error fetching secret_mounts: %v", err)
1527 // ok && apierr.HttpStatusCode == 404, which means
1528 // secret_mounts isn't supported by this API server.
1530 runner.SecretMounts = sm.SecretMounts
1535 // NewContainerRunner creates a new container runner.
1536 func NewContainerRunner(dispatcherClient *arvados.Client,
1537 dispatcherArvClient IArvadosClient,
1538 dispatcherKeepClient IKeepClient,
1539 containerUUID string) (*ContainerRunner, error) {
1541 cr := &ContainerRunner{
1542 dispatcherClient: dispatcherClient,
1543 DispatcherArvClient: dispatcherArvClient,
1544 DispatcherKeepClient: dispatcherKeepClient,
1546 cr.NewLogWriter = cr.NewArvLogWriter
1547 cr.RunArvMount = cr.ArvMountCmd
1548 cr.MkTempDir = ioutil.TempDir
1549 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1550 cl, err := arvadosclient.MakeArvadosClient()
1552 return nil, nil, nil, err
1555 kc, err := keepclient.MakeKeepClient(cl)
1557 return nil, nil, nil, err
1559 c2 := arvados.NewClientFromEnv()
1560 c2.AuthToken = token
1561 return cl, kc, c2, nil
1564 cr.LogCollection, err = (&arvados.Collection{}).FileSystem(cr.dispatcherClient, cr.DispatcherKeepClient)
1568 cr.Container.UUID = containerUUID
1569 w, err := cr.NewLogWriter("crunch-run")
1573 cr.CrunchLog = NewThrottledLogger(w)
1574 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1576 loadLogThrottleParams(dispatcherArvClient)
1582 func (command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
1583 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
1584 statInterval := flags.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1585 cgroupRoot := flags.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1586 cgroupParent := flags.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1587 cgroupParentSubsystem := flags.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1588 caCertsPath := flags.String("ca-certs", "", "Path to TLS root certificates")
1589 detach := flags.Bool("detach", false, "Detach from parent process and run in the background")
1590 stdinEnv := flags.Bool("stdin-env", false, "Load environment variables from JSON message on stdin")
1591 sleep := flags.Duration("sleep", 0, "Delay before starting (testing use only)")
1592 kill := flags.Int("kill", -1, "Send signal to an existing crunch-run process for given UUID")
1593 list := flags.Bool("list", false, "List UUIDs of existing crunch-run processes")
1594 enableMemoryLimit := flags.Bool("enable-memory-limit", true, "tell container runtime to limit container's memory usage")
1595 enableNetwork := flags.String("container-enable-networking", "default", "enable networking \"always\" (for all containers) or \"default\" (for containers that request it)")
1596 networkMode := flags.String("container-network-mode", "default", `Docker network mode for container (use any argument valid for docker --net)`)
1597 memprofile := flags.String("memprofile", "", "write memory profile to `file` after running container")
1598 runtimeEngine := flags.String("runtime-engine", "docker", "container runtime: docker or singularity")
1599 flags.Duration("check-containerd", 0, "Ignored. Exists for compatibility with older versions.")
1601 ignoreDetachFlag := false
1602 if len(args) > 0 && args[0] == "-no-detach" {
1603 // This process was invoked by a parent process, which
1604 // has passed along its own arguments, including
1605 // -detach, after the leading -no-detach flag. Strip
1606 // the leading -no-detach flag (it's not recognized by
1607 // flags.Parse()) and ignore the -detach flag that
1610 ignoreDetachFlag = true
1613 if err := flags.Parse(args); err == flag.ErrHelp {
1615 } else if err != nil {
1620 if *stdinEnv && !ignoreDetachFlag {
1621 // Load env vars on stdin if asked (but not in a
1622 // detached child process, in which case stdin is
1624 err := loadEnv(os.Stdin)
1631 containerUUID := flags.Arg(0)
1634 case *detach && !ignoreDetachFlag:
1635 return Detach(containerUUID, prog, args, os.Stdout, os.Stderr)
1637 return KillProcess(containerUUID, syscall.Signal(*kill), os.Stdout, os.Stderr)
1639 return ListProcesses(os.Stdout, os.Stderr)
1642 if containerUUID == "" {
1643 log.Printf("usage: %s [options] UUID", prog)
1647 log.Printf("crunch-run %s started", cmd.Version.String())
1650 if *caCertsPath != "" {
1651 arvadosclient.CertFiles = []string{*caCertsPath}
1654 api, err := arvadosclient.MakeArvadosClient()
1656 log.Printf("%s: %v", containerUUID, err)
1661 kc, kcerr := keepclient.MakeKeepClient(api)
1663 log.Printf("%s: %v", containerUUID, kcerr)
1666 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1669 cr, err := NewContainerRunner(arvados.NewClientFromEnv(), api, kc, containerUUID)
1675 switch *runtimeEngine {
1677 cr.executor, err = newDockerExecutor(containerUUID, cr.CrunchLog.Printf, cr.containerWatchdogInterval)
1679 cr.executor, err = newSingularityExecutor(cr.CrunchLog.Printf)
1681 cr.CrunchLog.Printf("%s: unsupported RuntimeEngine %q", containerUUID, *runtimeEngine)
1682 cr.CrunchLog.Close()
1686 cr.CrunchLog.Printf("%s: %v", containerUUID, err)
1687 cr.checkBrokenNode(err)
1688 cr.CrunchLog.Close()
1691 defer cr.executor.Close()
1693 gwAuthSecret := os.Getenv("GatewayAuthSecret")
1694 os.Unsetenv("GatewayAuthSecret")
1695 if gwAuthSecret == "" {
1696 // not safe to run a gateway service without an auth
1698 } else if gwListen := os.Getenv("GatewayAddress"); gwListen == "" {
1699 // dispatcher did not tell us which external IP
1700 // address to advertise --> no gateway service
1701 } else if de, ok := cr.executor.(*dockerExecutor); ok {
1702 cr.gateway = Gateway{
1704 AuthSecret: gwAuthSecret,
1705 ContainerUUID: containerUUID,
1706 DockerContainerID: &de.containerID,
1708 ContainerIPAddress: dockerContainerIPAddress(&de.containerID),
1710 err = cr.gateway.Start()
1712 log.Printf("error starting gateway server: %s", err)
1717 parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerUUID+".")
1719 log.Printf("%s: %v", containerUUID, tmperr)
1723 cr.parentTemp = parentTemp
1724 cr.statInterval = *statInterval
1725 cr.cgroupRoot = *cgroupRoot
1726 cr.expectCgroupParent = *cgroupParent
1727 cr.enableMemoryLimit = *enableMemoryLimit
1728 cr.enableNetwork = *enableNetwork
1729 cr.networkMode = *networkMode
1730 if *cgroupParentSubsystem != "" {
1731 p := findCgroup(*cgroupParentSubsystem)
1732 cr.setCgroupParent = p
1733 cr.expectCgroupParent = p
1738 if *memprofile != "" {
1739 f, err := os.Create(*memprofile)
1741 log.Printf("could not create memory profile: %s", err)
1743 runtime.GC() // get up-to-date statistics
1744 if err := pprof.WriteHeapProfile(f); err != nil {
1745 log.Printf("could not write memory profile: %s", err)
1747 closeerr := f.Close()
1748 if closeerr != nil {
1749 log.Printf("closing memprofile file: %s", err)
1754 log.Printf("%s: %v", containerUUID, runerr)
1760 func loadEnv(rdr io.Reader) error {
1761 buf, err := ioutil.ReadAll(rdr)
1763 return fmt.Errorf("read stdin: %s", err)
1765 var env map[string]string
1766 err = json.Unmarshal(buf, &env)
1768 return fmt.Errorf("decode stdin: %s", err)
1770 for k, v := range env {
1771 err = os.Setenv(k, v)
1773 return fmt.Errorf("setenv(%q): %s", k, err)