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(args []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
82 // Dispatcher client is initialized with the Dispatcher token.
83 // This is a privileged token used to manage container status
86 // We have both dispatcherClient and DispatcherArvClient
87 // because there are two different incompatible Arvados Go
88 // SDKs and we have to use both (hopefully this gets fixed in
90 dispatcherClient *arvados.Client
91 DispatcherArvClient IArvadosClient
92 DispatcherKeepClient IKeepClient
94 // Container client is initialized with the Container token
95 // This token controls the permissions of the container, and
96 // must be used for operations such as reading collections.
98 // Same comment as above applies to
99 // containerClient/ContainerArvClient.
100 containerClient *arvados.Client
101 ContainerArvClient IArvadosClient
102 ContainerKeepClient IKeepClient
104 Container arvados.Container
107 NewLogWriter NewLogWriter
108 CrunchLog *ThrottledLogger
109 Stdout io.WriteCloser
110 Stderr io.WriteCloser
113 LogCollection arvados.CollectionFileSystem
115 RunArvMount RunArvMount
120 Volumes map[string]struct{}
122 SigChan chan os.Signal
123 ArvMountExit chan error
124 SecretMounts map[string]arvados.Mount
125 MkArvClient func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error)
129 statLogger io.WriteCloser
130 statReporter *crunchstat.Reporter
131 hoststatLogger io.WriteCloser
132 hoststatReporter *crunchstat.Reporter
133 statInterval time.Duration
135 // What we expect the container's cgroup parent to be.
136 expectCgroupParent string
137 // What we tell docker to use as the container's cgroup
138 // parent. Note: Ideally we would use the same field for both
139 // expectCgroupParent and setCgroupParent, and just make it
140 // default to "docker". However, when using docker < 1.10 with
141 // systemd, specifying a non-empty cgroup parent (even the
142 // default value "docker") hits a docker bug
143 // (https://github.com/docker/docker/issues/17126). Using two
144 // separate fields makes it possible to use the "expect cgroup
145 // parent to be X" feature even on sites where the "specify
146 // cgroup parent" feature breaks.
147 setCgroupParent string
149 cStateLock sync.Mutex
150 cCancelled bool // StopContainer() invoked
152 enableMemoryLimit bool
153 enableNetwork string // one of "default" or "always"
154 networkMode string // "none", "host", or "" -- passed through to executor
155 arvMountLog *ThrottledLogger
157 containerWatchdogInterval time.Duration
162 // setupSignals sets up signal handling to gracefully terminate the
163 // underlying container and update state when receiving a TERM, INT or
165 func (runner *ContainerRunner) setupSignals() {
166 runner.SigChan = make(chan os.Signal, 1)
167 signal.Notify(runner.SigChan, syscall.SIGTERM)
168 signal.Notify(runner.SigChan, syscall.SIGINT)
169 signal.Notify(runner.SigChan, syscall.SIGQUIT)
171 go func(sig chan os.Signal) {
178 // stop the underlying container.
179 func (runner *ContainerRunner) stop(sig os.Signal) {
180 runner.cStateLock.Lock()
181 defer runner.cStateLock.Unlock()
183 runner.CrunchLog.Printf("caught signal: %v", sig)
185 runner.cCancelled = true
186 runner.CrunchLog.Printf("stopping container")
187 err := runner.executor.Stop()
189 runner.CrunchLog.Printf("error stopping container: %s", err)
193 var errorBlacklist = []string{
194 "(?ms).*[Cc]annot connect to the Docker daemon.*",
195 "(?ms).*oci runtime error.*starting container process.*container init.*mounting.*to rootfs.*no such file or directory.*",
196 "(?ms).*grpc: the connection is unavailable.*",
198 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)")
200 func (runner *ContainerRunner) runBrokenNodeHook() {
201 if *brokenNodeHook == "" {
202 path := filepath.Join(lockdir, brokenfile)
203 runner.CrunchLog.Printf("Writing %s to mark node as broken", path)
204 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0700)
206 runner.CrunchLog.Printf("Error writing %s: %s", path, err)
211 runner.CrunchLog.Printf("Running broken node hook %q", *brokenNodeHook)
213 c := exec.Command(*brokenNodeHook)
214 c.Stdout = runner.CrunchLog
215 c.Stderr = runner.CrunchLog
218 runner.CrunchLog.Printf("Error running broken node hook: %v", err)
223 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
224 for _, d := range errorBlacklist {
225 if m, e := regexp.MatchString(d, goterr.Error()); m && e == nil {
226 runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
227 runner.runBrokenNodeHook()
234 // LoadImage determines the docker image id from the container record and
235 // checks if it is available in the local Docker image store. If not, it loads
236 // the image from Keep.
237 func (runner *ContainerRunner) LoadImage() (string, error) {
238 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
240 d, err := os.Open(runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage)
245 allfiles, err := d.Readdirnames(-1)
249 var tarfiles []string
250 for _, fnm := range allfiles {
251 if strings.HasSuffix(fnm, ".tar") {
252 tarfiles = append(tarfiles, fnm)
255 if len(tarfiles) == 0 {
256 return "", fmt.Errorf("image collection does not include a .tar image file")
258 if len(tarfiles) > 1 {
259 return "", fmt.Errorf("cannot choose from multiple tar files in image collection: %v", tarfiles)
261 imageID := tarfiles[0][:len(tarfiles[0])-4]
262 imageFile := runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage + "/" + tarfiles[0]
263 runner.CrunchLog.Printf("Using Docker image id %q", imageID)
265 if !runner.executor.ImageLoaded(imageID) {
266 runner.CrunchLog.Print("Loading Docker image from keep")
267 err = runner.executor.LoadImage(imageFile)
272 runner.CrunchLog.Print("Docker image is available")
277 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
278 c = exec.Command("arv-mount", arvMountCmd...)
280 // Copy our environment, but override ARVADOS_API_TOKEN with
281 // the container auth token.
283 for _, s := range os.Environ() {
284 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
285 c.Env = append(c.Env, s)
288 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
290 w, err := runner.NewLogWriter("arv-mount")
294 runner.arvMountLog = NewThrottledLogger(w)
295 c.Stdout = runner.arvMountLog
296 c.Stderr = io.MultiWriter(runner.arvMountLog, os.Stderr)
298 runner.CrunchLog.Printf("Running %v", c.Args)
305 statReadme := make(chan bool)
306 runner.ArvMountExit = make(chan error)
311 time.Sleep(100 * time.Millisecond)
312 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
324 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
326 runner.ArvMountExit <- mnterr
327 close(runner.ArvMountExit)
333 case err := <-runner.ArvMountExit:
334 runner.ArvMount = nil
342 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
343 if runner.ArvMountPoint == "" {
344 runner.ArvMountPoint, err = runner.MkTempDir(runner.parentTemp, prefix)
349 func copyfile(src string, dst string) (err error) {
350 srcfile, err := os.Open(src)
355 os.MkdirAll(path.Dir(dst), 0777)
357 dstfile, err := os.Create(dst)
361 _, err = io.Copy(dstfile, srcfile)
366 err = srcfile.Close()
367 err2 := dstfile.Close()
380 func (runner *ContainerRunner) SetupMounts() (map[string]bindmount, error) {
381 bindmounts := map[string]bindmount{}
382 err := runner.SetupArvMountPoint("keep")
384 return nil, fmt.Errorf("While creating keep mount temp dir: %v", err)
387 token, err := runner.ContainerToken()
389 return nil, fmt.Errorf("could not get container token: %s", err)
391 runner.CrunchLog.Printf("container token %q", token)
395 arvMountCmd := []string{
399 "--storage-classes", strings.Join(runner.Container.OutputStorageClasses, ","),
400 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
402 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
403 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
406 collectionPaths := []string{}
407 needCertMount := true
408 type copyFile struct {
412 var copyFiles []copyFile
415 for bind := range runner.Container.Mounts {
416 binds = append(binds, bind)
418 for bind := range runner.SecretMounts {
419 if _, ok := runner.Container.Mounts[bind]; ok {
420 return nil, fmt.Errorf("secret mount %q conflicts with regular mount", bind)
422 if runner.SecretMounts[bind].Kind != "json" &&
423 runner.SecretMounts[bind].Kind != "text" {
424 return nil, fmt.Errorf("secret mount %q type is %q but only 'json' and 'text' are permitted",
425 bind, runner.SecretMounts[bind].Kind)
427 binds = append(binds, bind)
431 for _, bind := range binds {
432 mnt, ok := runner.Container.Mounts[bind]
434 mnt = runner.SecretMounts[bind]
436 if bind == "stdout" || bind == "stderr" {
437 // Is it a "file" mount kind?
438 if mnt.Kind != "file" {
439 return nil, fmt.Errorf("unsupported mount kind '%s' for %s: only 'file' is supported", mnt.Kind, bind)
442 // Does path start with OutputPath?
443 prefix := runner.Container.OutputPath
444 if !strings.HasSuffix(prefix, "/") {
447 if !strings.HasPrefix(mnt.Path, prefix) {
448 return nil, fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
453 // Is it a "collection" mount kind?
454 if mnt.Kind != "collection" && mnt.Kind != "json" {
455 return nil, fmt.Errorf("unsupported mount kind '%s' for stdin: only 'collection' and 'json' are supported", mnt.Kind)
459 if bind == "/etc/arvados/ca-certificates.crt" {
460 needCertMount = false
463 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
464 if mnt.Kind != "collection" && mnt.Kind != "text" && mnt.Kind != "json" {
465 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)
470 case mnt.Kind == "collection" && bind != "stdin":
472 if mnt.UUID != "" && mnt.PortableDataHash != "" {
473 return nil, fmt.Errorf("cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
477 return nil, fmt.Errorf("writing to existing collections currently not permitted")
480 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
481 } else if mnt.PortableDataHash != "" {
482 if mnt.Writable && !strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
483 return nil, fmt.Errorf("can never write to a collection specified by portable data hash")
485 idx := strings.Index(mnt.PortableDataHash, "/")
487 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
488 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
489 runner.Container.Mounts[bind] = mnt
491 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
492 if mnt.Path != "" && mnt.Path != "." {
493 if strings.HasPrefix(mnt.Path, "./") {
494 mnt.Path = mnt.Path[2:]
495 } else if strings.HasPrefix(mnt.Path, "/") {
496 mnt.Path = mnt.Path[1:]
498 src += "/" + mnt.Path
501 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
502 arvMountCmd = append(arvMountCmd, "--mount-tmp")
503 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
507 if bind == runner.Container.OutputPath {
508 runner.HostOutputDir = src
509 bindmounts[bind] = bindmount{HostPath: src}
510 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
511 copyFiles = append(copyFiles, copyFile{src, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
513 bindmounts[bind] = bindmount{HostPath: src}
516 bindmounts[bind] = bindmount{HostPath: src, ReadOnly: true}
518 collectionPaths = append(collectionPaths, src)
520 case mnt.Kind == "tmp":
522 tmpdir, err = runner.MkTempDir(runner.parentTemp, "tmp")
524 return nil, fmt.Errorf("while creating mount temp dir: %v", err)
526 st, staterr := os.Stat(tmpdir)
528 return nil, fmt.Errorf("while Stat on temp dir: %v", staterr)
530 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
532 return nil, fmt.Errorf("while Chmod temp dir: %v", err)
534 bindmounts[bind] = bindmount{HostPath: tmpdir}
535 if bind == runner.Container.OutputPath {
536 runner.HostOutputDir = tmpdir
539 case mnt.Kind == "json" || mnt.Kind == "text":
541 if mnt.Kind == "json" {
542 filedata, err = json.Marshal(mnt.Content)
544 return nil, fmt.Errorf("encoding json data: %v", err)
547 text, ok := mnt.Content.(string)
549 return nil, fmt.Errorf("content for mount %q must be a string", bind)
551 filedata = []byte(text)
554 tmpdir, err := runner.MkTempDir(runner.parentTemp, mnt.Kind)
556 return nil, fmt.Errorf("creating temp dir: %v", err)
558 tmpfn := filepath.Join(tmpdir, "mountdata."+mnt.Kind)
559 err = ioutil.WriteFile(tmpfn, filedata, 0444)
561 return nil, fmt.Errorf("writing temp file: %v", err)
563 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
564 copyFiles = append(copyFiles, copyFile{tmpfn, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
566 bindmounts[bind] = bindmount{HostPath: tmpfn, ReadOnly: true}
569 case mnt.Kind == "git_tree":
570 tmpdir, err := runner.MkTempDir(runner.parentTemp, "git_tree")
572 return nil, fmt.Errorf("creating temp dir: %v", err)
574 err = gitMount(mnt).extractTree(runner.ContainerArvClient, tmpdir, token)
578 bindmounts[bind] = bindmount{HostPath: tmpdir, ReadOnly: true}
582 if runner.HostOutputDir == "" {
583 return nil, fmt.Errorf("output path does not correspond to a writable mount point")
586 if needCertMount && runner.Container.RuntimeConstraints.API {
587 for _, certfile := range arvadosclient.CertFiles {
588 _, err := os.Stat(certfile)
590 bindmounts["/etc/arvados/ca-certificates.crt"] = bindmount{HostPath: certfile, ReadOnly: true}
597 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
599 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
601 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
603 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
605 return nil, fmt.Errorf("while trying to start arv-mount: %v", err)
608 for _, p := range collectionPaths {
611 return nil, fmt.Errorf("while checking that input files exist: %v", err)
615 for _, cp := range copyFiles {
616 st, err := os.Stat(cp.src)
618 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
621 err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
625 target := path.Join(cp.bind, walkpath[len(cp.src):])
626 if walkinfo.Mode().IsRegular() {
627 copyerr := copyfile(walkpath, target)
631 return os.Chmod(target, walkinfo.Mode()|0777)
632 } else if walkinfo.Mode().IsDir() {
633 mkerr := os.MkdirAll(target, 0777)
637 return os.Chmod(target, walkinfo.Mode()|os.ModeSetgid|0777)
639 return fmt.Errorf("source %q is not a regular file or directory", cp.src)
642 } else if st.Mode().IsRegular() {
643 err = copyfile(cp.src, cp.bind)
645 err = os.Chmod(cp.bind, st.Mode()|0777)
649 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
653 return bindmounts, nil
656 func (runner *ContainerRunner) stopHoststat() error {
657 if runner.hoststatReporter == nil {
660 runner.hoststatReporter.Stop()
661 err := runner.hoststatLogger.Close()
663 return fmt.Errorf("error closing hoststat logs: %v", err)
668 func (runner *ContainerRunner) startHoststat() error {
669 w, err := runner.NewLogWriter("hoststat")
673 runner.hoststatLogger = NewThrottledLogger(w)
674 runner.hoststatReporter = &crunchstat.Reporter{
675 Logger: log.New(runner.hoststatLogger, "", 0),
676 CgroupRoot: runner.cgroupRoot,
677 PollPeriod: runner.statInterval,
679 runner.hoststatReporter.Start()
683 func (runner *ContainerRunner) startCrunchstat() error {
684 w, err := runner.NewLogWriter("crunchstat")
688 runner.statLogger = NewThrottledLogger(w)
689 runner.statReporter = &crunchstat.Reporter{
690 CID: runner.executor.CgroupID(),
691 Logger: log.New(runner.statLogger, "", 0),
692 CgroupParent: runner.expectCgroupParent,
693 CgroupRoot: runner.cgroupRoot,
694 PollPeriod: runner.statInterval,
695 TempDir: runner.parentTemp,
697 runner.statReporter.Start()
701 type infoCommand struct {
706 // LogHostInfo logs info about the current host, for debugging and
707 // accounting purposes. Although it's logged as "node-info", this is
708 // about the environment where crunch-run is actually running, which
709 // might differ from what's described in the node record (see
711 func (runner *ContainerRunner) LogHostInfo() (err error) {
712 w, err := runner.NewLogWriter("node-info")
717 commands := []infoCommand{
719 label: "Host Information",
720 cmd: []string{"uname", "-a"},
723 label: "CPU Information",
724 cmd: []string{"cat", "/proc/cpuinfo"},
727 label: "Memory Information",
728 cmd: []string{"cat", "/proc/meminfo"},
732 cmd: []string{"df", "-m", "/", os.TempDir()},
735 label: "Disk INodes",
736 cmd: []string{"df", "-i", "/", os.TempDir()},
740 // Run commands with informational output to be logged.
741 for _, command := range commands {
742 fmt.Fprintln(w, command.label)
743 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
746 if err := cmd.Run(); err != nil {
747 err = fmt.Errorf("While running command %q: %v", command.cmd, err)
756 return fmt.Errorf("While closing node-info logs: %v", err)
761 // LogContainerRecord gets and saves the raw JSON container record from the API server
762 func (runner *ContainerRunner) LogContainerRecord() error {
763 logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
764 if !logged && err == nil {
765 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
770 // LogNodeRecord logs the current host's InstanceType config entry (or
771 // the arvados#node record, if running via crunch-dispatch-slurm).
772 func (runner *ContainerRunner) LogNodeRecord() error {
773 if it := os.Getenv("InstanceType"); it != "" {
774 // Dispatched via arvados-dispatch-cloud. Save
775 // InstanceType config fragment received from
776 // dispatcher on stdin.
777 w, err := runner.LogCollection.OpenFile("node.json", os.O_CREATE|os.O_WRONLY, 0666)
782 _, err = io.WriteString(w, it)
788 // Dispatched via crunch-dispatch-slurm. Look up
789 // apiserver's node record corresponding to
791 hostname := os.Getenv("SLURMD_NODENAME")
793 hostname, _ = os.Hostname()
795 _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
796 // The "info" field has admin-only info when
797 // obtained with a privileged token, and
798 // should not be logged.
799 node, ok := resp.(map[string]interface{})
807 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
808 writer, err := runner.LogCollection.OpenFile(label+".json", os.O_CREATE|os.O_WRONLY, 0666)
813 ArvClient: runner.DispatcherArvClient,
814 UUID: runner.Container.UUID,
815 loggingStream: label,
819 reader, err := runner.DispatcherArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
821 return false, fmt.Errorf("error getting %s record: %v", label, err)
825 dec := json.NewDecoder(reader)
827 var resp map[string]interface{}
828 if err = dec.Decode(&resp); err != nil {
829 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
831 items, ok := resp["items"].([]interface{})
833 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
834 } else if len(items) < 1 {
840 // Re-encode it using indentation to improve readability
841 enc := json.NewEncoder(w)
842 enc.SetIndent("", " ")
843 if err = enc.Encode(items[0]); err != nil {
844 return false, fmt.Errorf("error logging %s record: %v", label, err)
848 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
853 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
854 stdoutPath := mntPath[len(runner.Container.OutputPath):]
855 index := strings.LastIndex(stdoutPath, "/")
857 subdirs := stdoutPath[:index]
859 st, err := os.Stat(runner.HostOutputDir)
861 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
863 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
864 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
866 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
870 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
872 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
875 return stdoutFile, nil
878 // CreateContainer creates the docker container.
879 func (runner *ContainerRunner) CreateContainer(imageID string, bindmounts map[string]bindmount) error {
880 var stdin io.ReadCloser
881 if mnt, ok := runner.Container.Mounts["stdin"]; ok {
888 collID = mnt.PortableDataHash
890 path := runner.ArvMountPoint + "/by_id/" + collID + "/" + mnt.Path
891 f, err := os.Open(path)
897 j, err := json.Marshal(mnt.Content)
899 return fmt.Errorf("error encoding stdin json data: %v", err)
901 stdin = ioutil.NopCloser(bytes.NewReader(j))
903 return fmt.Errorf("stdin mount has unsupported kind %q", mnt.Kind)
907 var stdout, stderr io.WriteCloser
908 if mnt, ok := runner.Container.Mounts["stdout"]; ok {
909 f, err := runner.getStdoutFile(mnt.Path)
914 } else if w, err := runner.NewLogWriter("stdout"); err != nil {
917 stdout = NewThrottledLogger(w)
920 if mnt, ok := runner.Container.Mounts["stderr"]; ok {
921 f, err := runner.getStdoutFile(mnt.Path)
926 } else if w, err := runner.NewLogWriter("stderr"); err != nil {
929 stderr = NewThrottledLogger(w)
932 env := runner.Container.Environment
933 enableNetwork := runner.enableNetwork == "always"
934 if runner.Container.RuntimeConstraints.API {
936 tok, err := runner.ContainerToken()
940 env = map[string]string{}
941 for k, v := range runner.Container.Environment {
944 env["ARVADOS_API_TOKEN"] = tok
945 env["ARVADOS_API_HOST"] = os.Getenv("ARVADOS_API_HOST")
946 env["ARVADOS_API_HOST_INSECURE"] = os.Getenv("ARVADOS_API_HOST_INSECURE")
948 workdir := runner.Container.Cwd
950 // both "" and "." mean default
953 ram := runner.Container.RuntimeConstraints.RAM
954 if !runner.enableMemoryLimit {
957 return runner.executor.Create(containerSpec{
959 VCPUs: runner.Container.RuntimeConstraints.VCPUs,
963 BindMounts: bindmounts,
964 Command: runner.Container.Command,
965 EnableNetwork: enableNetwork,
966 NetworkMode: runner.networkMode,
967 CgroupParent: runner.setCgroupParent,
974 // StartContainer starts the docker container created by CreateContainer.
975 func (runner *ContainerRunner) StartContainer() error {
976 runner.CrunchLog.Printf("Starting container")
977 runner.cStateLock.Lock()
978 defer runner.cStateLock.Unlock()
979 if runner.cCancelled {
982 err := runner.executor.Start()
985 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
986 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])
988 return fmt.Errorf("could not start container: %v%s", err, advice)
993 // WaitFinish waits for the container to terminate, capture the exit code, and
994 // close the stdout/stderr logging.
995 func (runner *ContainerRunner) WaitFinish() error {
996 runner.CrunchLog.Print("Waiting for container to finish")
997 var timeout <-chan time.Time
998 if s := runner.Container.SchedulingParameters.MaxRunTime; s > 0 {
999 timeout = time.After(time.Duration(s) * time.Second)
1001 ctx, cancel := context.WithCancel(context.Background())
1006 runner.CrunchLog.Printf("maximum run time exceeded. Stopping container.")
1008 case <-runner.ArvMountExit:
1009 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
1014 exitcode, err := runner.executor.Wait(ctx)
1016 runner.checkBrokenNode(err)
1019 runner.ExitCode = &exitcode
1021 if runner.statReporter != nil {
1022 runner.statReporter.Stop()
1023 err = runner.statLogger.Close()
1025 runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
1031 func (runner *ContainerRunner) updateLogs() {
1032 ticker := time.NewTicker(crunchLogUpdatePeriod / 360)
1035 sigusr1 := make(chan os.Signal, 1)
1036 signal.Notify(sigusr1, syscall.SIGUSR1)
1037 defer signal.Stop(sigusr1)
1039 saveAtTime := time.Now().Add(crunchLogUpdatePeriod)
1040 saveAtSize := crunchLogUpdateSize
1046 saveAtTime = time.Now()
1048 runner.logMtx.Lock()
1049 done := runner.LogsPDH != nil
1050 runner.logMtx.Unlock()
1054 size := runner.LogCollection.Size()
1055 if size == savedSize || (time.Now().Before(saveAtTime) && size < saveAtSize) {
1058 saveAtTime = time.Now().Add(crunchLogUpdatePeriod)
1059 saveAtSize = runner.LogCollection.Size() + crunchLogUpdateSize
1060 saved, err := runner.saveLogCollection(false)
1062 runner.CrunchLog.Printf("error updating log collection: %s", err)
1066 var updated arvados.Container
1067 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1068 "container": arvadosclient.Dict{"log": saved.PortableDataHash},
1071 runner.CrunchLog.Printf("error updating container log to %s: %s", saved.PortableDataHash, err)
1079 // CaptureOutput saves data from the container's output directory if
1080 // needed, and updates the container output accordingly.
1081 func (runner *ContainerRunner) CaptureOutput(bindmounts map[string]bindmount) error {
1082 if runner.Container.RuntimeConstraints.API {
1083 // Output may have been set directly by the container, so
1084 // refresh the container record to check.
1085 err := runner.DispatcherArvClient.Get("containers", runner.Container.UUID,
1086 nil, &runner.Container)
1090 if runner.Container.Output != "" {
1091 // Container output is already set.
1092 runner.OutputPDH = &runner.Container.Output
1097 txt, err := (&copier{
1098 client: runner.containerClient,
1099 arvClient: runner.ContainerArvClient,
1100 keepClient: runner.ContainerKeepClient,
1101 hostOutputDir: runner.HostOutputDir,
1102 ctrOutputDir: runner.Container.OutputPath,
1103 bindmounts: bindmounts,
1104 mounts: runner.Container.Mounts,
1105 secretMounts: runner.SecretMounts,
1106 logger: runner.CrunchLog,
1111 if n := len(regexp.MustCompile(` [0-9a-f]+\+\S*\+R`).FindAllStringIndex(txt, -1)); n > 0 {
1112 runner.CrunchLog.Printf("Copying %d data blocks from remote input collections...", n)
1113 fs, err := (&arvados.Collection{ManifestText: txt}).FileSystem(runner.containerClient, runner.ContainerKeepClient)
1117 txt, err = fs.MarshalManifest(".")
1122 var resp arvados.Collection
1123 err = runner.ContainerArvClient.Create("collections", arvadosclient.Dict{
1124 "ensure_unique_name": true,
1125 "collection": arvadosclient.Dict{
1127 "name": "output for " + runner.Container.UUID,
1128 "manifest_text": txt,
1132 return fmt.Errorf("error creating output collection: %v", err)
1134 runner.OutputPDH = &resp.PortableDataHash
1138 func (runner *ContainerRunner) CleanupDirs() {
1139 if runner.ArvMount != nil {
1141 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1142 umount.Stdout = runner.CrunchLog
1143 umount.Stderr = runner.CrunchLog
1144 runner.CrunchLog.Printf("Running %v", umount.Args)
1145 umnterr := umount.Start()
1148 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1150 // If arv-mount --unmount gets stuck for any reason, we
1151 // don't want to wait for it forever. Do Wait() in a goroutine
1152 // so it doesn't block crunch-run.
1153 umountExit := make(chan error)
1155 mnterr := umount.Wait()
1157 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1159 umountExit <- mnterr
1162 for again := true; again; {
1168 case <-runner.ArvMountExit:
1170 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1171 runner.CrunchLog.Printf("Timed out waiting for unmount")
1173 umount.Process.Kill()
1175 runner.ArvMount.Process.Kill()
1181 if runner.ArvMountPoint != "" {
1182 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1183 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1187 if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1188 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1192 // CommitLogs posts the collection containing the final container logs.
1193 func (runner *ContainerRunner) CommitLogs() error {
1195 // Hold cStateLock to prevent races on CrunchLog (e.g., stop()).
1196 runner.cStateLock.Lock()
1197 defer runner.cStateLock.Unlock()
1199 runner.CrunchLog.Print(runner.finalState)
1201 if runner.arvMountLog != nil {
1202 runner.arvMountLog.Close()
1204 runner.CrunchLog.Close()
1206 // Closing CrunchLog above allows them to be committed to Keep at this
1207 // point, but re-open crunch log with ArvClient in case there are any
1208 // other further errors (such as failing to write the log to Keep!)
1209 // while shutting down
1210 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{
1211 ArvClient: runner.DispatcherArvClient,
1212 UUID: runner.Container.UUID,
1213 loggingStream: "crunch-run",
1216 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1219 if runner.LogsPDH != nil {
1220 // If we have already assigned something to LogsPDH,
1221 // we must be closing the re-opened log, which won't
1222 // end up getting attached to the container record and
1223 // therefore doesn't need to be saved as a collection
1224 // -- it exists only to send logs to other channels.
1227 saved, err := runner.saveLogCollection(true)
1229 return fmt.Errorf("error saving log collection: %s", err)
1231 runner.logMtx.Lock()
1232 defer runner.logMtx.Unlock()
1233 runner.LogsPDH = &saved.PortableDataHash
1237 func (runner *ContainerRunner) saveLogCollection(final bool) (response arvados.Collection, err error) {
1238 runner.logMtx.Lock()
1239 defer runner.logMtx.Unlock()
1240 if runner.LogsPDH != nil {
1241 // Already finalized.
1244 updates := arvadosclient.Dict{
1245 "name": "logs for " + runner.Container.UUID,
1247 mt, err1 := runner.LogCollection.MarshalManifest(".")
1249 // Only send updated manifest text if there was no
1251 updates["manifest_text"] = mt
1254 // Even if flushing the manifest had an error, we still want
1255 // to update the log record, if possible, to push the trash_at
1256 // and delete_at times into the future. Details on bug
1259 updates["is_trashed"] = true
1261 exp := time.Now().Add(crunchLogUpdatePeriod * 24)
1262 updates["trash_at"] = exp
1263 updates["delete_at"] = exp
1265 reqBody := arvadosclient.Dict{"collection": updates}
1267 if runner.logUUID == "" {
1268 reqBody["ensure_unique_name"] = true
1269 err2 = runner.DispatcherArvClient.Create("collections", reqBody, &response)
1271 err2 = runner.DispatcherArvClient.Update("collections", runner.logUUID, reqBody, &response)
1274 runner.logUUID = response.UUID
1277 if err1 != nil || err2 != nil {
1278 err = fmt.Errorf("error recording logs: %q, %q", err1, err2)
1283 // UpdateContainerRunning updates the container state to "Running"
1284 func (runner *ContainerRunner) UpdateContainerRunning() error {
1285 runner.cStateLock.Lock()
1286 defer runner.cStateLock.Unlock()
1287 if runner.cCancelled {
1290 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID,
1291 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running", "gateway_address": runner.gateway.Address}}, nil)
1294 // ContainerToken returns the api_token the container (and any
1295 // arv-mount processes) are allowed to use.
1296 func (runner *ContainerRunner) ContainerToken() (string, error) {
1297 if runner.token != "" {
1298 return runner.token, nil
1301 var auth arvados.APIClientAuthorization
1302 err := runner.DispatcherArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1306 runner.token = fmt.Sprintf("v2/%s/%s/%s", auth.UUID, auth.APIToken, runner.Container.UUID)
1307 return runner.token, nil
1310 // UpdateContainerFinal updates the container record state on API
1311 // server to "Complete" or "Cancelled"
1312 func (runner *ContainerRunner) UpdateContainerFinal() error {
1313 update := arvadosclient.Dict{}
1314 update["state"] = runner.finalState
1315 if runner.LogsPDH != nil {
1316 update["log"] = *runner.LogsPDH
1318 if runner.finalState == "Complete" {
1319 if runner.ExitCode != nil {
1320 update["exit_code"] = *runner.ExitCode
1322 if runner.OutputPDH != nil {
1323 update["output"] = *runner.OutputPDH
1326 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1329 // IsCancelled returns the value of Cancelled, with goroutine safety.
1330 func (runner *ContainerRunner) IsCancelled() bool {
1331 runner.cStateLock.Lock()
1332 defer runner.cStateLock.Unlock()
1333 return runner.cCancelled
1336 // NewArvLogWriter creates an ArvLogWriter
1337 func (runner *ContainerRunner) NewArvLogWriter(name string) (io.WriteCloser, error) {
1338 writer, err := runner.LogCollection.OpenFile(name+".txt", os.O_CREATE|os.O_WRONLY, 0666)
1342 return &ArvLogWriter{
1343 ArvClient: runner.DispatcherArvClient,
1344 UUID: runner.Container.UUID,
1345 loggingStream: name,
1346 writeCloser: writer,
1350 // Run the full container lifecycle.
1351 func (runner *ContainerRunner) Run() (err error) {
1352 runner.CrunchLog.Printf("crunch-run %s started", cmd.Version.String())
1353 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1355 hostname, hosterr := os.Hostname()
1357 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1359 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1362 runner.finalState = "Queued"
1365 runner.CleanupDirs()
1367 runner.CrunchLog.Printf("crunch-run finished")
1368 runner.CrunchLog.Close()
1371 err = runner.fetchContainerRecord()
1375 if runner.Container.State != "Locked" {
1376 return fmt.Errorf("dispatch error detected: container %q has state %q", runner.Container.UUID, runner.Container.State)
1379 var bindmounts map[string]bindmount
1381 // checkErr prints e (unless it's nil) and sets err to
1382 // e (unless err is already non-nil). Thus, if err
1383 // hasn't already been assigned when Run() returns,
1384 // this cleanup func will cause Run() to return the
1385 // first non-nil error that is passed to checkErr().
1386 checkErr := func(errorIn string, e error) {
1390 runner.CrunchLog.Printf("error in %s: %v", errorIn, e)
1394 if runner.finalState == "Complete" {
1395 // There was an error in the finalization.
1396 runner.finalState = "Cancelled"
1400 // Log the error encountered in Run(), if any
1401 checkErr("Run", err)
1403 if runner.finalState == "Queued" {
1404 runner.UpdateContainerFinal()
1408 if runner.IsCancelled() {
1409 runner.finalState = "Cancelled"
1410 // but don't return yet -- we still want to
1411 // capture partial output and write logs
1414 if bindmounts != nil {
1415 checkErr("CaptureOutput", runner.CaptureOutput(bindmounts))
1417 checkErr("stopHoststat", runner.stopHoststat())
1418 checkErr("CommitLogs", runner.CommitLogs())
1419 checkErr("UpdateContainerFinal", runner.UpdateContainerFinal())
1422 runner.setupSignals()
1423 err = runner.startHoststat()
1428 // set up FUSE mount and binds
1429 bindmounts, err = runner.SetupMounts()
1431 runner.finalState = "Cancelled"
1432 err = fmt.Errorf("While setting up mounts: %v", err)
1436 // check for and/or load image
1437 imageID, err := runner.LoadImage()
1439 if !runner.checkBrokenNode(err) {
1440 // Failed to load image but not due to a "broken node"
1441 // condition, probably user error.
1442 runner.finalState = "Cancelled"
1444 err = fmt.Errorf("While loading container image: %v", err)
1448 err = runner.CreateContainer(imageID, bindmounts)
1452 err = runner.LogHostInfo()
1456 err = runner.LogNodeRecord()
1460 err = runner.LogContainerRecord()
1465 if runner.IsCancelled() {
1469 err = runner.UpdateContainerRunning()
1473 runner.finalState = "Cancelled"
1475 err = runner.startCrunchstat()
1480 err = runner.StartContainer()
1482 runner.checkBrokenNode(err)
1486 err = runner.WaitFinish()
1487 if err == nil && !runner.IsCancelled() {
1488 runner.finalState = "Complete"
1493 // Fetch the current container record (uuid = runner.Container.UUID)
1494 // into runner.Container.
1495 func (runner *ContainerRunner) fetchContainerRecord() error {
1496 reader, err := runner.DispatcherArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1498 return fmt.Errorf("error fetching container record: %v", err)
1500 defer reader.Close()
1502 dec := json.NewDecoder(reader)
1504 err = dec.Decode(&runner.Container)
1506 return fmt.Errorf("error decoding container record: %v", err)
1510 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
1513 containerToken, err := runner.ContainerToken()
1515 return fmt.Errorf("error getting container token: %v", err)
1518 runner.ContainerArvClient, runner.ContainerKeepClient,
1519 runner.containerClient, err = runner.MkArvClient(containerToken)
1521 return fmt.Errorf("error creating container API client: %v", err)
1524 runner.ContainerKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1525 runner.DispatcherKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1527 err = runner.ContainerArvClient.Call("GET", "containers", runner.Container.UUID, "secret_mounts", nil, &sm)
1529 if apierr, ok := err.(arvadosclient.APIServerError); !ok || apierr.HttpStatusCode != 404 {
1530 return fmt.Errorf("error fetching secret_mounts: %v", err)
1532 // ok && apierr.HttpStatusCode == 404, which means
1533 // secret_mounts isn't supported by this API server.
1535 runner.SecretMounts = sm.SecretMounts
1540 // NewContainerRunner creates a new container runner.
1541 func NewContainerRunner(dispatcherClient *arvados.Client,
1542 dispatcherArvClient IArvadosClient,
1543 dispatcherKeepClient IKeepClient,
1544 containerUUID string) (*ContainerRunner, error) {
1546 cr := &ContainerRunner{
1547 dispatcherClient: dispatcherClient,
1548 DispatcherArvClient: dispatcherArvClient,
1549 DispatcherKeepClient: dispatcherKeepClient,
1551 cr.NewLogWriter = cr.NewArvLogWriter
1552 cr.RunArvMount = cr.ArvMountCmd
1553 cr.MkTempDir = ioutil.TempDir
1554 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1555 cl, err := arvadosclient.MakeArvadosClient()
1557 return nil, nil, nil, err
1560 kc, err := keepclient.MakeKeepClient(cl)
1562 return nil, nil, nil, err
1564 c2 := arvados.NewClientFromEnv()
1565 c2.AuthToken = token
1566 return cl, kc, c2, nil
1569 cr.LogCollection, err = (&arvados.Collection{}).FileSystem(cr.dispatcherClient, cr.DispatcherKeepClient)
1573 cr.Container.UUID = containerUUID
1574 w, err := cr.NewLogWriter("crunch-run")
1578 cr.CrunchLog = NewThrottledLogger(w)
1579 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1581 loadLogThrottleParams(dispatcherArvClient)
1587 func (command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
1588 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
1589 statInterval := flags.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1590 cgroupRoot := flags.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1591 cgroupParent := flags.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1592 cgroupParentSubsystem := flags.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1593 caCertsPath := flags.String("ca-certs", "", "Path to TLS root certificates")
1594 detach := flags.Bool("detach", false, "Detach from parent process and run in the background")
1595 stdinEnv := flags.Bool("stdin-env", false, "Load environment variables from JSON message on stdin")
1596 sleep := flags.Duration("sleep", 0, "Delay before starting (testing use only)")
1597 kill := flags.Int("kill", -1, "Send signal to an existing crunch-run process for given UUID")
1598 list := flags.Bool("list", false, "List UUIDs of existing crunch-run processes")
1599 enableMemoryLimit := flags.Bool("enable-memory-limit", true, "tell container runtime to limit container's memory usage")
1600 enableNetwork := flags.String("container-enable-networking", "default", "enable networking \"always\" (for all containers) or \"default\" (for containers that request it)")
1601 networkMode := flags.String("container-network-mode", "default", `Docker network mode for container (use any argument valid for docker --net)`)
1602 memprofile := flags.String("memprofile", "", "write memory profile to `file` after running container")
1603 runtimeEngine := flags.String("runtime-engine", "docker", "container runtime: docker or singularity")
1604 flags.Duration("check-containerd", 0, "Ignored. Exists for compatibility with older versions.")
1606 ignoreDetachFlag := false
1607 if len(args) > 0 && args[0] == "-no-detach" {
1608 // This process was invoked by a parent process, which
1609 // has passed along its own arguments, including
1610 // -detach, after the leading -no-detach flag. Strip
1611 // the leading -no-detach flag (it's not recognized by
1612 // flags.Parse()) and ignore the -detach flag that
1615 ignoreDetachFlag = true
1618 if err := flags.Parse(args); err == flag.ErrHelp {
1620 } else if err != nil {
1625 if *stdinEnv && !ignoreDetachFlag {
1626 // Load env vars on stdin if asked (but not in a
1627 // detached child process, in which case stdin is
1629 err := loadEnv(os.Stdin)
1636 containerUUID := flags.Arg(0)
1639 case *detach && !ignoreDetachFlag:
1640 return Detach(containerUUID, prog, args, os.Stdout, os.Stderr)
1642 return KillProcess(containerUUID, syscall.Signal(*kill), os.Stdout, os.Stderr)
1644 return ListProcesses(os.Stdout, os.Stderr)
1647 if containerUUID == "" {
1648 log.Printf("usage: %s [options] UUID", prog)
1652 log.Printf("crunch-run %s started", cmd.Version.String())
1655 if *caCertsPath != "" {
1656 arvadosclient.CertFiles = []string{*caCertsPath}
1659 api, err := arvadosclient.MakeArvadosClient()
1661 log.Printf("%s: %v", containerUUID, err)
1666 kc, kcerr := keepclient.MakeKeepClient(api)
1668 log.Printf("%s: %v", containerUUID, kcerr)
1671 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1674 cr, err := NewContainerRunner(arvados.NewClientFromEnv(), api, kc, containerUUID)
1680 switch *runtimeEngine {
1682 cr.executor, err = newDockerExecutor(containerUUID, cr.CrunchLog.Printf, cr.containerWatchdogInterval)
1684 cr.executor, err = newSingularityExecutor(cr.CrunchLog.Printf)
1686 cr.CrunchLog.Printf("%s: unsupported RuntimeEngine %q", containerUUID, *runtimeEngine)
1687 cr.CrunchLog.Close()
1691 cr.CrunchLog.Printf("%s: %v", containerUUID, err)
1692 cr.checkBrokenNode(err)
1693 cr.CrunchLog.Close()
1696 defer cr.executor.Close()
1698 gwAuthSecret := os.Getenv("GatewayAuthSecret")
1699 os.Unsetenv("GatewayAuthSecret")
1700 if gwAuthSecret == "" {
1701 // not safe to run a gateway service without an auth
1703 cr.CrunchLog.Printf("Not starting a gateway server (GatewayAuthSecret was not provided by dispatcher)")
1704 } else if gwListen := os.Getenv("GatewayAddress"); gwListen == "" {
1705 // dispatcher did not tell us which external IP
1706 // address to advertise --> no gateway service
1707 cr.CrunchLog.Printf("Not starting a gateway server (GatewayAddress was not provided by dispatcher)")
1708 } else if de, ok := cr.executor.(*dockerExecutor); ok {
1709 cr.gateway = Gateway{
1711 AuthSecret: gwAuthSecret,
1712 ContainerUUID: containerUUID,
1713 DockerContainerID: &de.containerID,
1715 ContainerIPAddress: dockerContainerIPAddress(&de.containerID),
1717 err = cr.gateway.Start()
1719 log.Printf("error starting gateway server: %s", err)
1724 parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerUUID+".")
1726 log.Printf("%s: %v", containerUUID, tmperr)
1730 cr.parentTemp = parentTemp
1731 cr.statInterval = *statInterval
1732 cr.cgroupRoot = *cgroupRoot
1733 cr.expectCgroupParent = *cgroupParent
1734 cr.enableMemoryLimit = *enableMemoryLimit
1735 cr.enableNetwork = *enableNetwork
1736 cr.networkMode = *networkMode
1737 if *cgroupParentSubsystem != "" {
1738 p := findCgroup(*cgroupParentSubsystem)
1739 cr.setCgroupParent = p
1740 cr.expectCgroupParent = p
1745 if *memprofile != "" {
1746 f, err := os.Create(*memprofile)
1748 log.Printf("could not create memory profile: %s", err)
1750 runtime.GC() // get up-to-date statistics
1751 if err := pprof.WriteHeapProfile(f); err != nil {
1752 log.Printf("could not write memory profile: %s", err)
1754 closeerr := f.Close()
1755 if closeerr != nil {
1756 log.Printf("closing memprofile file: %s", err)
1761 log.Printf("%s: %v", containerUUID, runerr)
1767 func loadEnv(rdr io.Reader) error {
1768 buf, err := ioutil.ReadAll(rdr)
1770 return fmt.Errorf("read stdin: %s", err)
1772 var env map[string]string
1773 err = json.Unmarshal(buf, &env)
1775 return fmt.Errorf("decode stdin: %s", err)
1777 for k, v := range env {
1778 err = os.Setenv(k, v)
1780 return fmt.Errorf("setenv(%q): %s", k, err)