1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
30 "git.curoverse.com/arvados.git/lib/crunchstat"
31 "git.curoverse.com/arvados.git/sdk/go/arvados"
32 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
33 "git.curoverse.com/arvados.git/sdk/go/keepclient"
34 "git.curoverse.com/arvados.git/sdk/go/manifest"
35 "golang.org/x/net/context"
37 dockertypes "github.com/docker/docker/api/types"
38 dockercontainer "github.com/docker/docker/api/types/container"
39 dockernetwork "github.com/docker/docker/api/types/network"
40 dockerclient "github.com/docker/docker/client"
45 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
46 type IArvadosClient interface {
47 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
48 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
49 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
50 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
51 CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
52 Discovery(key string) (interface{}, error)
55 // ErrCancelled is the error returned when the container is cancelled.
56 var ErrCancelled = errors.New("Cancelled")
58 // IKeepClient is the minimal Keep API methods used by crunch-run.
59 type IKeepClient interface {
60 PutB(buf []byte) (string, int, error)
61 ReadAt(locator string, p []byte, off int) (int, error)
62 ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error)
63 LocalLocator(locator string) (string, error)
67 // NewLogWriter is a factory function to create a new log writer.
68 type NewLogWriter func(name string) (io.WriteCloser, error)
70 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
72 type MkTempDir func(string, string) (string, error)
74 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
75 type ThinDockerClient interface {
76 ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error)
77 ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
78 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error)
79 ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error
80 ContainerRemove(ctx context.Context, container string, options dockertypes.ContainerRemoveOptions) error
81 ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error)
82 ContainerInspect(ctx context.Context, id string) (dockertypes.ContainerJSON, error)
83 ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error)
84 ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error)
85 ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error)
88 type PsProcess interface {
89 CmdlineSlice() ([]string, error)
92 // ContainerRunner is the main stateful struct used for a single execution of a
94 type ContainerRunner struct {
95 Docker ThinDockerClient
97 // Dispatcher client is initialized with the Dispatcher token.
98 // This is a privileged token used to manage container status
101 // We have both dispatcherClient and DispatcherArvClient
102 // because there are two different incompatible Arvados Go
103 // SDKs and we have to use both (hopefully this gets fixed in
105 dispatcherClient *arvados.Client
106 DispatcherArvClient IArvadosClient
107 DispatcherKeepClient IKeepClient
109 // Container client is initialized with the Container token
110 // This token controls the permissions of the container, and
111 // must be used for operations such as reading collections.
113 // Same comment as above applies to
114 // containerClient/ContainerArvClient.
115 containerClient *arvados.Client
116 ContainerArvClient IArvadosClient
117 ContainerKeepClient IKeepClient
119 // environment provided by arvados-dispatch-cloud
120 dispatchEnv map[string]interface{}
122 Container arvados.Container
123 ContainerConfig dockercontainer.Config
124 HostConfig dockercontainer.HostConfig
128 NewLogWriter NewLogWriter
129 loggingDone chan bool
130 CrunchLog *ThrottledLogger
131 Stdout io.WriteCloser
132 Stderr io.WriteCloser
135 LogCollection arvados.CollectionFileSystem
137 RunArvMount RunArvMount
143 Volumes map[string]struct{}
145 SigChan chan os.Signal
146 ArvMountExit chan error
147 SecretMounts map[string]arvados.Mount
148 MkArvClient func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error)
152 statLogger io.WriteCloser
153 statReporter *crunchstat.Reporter
154 hoststatLogger io.WriteCloser
155 hoststatReporter *crunchstat.Reporter
156 statInterval time.Duration
158 // What we expect the container's cgroup parent to be.
159 expectCgroupParent string
160 // What we tell docker to use as the container's cgroup
161 // parent. Note: Ideally we would use the same field for both
162 // expectCgroupParent and setCgroupParent, and just make it
163 // default to "docker". However, when using docker < 1.10 with
164 // systemd, specifying a non-empty cgroup parent (even the
165 // default value "docker") hits a docker bug
166 // (https://github.com/docker/docker/issues/17126). Using two
167 // separate fields makes it possible to use the "expect cgroup
168 // parent to be X" feature even on sites where the "specify
169 // cgroup parent" feature breaks.
170 setCgroupParent string
172 cStateLock sync.Mutex
173 cCancelled bool // StopContainer() invoked
174 cRemoved bool // docker confirmed the container no longer exists
176 enableNetwork string // one of "default" or "always"
177 networkMode string // passed through to HostConfig.NetworkMode
178 arvMountLog *ThrottledLogger
180 containerWatchdogInterval time.Duration
183 // setupSignals sets up signal handling to gracefully terminate the underlying
184 // Docker container and update state when receiving a TERM, INT or QUIT signal.
185 func (runner *ContainerRunner) setupSignals() {
186 runner.SigChan = make(chan os.Signal, 1)
187 signal.Notify(runner.SigChan, syscall.SIGTERM)
188 signal.Notify(runner.SigChan, syscall.SIGINT)
189 signal.Notify(runner.SigChan, syscall.SIGQUIT)
191 go func(sig chan os.Signal) {
198 // stop the underlying Docker container.
199 func (runner *ContainerRunner) stop(sig os.Signal) {
200 runner.cStateLock.Lock()
201 defer runner.cStateLock.Unlock()
203 runner.CrunchLog.Printf("caught signal: %v", sig)
205 if runner.ContainerID == "" {
208 runner.cCancelled = true
209 runner.CrunchLog.Printf("removing container")
210 err := runner.Docker.ContainerRemove(context.TODO(), runner.ContainerID, dockertypes.ContainerRemoveOptions{Force: true})
212 runner.CrunchLog.Printf("error removing container: %s", err)
214 if err == nil || strings.Contains(err.Error(), "No such container: "+runner.ContainerID) {
215 runner.cRemoved = true
219 var errorBlacklist = []string{
220 "(?ms).*[Cc]annot connect to the Docker daemon.*",
221 "(?ms).*oci runtime error.*starting container process.*container init.*mounting.*to rootfs.*no such file or directory.*",
222 "(?ms).*grpc: the connection is unavailable.*",
224 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)")
226 func (runner *ContainerRunner) runBrokenNodeHook() {
227 if *brokenNodeHook == "" {
228 path := filepath.Join(lockdir, brokenfile)
229 runner.CrunchLog.Printf("Writing %s to mark node as broken", path)
230 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0700)
232 runner.CrunchLog.Printf("Error writing %s: %s", path, err)
237 runner.CrunchLog.Printf("Running broken node hook %q", *brokenNodeHook)
239 c := exec.Command(*brokenNodeHook)
240 c.Stdout = runner.CrunchLog
241 c.Stderr = runner.CrunchLog
244 runner.CrunchLog.Printf("Error running broken node hook: %v", err)
249 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
250 for _, d := range errorBlacklist {
251 if m, e := regexp.MatchString(d, goterr.Error()); m && e == nil {
252 runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
253 runner.runBrokenNodeHook()
260 // LoadImage determines the docker image id from the container record and
261 // checks if it is available in the local Docker image store. If not, it loads
262 // the image from Keep.
263 func (runner *ContainerRunner) LoadImage() (err error) {
265 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
267 var collection arvados.Collection
268 err = runner.ContainerArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
270 return fmt.Errorf("While getting container image collection: %v", err)
272 manifest := manifest.Manifest{Text: collection.ManifestText}
273 var img, imageID string
274 for ms := range manifest.StreamIter() {
275 img = ms.FileStreamSegments[0].Name
276 if !strings.HasSuffix(img, ".tar") {
277 return fmt.Errorf("First file in the container image collection does not end in .tar")
279 imageID = img[:len(img)-4]
282 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
284 _, _, err = runner.Docker.ImageInspectWithRaw(context.TODO(), imageID)
286 runner.CrunchLog.Print("Loading Docker image from keep")
288 var readCloser io.ReadCloser
289 readCloser, err = runner.ContainerKeepClient.ManifestFileReader(manifest, img)
291 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
294 response, err := runner.Docker.ImageLoad(context.TODO(), readCloser, true)
296 return fmt.Errorf("While loading container image into Docker: %v", err)
299 defer response.Body.Close()
300 rbody, err := ioutil.ReadAll(response.Body)
302 return fmt.Errorf("Reading response to image load: %v", err)
304 runner.CrunchLog.Printf("Docker response: %s", rbody)
306 runner.CrunchLog.Print("Docker image is available")
309 runner.ContainerConfig.Image = imageID
311 runner.ContainerKeepClient.ClearBlockCache()
316 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
317 c = exec.Command("arv-mount", arvMountCmd...)
319 // Copy our environment, but override ARVADOS_API_TOKEN with
320 // the container auth token.
322 for _, s := range os.Environ() {
323 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
324 c.Env = append(c.Env, s)
327 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
329 w, err := runner.NewLogWriter("arv-mount")
333 runner.arvMountLog = NewThrottledLogger(w)
334 c.Stdout = runner.arvMountLog
335 c.Stderr = runner.arvMountLog
337 runner.CrunchLog.Printf("Running %v", c.Args)
344 statReadme := make(chan bool)
345 runner.ArvMountExit = make(chan error)
350 time.Sleep(100 * time.Millisecond)
351 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
363 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
365 runner.ArvMountExit <- mnterr
366 close(runner.ArvMountExit)
372 case err := <-runner.ArvMountExit:
373 runner.ArvMount = nil
381 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
382 if runner.ArvMountPoint == "" {
383 runner.ArvMountPoint, err = runner.MkTempDir(runner.parentTemp, prefix)
388 func copyfile(src string, dst string) (err error) {
389 srcfile, err := os.Open(src)
394 os.MkdirAll(path.Dir(dst), 0777)
396 dstfile, err := os.Create(dst)
400 _, err = io.Copy(dstfile, srcfile)
405 err = srcfile.Close()
406 err2 := dstfile.Close()
419 func (runner *ContainerRunner) SetupMounts() (err error) {
420 err = runner.SetupArvMountPoint("keep")
422 return fmt.Errorf("While creating keep mount temp dir: %v", err)
425 token, err := runner.ContainerToken()
427 return fmt.Errorf("could not get container token: %s", err)
432 arvMountCmd := []string{
436 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
438 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
439 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
442 collectionPaths := []string{}
444 runner.Volumes = make(map[string]struct{})
445 needCertMount := true
446 type copyFile struct {
450 var copyFiles []copyFile
453 for bind := range runner.Container.Mounts {
454 binds = append(binds, bind)
456 for bind := range runner.SecretMounts {
457 if _, ok := runner.Container.Mounts[bind]; ok {
458 return fmt.Errorf("Secret mount %q conflicts with regular mount", bind)
460 if runner.SecretMounts[bind].Kind != "json" &&
461 runner.SecretMounts[bind].Kind != "text" {
462 return fmt.Errorf("Secret mount %q type is %q but only 'json' and 'text' are permitted.",
463 bind, runner.SecretMounts[bind].Kind)
465 binds = append(binds, bind)
469 for _, bind := range binds {
470 mnt, ok := runner.Container.Mounts[bind]
472 mnt = runner.SecretMounts[bind]
474 if bind == "stdout" || bind == "stderr" {
475 // Is it a "file" mount kind?
476 if mnt.Kind != "file" {
477 return fmt.Errorf("Unsupported mount kind '%s' for %s. Only 'file' is supported.", mnt.Kind, bind)
480 // Does path start with OutputPath?
481 prefix := runner.Container.OutputPath
482 if !strings.HasSuffix(prefix, "/") {
485 if !strings.HasPrefix(mnt.Path, prefix) {
486 return fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
491 // Is it a "collection" mount kind?
492 if mnt.Kind != "collection" && mnt.Kind != "json" {
493 return fmt.Errorf("Unsupported mount kind '%s' for stdin. Only 'collection' or 'json' are supported.", mnt.Kind)
497 if bind == "/etc/arvados/ca-certificates.crt" {
498 needCertMount = false
501 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
502 if mnt.Kind != "collection" && mnt.Kind != "text" && mnt.Kind != "json" {
503 return fmt.Errorf("Only mount points of kind 'collection', 'text' or 'json' are supported underneath the output_path for %q, was %q", bind, mnt.Kind)
508 case mnt.Kind == "collection" && bind != "stdin":
510 if mnt.UUID != "" && mnt.PortableDataHash != "" {
511 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
515 return fmt.Errorf("Writing to existing collections currently not permitted.")
518 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
519 } else if mnt.PortableDataHash != "" {
520 if mnt.Writable && !strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
521 return fmt.Errorf("Can never write to a collection specified by portable data hash")
523 idx := strings.Index(mnt.PortableDataHash, "/")
525 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
526 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
527 runner.Container.Mounts[bind] = mnt
529 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
530 if mnt.Path != "" && mnt.Path != "." {
531 if strings.HasPrefix(mnt.Path, "./") {
532 mnt.Path = mnt.Path[2:]
533 } else if strings.HasPrefix(mnt.Path, "/") {
534 mnt.Path = mnt.Path[1:]
536 src += "/" + mnt.Path
539 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
540 arvMountCmd = append(arvMountCmd, "--mount-tmp")
541 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
545 if bind == runner.Container.OutputPath {
546 runner.HostOutputDir = src
547 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
548 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
549 copyFiles = append(copyFiles, copyFile{src, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
551 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
554 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
556 collectionPaths = append(collectionPaths, src)
558 case mnt.Kind == "tmp":
560 tmpdir, err = runner.MkTempDir(runner.parentTemp, "tmp")
562 return fmt.Errorf("While creating mount temp dir: %v", err)
564 st, staterr := os.Stat(tmpdir)
566 return fmt.Errorf("While Stat on temp dir: %v", staterr)
568 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
570 return fmt.Errorf("While Chmod temp dir: %v", err)
572 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", tmpdir, bind))
573 if bind == runner.Container.OutputPath {
574 runner.HostOutputDir = tmpdir
577 case mnt.Kind == "json" || mnt.Kind == "text":
579 if mnt.Kind == "json" {
580 filedata, err = json.Marshal(mnt.Content)
582 return fmt.Errorf("encoding json data: %v", err)
585 text, ok := mnt.Content.(string)
587 return fmt.Errorf("content for mount %q must be a string", bind)
589 filedata = []byte(text)
592 tmpdir, err := runner.MkTempDir(runner.parentTemp, mnt.Kind)
594 return fmt.Errorf("creating temp dir: %v", err)
596 tmpfn := filepath.Join(tmpdir, "mountdata."+mnt.Kind)
597 err = ioutil.WriteFile(tmpfn, filedata, 0444)
599 return fmt.Errorf("writing temp file: %v", err)
601 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
602 copyFiles = append(copyFiles, copyFile{tmpfn, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
604 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
607 case mnt.Kind == "git_tree":
608 tmpdir, err := runner.MkTempDir(runner.parentTemp, "git_tree")
610 return fmt.Errorf("creating temp dir: %v", err)
612 err = gitMount(mnt).extractTree(runner.ContainerArvClient, tmpdir, token)
616 runner.Binds = append(runner.Binds, tmpdir+":"+bind+":ro")
620 if runner.HostOutputDir == "" {
621 return fmt.Errorf("Output path does not correspond to a writable mount point")
624 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
625 for _, certfile := range arvadosclient.CertFiles {
626 _, err := os.Stat(certfile)
628 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
635 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
637 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
639 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
641 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
643 return fmt.Errorf("While trying to start arv-mount: %v", err)
646 for _, p := range collectionPaths {
649 return fmt.Errorf("While checking that input files exist: %v", err)
653 for _, cp := range copyFiles {
654 st, err := os.Stat(cp.src)
656 return fmt.Errorf("While staging writable file from %q to %q: %v", cp.src, cp.bind, err)
659 err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
663 target := path.Join(cp.bind, walkpath[len(cp.src):])
664 if walkinfo.Mode().IsRegular() {
665 copyerr := copyfile(walkpath, target)
669 return os.Chmod(target, walkinfo.Mode()|0777)
670 } else if walkinfo.Mode().IsDir() {
671 mkerr := os.MkdirAll(target, 0777)
675 return os.Chmod(target, walkinfo.Mode()|os.ModeSetgid|0777)
677 return fmt.Errorf("Source %q is not a regular file or directory", cp.src)
680 } else if st.Mode().IsRegular() {
681 err = copyfile(cp.src, cp.bind)
683 err = os.Chmod(cp.bind, st.Mode()|0777)
687 return fmt.Errorf("While staging writable file from %q to %q: %v", cp.src, cp.bind, err)
694 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
695 // Handle docker log protocol
696 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
697 defer close(runner.loggingDone)
699 header := make([]byte, 8)
702 _, err = io.ReadAtLeast(containerReader, header, 8)
709 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
712 _, err = io.CopyN(runner.Stdout, containerReader, readsize)
715 _, err = io.CopyN(runner.Stderr, containerReader, readsize)
720 runner.CrunchLog.Printf("error reading docker logs: %v", err)
723 err = runner.Stdout.Close()
725 runner.CrunchLog.Printf("error closing stdout logs: %v", err)
728 err = runner.Stderr.Close()
730 runner.CrunchLog.Printf("error closing stderr logs: %v", err)
733 if runner.statReporter != nil {
734 runner.statReporter.Stop()
735 err = runner.statLogger.Close()
737 runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
742 func (runner *ContainerRunner) stopHoststat() error {
743 if runner.hoststatReporter == nil {
746 runner.hoststatReporter.Stop()
747 err := runner.hoststatLogger.Close()
749 return fmt.Errorf("error closing hoststat logs: %v", err)
754 func (runner *ContainerRunner) startHoststat() error {
755 w, err := runner.NewLogWriter("hoststat")
759 runner.hoststatLogger = NewThrottledLogger(w)
760 runner.hoststatReporter = &crunchstat.Reporter{
761 Logger: log.New(runner.hoststatLogger, "", 0),
762 CgroupRoot: runner.cgroupRoot,
763 PollPeriod: runner.statInterval,
765 runner.hoststatReporter.Start()
769 func (runner *ContainerRunner) startCrunchstat() error {
770 w, err := runner.NewLogWriter("crunchstat")
774 runner.statLogger = NewThrottledLogger(w)
775 runner.statReporter = &crunchstat.Reporter{
776 CID: runner.ContainerID,
777 Logger: log.New(runner.statLogger, "", 0),
778 CgroupParent: runner.expectCgroupParent,
779 CgroupRoot: runner.cgroupRoot,
780 PollPeriod: runner.statInterval,
781 TempDir: runner.parentTemp,
783 runner.statReporter.Start()
787 type infoCommand struct {
792 // LogHostInfo logs info about the current host, for debugging and
793 // accounting purposes. Although it's logged as "node-info", this is
794 // about the environment where crunch-run is actually running, which
795 // might differ from what's described in the node record (see
797 func (runner *ContainerRunner) LogHostInfo() (err error) {
798 w, err := runner.NewLogWriter("node-info")
803 commands := []infoCommand{
805 label: "Host Information",
806 cmd: []string{"uname", "-a"},
809 label: "CPU Information",
810 cmd: []string{"cat", "/proc/cpuinfo"},
813 label: "Memory Information",
814 cmd: []string{"cat", "/proc/meminfo"},
818 cmd: []string{"df", "-m", "/", os.TempDir()},
821 label: "Disk INodes",
822 cmd: []string{"df", "-i", "/", os.TempDir()},
826 // Run commands with informational output to be logged.
827 for _, command := range commands {
828 fmt.Fprintln(w, command.label)
829 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
832 if err := cmd.Run(); err != nil {
833 err = fmt.Errorf("While running command %q: %v", command.cmd, err)
842 return fmt.Errorf("While closing node-info logs: %v", err)
847 // LogContainerRecord gets and saves the raw JSON container record from the API server
848 func (runner *ContainerRunner) LogContainerRecord() error {
849 logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
850 if !logged && err == nil {
851 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
856 // LogNodeRecord logs the current host's InstanceType config entry (or
857 // the arvados#node record, if running via crunch-dispatch-slurm).
858 func (runner *ContainerRunner) LogNodeRecord() error {
859 if it, ok := runner.dispatchEnv["InstanceType"]; ok {
860 // Dispatched via arvados-dispatch-cloud. Save
861 // InstanceType config fragment received from
862 // dispatcher on stdin.
863 w, err := runner.LogCollection.OpenFile("node.json", os.O_CREATE|os.O_WRONLY, 0666)
868 if it, ok := it.(string); ok {
869 // dispatcher supplied JSON data (in order to
870 // stay compatible with old crunch-run
872 _, err = io.WriteString(w, it)
877 // dispatcher supplied struct
878 enc := json.NewEncoder(w)
879 enc.SetIndent("", " ")
887 // Dispatched via crunch-dispatch-slurm. Look up
888 // apiserver's node record corresponding to
890 hostname := os.Getenv("SLURMD_NODENAME")
892 hostname, _ = os.Hostname()
894 _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
895 // The "info" field has admin-only info when
896 // obtained with a privileged token, and
897 // should not be logged.
898 node, ok := resp.(map[string]interface{})
907 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
908 writer, err := runner.LogCollection.OpenFile(label+".json", os.O_CREATE|os.O_WRONLY, 0666)
913 ArvClient: runner.DispatcherArvClient,
914 UUID: runner.Container.UUID,
915 loggingStream: label,
919 reader, err := runner.DispatcherArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
921 return false, fmt.Errorf("error getting %s record: %v", label, err)
925 dec := json.NewDecoder(reader)
927 var resp map[string]interface{}
928 if err = dec.Decode(&resp); err != nil {
929 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
931 items, ok := resp["items"].([]interface{})
933 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
934 } else if len(items) < 1 {
940 // Re-encode it using indentation to improve readability
941 enc := json.NewEncoder(w)
942 enc.SetIndent("", " ")
943 if err = enc.Encode(items[0]); err != nil {
944 return false, fmt.Errorf("error logging %s record: %v", label, err)
948 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
953 // AttachStreams connects the docker container stdin, stdout and stderr logs
954 // to the Arvados logger which logs to Keep and the API server logs table.
955 func (runner *ContainerRunner) AttachStreams() (err error) {
957 runner.CrunchLog.Print("Attaching container streams")
959 // If stdin mount is provided, attach it to the docker container
960 var stdinRdr arvados.File
962 if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
963 if stdinMnt.Kind == "collection" {
964 var stdinColl arvados.Collection
965 collId := stdinMnt.UUID
967 collId = stdinMnt.PortableDataHash
969 err = runner.ContainerArvClient.Get("collections", collId, nil, &stdinColl)
971 return fmt.Errorf("While getting stdin collection: %v", err)
974 stdinRdr, err = runner.ContainerKeepClient.ManifestFileReader(
975 manifest.Manifest{Text: stdinColl.ManifestText},
977 if os.IsNotExist(err) {
978 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
979 } else if err != nil {
980 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
982 } else if stdinMnt.Kind == "json" {
983 stdinJson, err = json.Marshal(stdinMnt.Content)
985 return fmt.Errorf("While encoding stdin json data: %v", err)
990 stdinUsed := stdinRdr != nil || len(stdinJson) != 0
991 response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
992 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
994 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
997 runner.loggingDone = make(chan bool)
999 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
1000 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
1004 runner.Stdout = stdoutFile
1005 } else if w, err := runner.NewLogWriter("stdout"); err != nil {
1008 runner.Stdout = NewThrottledLogger(w)
1011 if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
1012 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
1016 runner.Stderr = stderrFile
1017 } else if w, err := runner.NewLogWriter("stderr"); err != nil {
1020 runner.Stderr = NewThrottledLogger(w)
1023 if stdinRdr != nil {
1025 _, err := io.Copy(response.Conn, stdinRdr)
1027 runner.CrunchLog.Printf("While writing stdin collection to docker container: %v", err)
1031 response.CloseWrite()
1033 } else if len(stdinJson) != 0 {
1035 _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
1037 runner.CrunchLog.Printf("While writing stdin json to docker container: %v", err)
1040 response.CloseWrite()
1044 go runner.ProcessDockerAttach(response.Reader)
1049 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
1050 stdoutPath := mntPath[len(runner.Container.OutputPath):]
1051 index := strings.LastIndex(stdoutPath, "/")
1053 subdirs := stdoutPath[:index]
1055 st, err := os.Stat(runner.HostOutputDir)
1057 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
1059 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
1060 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
1062 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
1066 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
1068 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
1071 return stdoutFile, nil
1074 // CreateContainer creates the docker container.
1075 func (runner *ContainerRunner) CreateContainer() error {
1076 runner.CrunchLog.Print("Creating Docker container")
1078 runner.ContainerConfig.Cmd = runner.Container.Command
1079 if runner.Container.Cwd != "." {
1080 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
1083 for k, v := range runner.Container.Environment {
1084 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
1087 runner.ContainerConfig.Volumes = runner.Volumes
1089 maxRAM := int64(runner.Container.RuntimeConstraints.RAM)
1090 if maxRAM < 4*1024*1024 {
1091 // Docker daemon won't let you set a limit less than 4 MiB
1092 maxRAM = 4 * 1024 * 1024
1094 runner.HostConfig = dockercontainer.HostConfig{
1095 Binds: runner.Binds,
1096 LogConfig: dockercontainer.LogConfig{
1099 Resources: dockercontainer.Resources{
1100 CgroupParent: runner.setCgroupParent,
1101 NanoCPUs: int64(runner.Container.RuntimeConstraints.VCPUs) * 1000000000,
1102 Memory: maxRAM, // RAM
1103 MemorySwap: maxRAM, // RAM+swap
1104 KernelMemory: maxRAM, // kernel portion
1108 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
1109 tok, err := runner.ContainerToken()
1113 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
1114 "ARVADOS_API_TOKEN="+tok,
1115 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
1116 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
1118 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
1120 if runner.enableNetwork == "always" {
1121 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
1123 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
1127 _, stdinUsed := runner.Container.Mounts["stdin"]
1128 runner.ContainerConfig.OpenStdin = stdinUsed
1129 runner.ContainerConfig.StdinOnce = stdinUsed
1130 runner.ContainerConfig.AttachStdin = stdinUsed
1131 runner.ContainerConfig.AttachStdout = true
1132 runner.ContainerConfig.AttachStderr = true
1134 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
1136 return fmt.Errorf("While creating container: %v", err)
1139 runner.ContainerID = createdBody.ID
1141 return runner.AttachStreams()
1144 // StartContainer starts the docker container created by CreateContainer.
1145 func (runner *ContainerRunner) StartContainer() error {
1146 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
1147 runner.cStateLock.Lock()
1148 defer runner.cStateLock.Unlock()
1149 if runner.cCancelled {
1152 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
1153 dockertypes.ContainerStartOptions{})
1156 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
1157 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])
1159 return fmt.Errorf("could not start container: %v%s", err, advice)
1164 // WaitFinish waits for the container to terminate, capture the exit code, and
1165 // close the stdout/stderr logging.
1166 func (runner *ContainerRunner) WaitFinish() error {
1167 var runTimeExceeded <-chan time.Time
1168 runner.CrunchLog.Print("Waiting for container to finish")
1170 waitOk, waitErr := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID, dockercontainer.WaitConditionNotRunning)
1171 arvMountExit := runner.ArvMountExit
1172 if timeout := runner.Container.SchedulingParameters.MaxRunTime; timeout > 0 {
1173 runTimeExceeded = time.After(time.Duration(timeout) * time.Second)
1176 containerGone := make(chan struct{})
1178 defer close(containerGone)
1179 if runner.containerWatchdogInterval < 1 {
1180 runner.containerWatchdogInterval = time.Minute
1182 for range time.NewTicker(runner.containerWatchdogInterval).C {
1183 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(runner.containerWatchdogInterval))
1184 ctr, err := runner.Docker.ContainerInspect(ctx, runner.ContainerID)
1186 runner.cStateLock.Lock()
1187 done := runner.cRemoved || runner.ExitCode != nil
1188 runner.cStateLock.Unlock()
1191 } else if err != nil {
1192 runner.CrunchLog.Printf("Error inspecting container: %s", err)
1193 runner.checkBrokenNode(err)
1195 } else if ctr.State == nil || !(ctr.State.Running || ctr.State.Status == "created") {
1196 runner.CrunchLog.Printf("Container is not running: State=%v", ctr.State)
1204 case waitBody := <-waitOk:
1205 runner.CrunchLog.Printf("Container exited with code: %v", waitBody.StatusCode)
1206 code := int(waitBody.StatusCode)
1207 runner.ExitCode = &code
1209 // wait for stdout/stderr to complete
1210 <-runner.loggingDone
1213 case err := <-waitErr:
1214 return fmt.Errorf("container wait: %v", err)
1216 case <-arvMountExit:
1217 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
1219 // arvMountExit will always be ready now that
1220 // it's closed, but that doesn't interest us.
1223 case <-runTimeExceeded:
1224 runner.CrunchLog.Printf("maximum run time exceeded. Stopping container.")
1226 runTimeExceeded = nil
1228 case <-containerGone:
1229 return errors.New("docker client never returned status")
1234 func (runner *ContainerRunner) updateLogs() {
1235 ticker := time.NewTicker(crunchLogUpdatePeriod / 360)
1238 sigusr1 := make(chan os.Signal, 1)
1239 signal.Notify(sigusr1, syscall.SIGUSR1)
1240 defer signal.Stop(sigusr1)
1242 saveAtTime := time.Now().Add(crunchLogUpdatePeriod)
1243 saveAtSize := crunchLogUpdateSize
1249 saveAtTime = time.Now()
1251 runner.logMtx.Lock()
1252 done := runner.LogsPDH != nil
1253 runner.logMtx.Unlock()
1257 size := runner.LogCollection.Size()
1258 if size == savedSize || (time.Now().Before(saveAtTime) && size < saveAtSize) {
1261 saveAtTime = time.Now().Add(crunchLogUpdatePeriod)
1262 saveAtSize = runner.LogCollection.Size() + crunchLogUpdateSize
1263 saved, err := runner.saveLogCollection(false)
1265 runner.CrunchLog.Printf("error updating log collection: %s", err)
1269 var updated arvados.Container
1270 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1271 "container": arvadosclient.Dict{"log": saved.PortableDataHash},
1274 runner.CrunchLog.Printf("error updating container log to %s: %s", saved.PortableDataHash, err)
1282 // CaptureOutput saves data from the container's output directory if
1283 // needed, and updates the container output accordingly.
1284 func (runner *ContainerRunner) CaptureOutput() error {
1285 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
1286 // Output may have been set directly by the container, so
1287 // refresh the container record to check.
1288 err := runner.DispatcherArvClient.Get("containers", runner.Container.UUID,
1289 nil, &runner.Container)
1293 if runner.Container.Output != "" {
1294 // Container output is already set.
1295 runner.OutputPDH = &runner.Container.Output
1300 txt, err := (&copier{
1301 client: runner.containerClient,
1302 arvClient: runner.ContainerArvClient,
1303 keepClient: runner.ContainerKeepClient,
1304 hostOutputDir: runner.HostOutputDir,
1305 ctrOutputDir: runner.Container.OutputPath,
1306 binds: runner.Binds,
1307 mounts: runner.Container.Mounts,
1308 secretMounts: runner.SecretMounts,
1309 logger: runner.CrunchLog,
1314 if n := len(regexp.MustCompile(` [0-9a-f]+\+\S*\+R`).FindAllStringIndex(txt, -1)); n > 0 {
1315 runner.CrunchLog.Printf("Copying %d data blocks from remote input collections...", n)
1316 fs, err := (&arvados.Collection{ManifestText: txt}).FileSystem(runner.containerClient, runner.ContainerKeepClient)
1320 txt, err = fs.MarshalManifest(".")
1325 var resp arvados.Collection
1326 err = runner.ContainerArvClient.Create("collections", arvadosclient.Dict{
1327 "ensure_unique_name": true,
1328 "collection": arvadosclient.Dict{
1330 "name": "output for " + runner.Container.UUID,
1331 "manifest_text": txt,
1335 return fmt.Errorf("error creating output collection: %v", err)
1337 runner.OutputPDH = &resp.PortableDataHash
1341 func (runner *ContainerRunner) CleanupDirs() {
1342 if runner.ArvMount != nil {
1344 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1345 umount.Stdout = runner.CrunchLog
1346 umount.Stderr = runner.CrunchLog
1347 runner.CrunchLog.Printf("Running %v", umount.Args)
1348 umnterr := umount.Start()
1351 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1353 // If arv-mount --unmount gets stuck for any reason, we
1354 // don't want to wait for it forever. Do Wait() in a goroutine
1355 // so it doesn't block crunch-run.
1356 umountExit := make(chan error)
1358 mnterr := umount.Wait()
1360 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1362 umountExit <- mnterr
1365 for again := true; again; {
1371 case <-runner.ArvMountExit:
1373 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1374 runner.CrunchLog.Printf("Timed out waiting for unmount")
1376 umount.Process.Kill()
1378 runner.ArvMount.Process.Kill()
1384 if runner.ArvMountPoint != "" {
1385 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1386 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1390 if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1391 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1395 // CommitLogs posts the collection containing the final container logs.
1396 func (runner *ContainerRunner) CommitLogs() error {
1398 // Hold cStateLock to prevent races on CrunchLog (e.g., stop()).
1399 runner.cStateLock.Lock()
1400 defer runner.cStateLock.Unlock()
1402 runner.CrunchLog.Print(runner.finalState)
1404 if runner.arvMountLog != nil {
1405 runner.arvMountLog.Close()
1407 runner.CrunchLog.Close()
1409 // Closing CrunchLog above allows them to be committed to Keep at this
1410 // point, but re-open crunch log with ArvClient in case there are any
1411 // other further errors (such as failing to write the log to Keep!)
1412 // while shutting down
1413 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{
1414 ArvClient: runner.DispatcherArvClient,
1415 UUID: runner.Container.UUID,
1416 loggingStream: "crunch-run",
1419 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1422 if runner.LogsPDH != nil {
1423 // If we have already assigned something to LogsPDH,
1424 // we must be closing the re-opened log, which won't
1425 // end up getting attached to the container record and
1426 // therefore doesn't need to be saved as a collection
1427 // -- it exists only to send logs to other channels.
1430 saved, err := runner.saveLogCollection(true)
1432 return fmt.Errorf("error saving log collection: %s", err)
1434 runner.logMtx.Lock()
1435 defer runner.logMtx.Unlock()
1436 runner.LogsPDH = &saved.PortableDataHash
1440 func (runner *ContainerRunner) saveLogCollection(final bool) (response arvados.Collection, err error) {
1441 runner.logMtx.Lock()
1442 defer runner.logMtx.Unlock()
1443 if runner.LogsPDH != nil {
1444 // Already finalized.
1447 mt, err := runner.LogCollection.MarshalManifest(".")
1449 err = fmt.Errorf("error creating log manifest: %v", err)
1452 updates := arvadosclient.Dict{
1453 "name": "logs for " + runner.Container.UUID,
1454 "manifest_text": mt,
1457 updates["is_trashed"] = true
1459 exp := time.Now().Add(crunchLogUpdatePeriod * 24)
1460 updates["trash_at"] = exp
1461 updates["delete_at"] = exp
1463 reqBody := arvadosclient.Dict{"collection": updates}
1464 if runner.logUUID == "" {
1465 reqBody["ensure_unique_name"] = true
1466 err = runner.DispatcherArvClient.Create("collections", reqBody, &response)
1468 err = runner.DispatcherArvClient.Update("collections", runner.logUUID, reqBody, &response)
1473 runner.logUUID = response.UUID
1477 // UpdateContainerRunning updates the container state to "Running"
1478 func (runner *ContainerRunner) UpdateContainerRunning() error {
1479 runner.cStateLock.Lock()
1480 defer runner.cStateLock.Unlock()
1481 if runner.cCancelled {
1484 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID,
1485 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1488 // ContainerToken returns the api_token the container (and any
1489 // arv-mount processes) are allowed to use.
1490 func (runner *ContainerRunner) ContainerToken() (string, error) {
1491 if runner.token != "" {
1492 return runner.token, nil
1495 var auth arvados.APIClientAuthorization
1496 err := runner.DispatcherArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1500 runner.token = fmt.Sprintf("v2/%s/%s/%s", auth.UUID, auth.APIToken, runner.Container.UUID)
1501 return runner.token, nil
1504 // UpdateContainerComplete updates the container record state on API
1505 // server to "Complete" or "Cancelled"
1506 func (runner *ContainerRunner) UpdateContainerFinal() error {
1507 update := arvadosclient.Dict{}
1508 update["state"] = runner.finalState
1509 if runner.LogsPDH != nil {
1510 update["log"] = *runner.LogsPDH
1512 if runner.finalState == "Complete" {
1513 if runner.ExitCode != nil {
1514 update["exit_code"] = *runner.ExitCode
1516 if runner.OutputPDH != nil {
1517 update["output"] = *runner.OutputPDH
1520 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1523 // IsCancelled returns the value of Cancelled, with goroutine safety.
1524 func (runner *ContainerRunner) IsCancelled() bool {
1525 runner.cStateLock.Lock()
1526 defer runner.cStateLock.Unlock()
1527 return runner.cCancelled
1530 // NewArvLogWriter creates an ArvLogWriter
1531 func (runner *ContainerRunner) NewArvLogWriter(name string) (io.WriteCloser, error) {
1532 writer, err := runner.LogCollection.OpenFile(name+".txt", os.O_CREATE|os.O_WRONLY, 0666)
1536 return &ArvLogWriter{
1537 ArvClient: runner.DispatcherArvClient,
1538 UUID: runner.Container.UUID,
1539 loggingStream: name,
1540 writeCloser: writer,
1544 // Run the full container lifecycle.
1545 func (runner *ContainerRunner) Run() (err error) {
1546 runner.CrunchLog.Printf("crunch-run %s started", version)
1547 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1549 hostname, hosterr := os.Hostname()
1551 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1553 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1556 runner.finalState = "Queued"
1559 runner.CleanupDirs()
1561 runner.CrunchLog.Printf("crunch-run finished")
1562 runner.CrunchLog.Close()
1565 err = runner.fetchContainerRecord()
1569 if runner.Container.State != "Locked" {
1570 return fmt.Errorf("dispatch error detected: container %q has state %q", runner.Container.UUID, runner.Container.State)
1574 // checkErr prints e (unless it's nil) and sets err to
1575 // e (unless err is already non-nil). Thus, if err
1576 // hasn't already been assigned when Run() returns,
1577 // this cleanup func will cause Run() to return the
1578 // first non-nil error that is passed to checkErr().
1579 checkErr := func(errorIn string, e error) {
1583 runner.CrunchLog.Printf("error in %s: %v", errorIn, e)
1587 if runner.finalState == "Complete" {
1588 // There was an error in the finalization.
1589 runner.finalState = "Cancelled"
1593 // Log the error encountered in Run(), if any
1594 checkErr("Run", err)
1596 if runner.finalState == "Queued" {
1597 runner.UpdateContainerFinal()
1601 if runner.IsCancelled() {
1602 runner.finalState = "Cancelled"
1603 // but don't return yet -- we still want to
1604 // capture partial output and write logs
1607 checkErr("CaptureOutput", runner.CaptureOutput())
1608 checkErr("stopHoststat", runner.stopHoststat())
1609 checkErr("CommitLogs", runner.CommitLogs())
1610 checkErr("UpdateContainerFinal", runner.UpdateContainerFinal())
1613 runner.setupSignals()
1614 err = runner.startHoststat()
1619 // check for and/or load image
1620 err = runner.LoadImage()
1622 if !runner.checkBrokenNode(err) {
1623 // Failed to load image but not due to a "broken node"
1624 // condition, probably user error.
1625 runner.finalState = "Cancelled"
1627 err = fmt.Errorf("While loading container image: %v", err)
1631 // set up FUSE mount and binds
1632 err = runner.SetupMounts()
1634 runner.finalState = "Cancelled"
1635 err = fmt.Errorf("While setting up mounts: %v", err)
1639 err = runner.CreateContainer()
1643 err = runner.LogHostInfo()
1647 err = runner.LogNodeRecord()
1651 err = runner.LogContainerRecord()
1656 if runner.IsCancelled() {
1660 err = runner.UpdateContainerRunning()
1664 runner.finalState = "Cancelled"
1666 err = runner.startCrunchstat()
1671 err = runner.StartContainer()
1673 runner.checkBrokenNode(err)
1677 err = runner.WaitFinish()
1678 if err == nil && !runner.IsCancelled() {
1679 runner.finalState = "Complete"
1684 // Fetch the current container record (uuid = runner.Container.UUID)
1685 // into runner.Container.
1686 func (runner *ContainerRunner) fetchContainerRecord() error {
1687 reader, err := runner.DispatcherArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1689 return fmt.Errorf("error fetching container record: %v", err)
1691 defer reader.Close()
1693 dec := json.NewDecoder(reader)
1695 err = dec.Decode(&runner.Container)
1697 return fmt.Errorf("error decoding container record: %v", err)
1701 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
1704 containerToken, err := runner.ContainerToken()
1706 return fmt.Errorf("error getting container token: %v", err)
1709 runner.ContainerArvClient, runner.ContainerKeepClient,
1710 runner.containerClient, err = runner.MkArvClient(containerToken)
1712 return fmt.Errorf("error creating container API client: %v", err)
1715 err = runner.ContainerArvClient.Call("GET", "containers", runner.Container.UUID, "secret_mounts", nil, &sm)
1717 if apierr, ok := err.(arvadosclient.APIServerError); !ok || apierr.HttpStatusCode != 404 {
1718 return fmt.Errorf("error fetching secret_mounts: %v", err)
1720 // ok && apierr.HttpStatusCode == 404, which means
1721 // secret_mounts isn't supported by this API server.
1723 runner.SecretMounts = sm.SecretMounts
1728 // NewContainerRunner creates a new container runner.
1729 func NewContainerRunner(dispatcherClient *arvados.Client,
1730 dispatcherArvClient IArvadosClient,
1731 dispatcherKeepClient IKeepClient,
1732 docker ThinDockerClient,
1733 containerUUID string) (*ContainerRunner, error) {
1735 cr := &ContainerRunner{
1736 dispatcherClient: dispatcherClient,
1737 DispatcherArvClient: dispatcherArvClient,
1738 DispatcherKeepClient: dispatcherKeepClient,
1741 cr.NewLogWriter = cr.NewArvLogWriter
1742 cr.RunArvMount = cr.ArvMountCmd
1743 cr.MkTempDir = ioutil.TempDir
1744 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1745 cl, err := arvadosclient.MakeArvadosClient()
1747 return nil, nil, nil, err
1750 kc, err := keepclient.MakeKeepClient(cl)
1752 return nil, nil, nil, err
1754 c2 := arvados.NewClientFromEnv()
1755 c2.AuthToken = token
1756 return cl, kc, c2, nil
1759 cr.LogCollection, err = (&arvados.Collection{}).FileSystem(cr.dispatcherClient, cr.DispatcherKeepClient)
1763 cr.Container.UUID = containerUUID
1764 w, err := cr.NewLogWriter("crunch-run")
1768 cr.CrunchLog = NewThrottledLogger(w)
1769 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1771 loadLogThrottleParams(dispatcherArvClient)
1778 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1779 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1780 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1781 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1782 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1783 detach := flag.Bool("detach", false, "Detach from parent process and run in the background")
1784 stdinEnv := flag.Bool("stdin-env", false, "Load environment variables from JSON message on stdin")
1785 sleep := flag.Duration("sleep", 0, "Delay before starting (testing use only)")
1786 kill := flag.Int("kill", -1, "Send signal to an existing crunch-run process for given UUID")
1787 list := flag.Bool("list", false, "List UUIDs of existing crunch-run processes")
1788 enableNetwork := flag.String("container-enable-networking", "default",
1789 `Specify if networking should be enabled for container. One of 'default', 'always':
1790 default: only enable networking if container requests it.
1791 always: containers always have networking enabled
1793 networkMode := flag.String("container-network-mode", "default",
1794 `Set networking mode for container. Corresponds to Docker network mode (--net).
1796 memprofile := flag.String("memprofile", "", "write memory profile to `file` after running container")
1797 getVersion := flag.Bool("version", false, "Print version information and exit.")
1798 flag.Duration("check-containerd", 0, "Ignored. Exists for compatibility with older versions.")
1800 ignoreDetachFlag := false
1801 if len(os.Args) > 1 && os.Args[1] == "-no-detach" {
1802 // This process was invoked by a parent process, which
1803 // has passed along its own arguments, including
1804 // -detach, after the leading -no-detach flag. Strip
1805 // the leading -no-detach flag (it's not recognized by
1806 // flag.Parse()) and ignore the -detach flag that
1808 os.Args = append([]string{os.Args[0]}, os.Args[2:]...)
1809 ignoreDetachFlag = true
1814 var env map[string]interface{}
1815 if *stdinEnv && !ignoreDetachFlag {
1816 // Load env vars on stdin if asked (but not in a
1817 // detached child process, in which case stdin is
1819 env = loadEnv(os.Stdin)
1823 case *detach && !ignoreDetachFlag:
1824 os.Exit(Detach(flag.Arg(0), os.Args, os.Stdout, os.Stderr))
1826 os.Exit(KillProcess(flag.Arg(0), syscall.Signal(*kill), os.Stdout, os.Stderr))
1828 os.Exit(ListProcesses(os.Stdout, os.Stderr))
1831 // Print version information if requested
1833 fmt.Printf("crunch-run %s\n", version)
1837 log.Printf("crunch-run %s started", version)
1840 containerId := flag.Arg(0)
1842 if *caCertsPath != "" {
1843 arvadosclient.CertFiles = []string{*caCertsPath}
1846 api, err := arvadosclient.MakeArvadosClient()
1848 log.Fatalf("%s: %v", containerId, err)
1852 kc, kcerr := keepclient.MakeKeepClient(api)
1854 log.Fatalf("%s: %v", containerId, kcerr)
1856 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1859 // API version 1.21 corresponds to Docker 1.9, which is currently the
1860 // minimum version we want to support.
1861 docker, dockererr := dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1863 cr, err := NewContainerRunner(arvados.NewClientFromEnv(), api, kc, docker, containerId)
1867 if dockererr != nil {
1868 cr.CrunchLog.Printf("%s: %v", containerId, dockererr)
1869 cr.checkBrokenNode(dockererr)
1870 cr.CrunchLog.Close()
1874 cr.dispatchEnv = env
1876 parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerId+".")
1878 log.Fatalf("%s: %v", containerId, tmperr)
1881 cr.parentTemp = parentTemp
1882 cr.statInterval = *statInterval
1883 cr.cgroupRoot = *cgroupRoot
1884 cr.expectCgroupParent = *cgroupParent
1885 cr.enableNetwork = *enableNetwork
1886 cr.networkMode = *networkMode
1887 if *cgroupParentSubsystem != "" {
1888 p := findCgroup(*cgroupParentSubsystem)
1889 cr.setCgroupParent = p
1890 cr.expectCgroupParent = p
1895 if *memprofile != "" {
1896 f, err := os.Create(*memprofile)
1898 log.Printf("could not create memory profile: %s", err)
1900 runtime.GC() // get up-to-date statistics
1901 if err := pprof.WriteHeapProfile(f); err != nil {
1902 log.Printf("could not write memory profile: %s", err)
1904 closeerr := f.Close()
1905 if closeerr != nil {
1906 log.Printf("closing memprofile file: %s", err)
1911 log.Fatalf("%s: %v", containerId, runerr)
1915 func loadEnv(rdr io.Reader) map[string]interface{} {
1916 buf, err := ioutil.ReadAll(rdr)
1918 log.Fatalf("read stdin: %s", err)
1920 var env map[string]interface{}
1921 err = json.Unmarshal(buf, &env)
1923 log.Fatalf("decode stdin: %s", err)
1925 for k, v := range env {
1926 if v, ok := v.(string); ok {
1927 err = os.Setenv(k, v)
1929 log.Fatalf("setenv(%q): %s", k, err)