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 PutHB(hash string, buf []byte) (string, int, error)
61 ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error)
65 // NewLogWriter is a factory function to create a new log writer.
66 type NewLogWriter func(name string) io.WriteCloser
68 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
70 type MkTempDir func(string, string) (string, error)
72 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
73 type ThinDockerClient interface {
74 ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error)
75 ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
76 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error)
77 ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error
78 ContainerRemove(ctx context.Context, container string, options dockertypes.ContainerRemoveOptions) error
79 ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error)
80 ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error)
81 ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error)
82 ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error)
85 // ContainerRunner is the main stateful struct used for a single execution of a
87 type ContainerRunner struct {
88 Docker ThinDockerClient
89 ArvClient IArvadosClient
92 ContainerConfig dockercontainer.Config
93 dockercontainer.HostConfig
99 CrunchLog *ThrottledLogger
100 Stdout io.WriteCloser
101 Stderr io.WriteCloser
102 LogCollection *CollectionWriter
109 CleanupTempDir []string
111 Volumes map[string]struct{}
113 SigChan chan os.Signal
114 ArvMountExit chan error
117 statLogger io.WriteCloser
118 statReporter *crunchstat.Reporter
119 statInterval time.Duration
121 // What we expect the container's cgroup parent to be.
122 expectCgroupParent string
123 // What we tell docker to use as the container's cgroup
124 // parent. Note: Ideally we would use the same field for both
125 // expectCgroupParent and setCgroupParent, and just make it
126 // default to "docker". However, when using docker < 1.10 with
127 // systemd, specifying a non-empty cgroup parent (even the
128 // default value "docker") hits a docker bug
129 // (https://github.com/docker/docker/issues/17126). Using two
130 // separate fields makes it possible to use the "expect cgroup
131 // parent to be X" feature even on sites where the "specify
132 // cgroup parent" feature breaks.
133 setCgroupParent string
135 cStateLock sync.Mutex
136 cStarted bool // StartContainer() succeeded
137 cCancelled bool // StopContainer() invoked
139 enableNetwork string // one of "default" or "always"
140 networkMode string // passed through to HostConfig.NetworkMode
141 arvMountLog *ThrottledLogger
144 // setupSignals sets up signal handling to gracefully terminate the underlying
145 // Docker container and update state when receiving a TERM, INT or QUIT signal.
146 func (runner *ContainerRunner) setupSignals() {
147 runner.SigChan = make(chan os.Signal, 1)
148 signal.Notify(runner.SigChan, syscall.SIGTERM)
149 signal.Notify(runner.SigChan, syscall.SIGINT)
150 signal.Notify(runner.SigChan, syscall.SIGQUIT)
152 go func(sig chan os.Signal) {
154 runner.CrunchLog.Printf("caught signal: %v", s)
160 // stop the underlying Docker container.
161 func (runner *ContainerRunner) stop() {
162 runner.cStateLock.Lock()
163 defer runner.cStateLock.Unlock()
164 if !runner.cStarted {
167 runner.cCancelled = true
168 runner.CrunchLog.Printf("removing container")
169 err := runner.Docker.ContainerRemove(context.TODO(), runner.ContainerID, dockertypes.ContainerRemoveOptions{Force: true})
171 runner.CrunchLog.Printf("error removing container: %s", err)
175 func (runner *ContainerRunner) stopSignals() {
176 if runner.SigChan != nil {
177 signal.Stop(runner.SigChan)
181 var errorBlacklist = []string{
182 "(?ms).*[Cc]annot connect to the Docker daemon.*",
183 "(?ms).*oci runtime error.*starting container process.*container init.*mounting.*to rootfs.*no such file or directory.*",
185 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)")
187 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
188 for _, d := range errorBlacklist {
189 if m, e := regexp.MatchString(d, goterr.Error()); m && e == nil {
190 runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
191 if *brokenNodeHook == "" {
192 runner.CrunchLog.Printf("No broken node hook provided, cannot mark node as broken.")
194 runner.CrunchLog.Printf("Running broken node hook %q", *brokenNodeHook)
196 c := exec.Command(*brokenNodeHook)
197 c.Stdout = runner.CrunchLog
198 c.Stderr = runner.CrunchLog
201 runner.CrunchLog.Printf("Error running broken node hook: %v", err)
210 // LoadImage determines the docker image id from the container record and
211 // checks if it is available in the local Docker image store. If not, it loads
212 // the image from Keep.
213 func (runner *ContainerRunner) LoadImage() (err error) {
215 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
217 var collection arvados.Collection
218 err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
220 return fmt.Errorf("While getting container image collection: %v", err)
222 manifest := manifest.Manifest{Text: collection.ManifestText}
223 var img, imageID string
224 for ms := range manifest.StreamIter() {
225 img = ms.FileStreamSegments[0].Name
226 if !strings.HasSuffix(img, ".tar") {
227 return fmt.Errorf("First file in the container image collection does not end in .tar")
229 imageID = img[:len(img)-4]
232 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
234 _, _, err = runner.Docker.ImageInspectWithRaw(context.TODO(), imageID)
236 runner.CrunchLog.Print("Loading Docker image from keep")
238 var readCloser io.ReadCloser
239 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
241 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
244 response, err := runner.Docker.ImageLoad(context.TODO(), readCloser, true)
246 return fmt.Errorf("While loading container image into Docker: %v", err)
249 defer response.Body.Close()
250 rbody, err := ioutil.ReadAll(response.Body)
252 return fmt.Errorf("Reading response to image load: %v", err)
254 runner.CrunchLog.Printf("Docker response: %s", rbody)
256 runner.CrunchLog.Print("Docker image is available")
259 runner.ContainerConfig.Image = imageID
261 runner.Kc.ClearBlockCache()
266 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
267 c = exec.Command("arv-mount", arvMountCmd...)
269 // Copy our environment, but override ARVADOS_API_TOKEN with
270 // the container auth token.
272 for _, s := range os.Environ() {
273 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
274 c.Env = append(c.Env, s)
277 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
279 runner.arvMountLog = NewThrottledLogger(runner.NewLogWriter("arv-mount"))
280 c.Stdout = runner.arvMountLog
281 c.Stderr = runner.arvMountLog
283 runner.CrunchLog.Printf("Running %v", c.Args)
290 statReadme := make(chan bool)
291 runner.ArvMountExit = make(chan error)
296 time.Sleep(100 * time.Millisecond)
297 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
309 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
311 runner.ArvMountExit <- mnterr
312 close(runner.ArvMountExit)
318 case err := <-runner.ArvMountExit:
319 runner.ArvMount = nil
327 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
328 if runner.ArvMountPoint == "" {
329 runner.ArvMountPoint, err = runner.MkTempDir("", prefix)
334 func (runner *ContainerRunner) SetupMounts() (err error) {
335 err = runner.SetupArvMountPoint("keep")
337 return fmt.Errorf("While creating keep mount temp dir: %v", err)
340 token, err := runner.ContainerToken()
342 return fmt.Errorf("could not get container token: %s", err)
347 arvMountCmd := []string{
351 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
353 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
354 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
357 collectionPaths := []string{}
359 runner.Volumes = make(map[string]struct{})
360 needCertMount := true
363 for bind := range runner.Container.Mounts {
364 binds = append(binds, bind)
368 for _, bind := range binds {
369 mnt := runner.Container.Mounts[bind]
370 if bind == "stdout" || bind == "stderr" {
371 // Is it a "file" mount kind?
372 if mnt.Kind != "file" {
373 return fmt.Errorf("Unsupported mount kind '%s' for %s. Only 'file' is supported.", mnt.Kind, bind)
376 // Does path start with OutputPath?
377 prefix := runner.Container.OutputPath
378 if !strings.HasSuffix(prefix, "/") {
381 if !strings.HasPrefix(mnt.Path, prefix) {
382 return fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
387 // Is it a "collection" mount kind?
388 if mnt.Kind != "collection" && mnt.Kind != "json" {
389 return fmt.Errorf("Unsupported mount kind '%s' for stdin. Only 'collection' or 'json' are supported.", mnt.Kind)
393 if bind == "/etc/arvados/ca-certificates.crt" {
394 needCertMount = false
397 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
398 if mnt.Kind != "collection" {
399 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
404 case mnt.Kind == "collection" && bind != "stdin":
406 if mnt.UUID != "" && mnt.PortableDataHash != "" {
407 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
411 return fmt.Errorf("Writing to existing collections currently not permitted.")
414 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
415 } else if mnt.PortableDataHash != "" {
417 return fmt.Errorf("Can never write to a collection specified by portable data hash")
419 idx := strings.Index(mnt.PortableDataHash, "/")
421 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
422 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
423 runner.Container.Mounts[bind] = mnt
425 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
426 if mnt.Path != "" && mnt.Path != "." {
427 if strings.HasPrefix(mnt.Path, "./") {
428 mnt.Path = mnt.Path[2:]
429 } else if strings.HasPrefix(mnt.Path, "/") {
430 mnt.Path = mnt.Path[1:]
432 src += "/" + mnt.Path
435 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
436 arvMountCmd = append(arvMountCmd, "--mount-tmp")
437 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
441 if bind == runner.Container.OutputPath {
442 runner.HostOutputDir = src
443 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
444 return fmt.Errorf("Writable mount points are not permitted underneath the output_path: %v", bind)
446 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
448 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
450 collectionPaths = append(collectionPaths, src)
452 case mnt.Kind == "tmp":
454 tmpdir, err = runner.MkTempDir("", "")
456 return fmt.Errorf("While creating mount temp dir: %v", err)
458 st, staterr := os.Stat(tmpdir)
460 return fmt.Errorf("While Stat on temp dir: %v", staterr)
462 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
464 return fmt.Errorf("While Chmod temp dir: %v", err)
466 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
467 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", tmpdir, bind))
468 if bind == runner.Container.OutputPath {
469 runner.HostOutputDir = tmpdir
472 case mnt.Kind == "json":
473 jsondata, err := json.Marshal(mnt.Content)
475 return fmt.Errorf("encoding json data: %v", err)
477 // Create a tempdir with a single file
478 // (instead of just a tempfile): this way we
479 // can ensure the file is world-readable
480 // inside the container, without having to
481 // make it world-readable on the docker host.
482 tmpdir, err := runner.MkTempDir("", "")
484 return fmt.Errorf("creating temp dir: %v", err)
486 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
487 tmpfn := filepath.Join(tmpdir, "mountdata.json")
488 err = ioutil.WriteFile(tmpfn, jsondata, 0644)
490 return fmt.Errorf("writing temp file: %v", err)
492 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
494 case mnt.Kind == "git_tree":
495 tmpdir, err := runner.MkTempDir("", "")
497 return fmt.Errorf("creating temp dir: %v", err)
499 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
500 err = gitMount(mnt).extractTree(runner.ArvClient, tmpdir, token)
504 runner.Binds = append(runner.Binds, tmpdir+":"+bind+":ro")
508 if runner.HostOutputDir == "" {
509 return fmt.Errorf("Output path does not correspond to a writable mount point")
512 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
513 for _, certfile := range arvadosclient.CertFiles {
514 _, err := os.Stat(certfile)
516 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
523 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
525 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
527 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
529 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
531 return fmt.Errorf("While trying to start arv-mount: %v", err)
534 for _, p := range collectionPaths {
537 return fmt.Errorf("While checking that input files exist: %v", err)
544 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
545 // Handle docker log protocol
546 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
548 header := make([]byte, 8)
550 _, readerr := io.ReadAtLeast(containerReader, header, 8)
553 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
556 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
559 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
564 if readerr != io.EOF {
565 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
568 closeerr := runner.Stdout.Close()
570 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
573 closeerr = runner.Stderr.Close()
575 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
578 if runner.statReporter != nil {
579 runner.statReporter.Stop()
580 closeerr = runner.statLogger.Close()
582 runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
586 runner.loggingDone <- true
587 close(runner.loggingDone)
593 func (runner *ContainerRunner) StartCrunchstat() {
594 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
595 runner.statReporter = &crunchstat.Reporter{
596 CID: runner.ContainerID,
597 Logger: log.New(runner.statLogger, "", 0),
598 CgroupParent: runner.expectCgroupParent,
599 CgroupRoot: runner.cgroupRoot,
600 PollPeriod: runner.statInterval,
602 runner.statReporter.Start()
605 type infoCommand struct {
610 // LogHostInfo logs info about the current host, for debugging and
611 // accounting purposes. Although it's logged as "node-info", this is
612 // about the environment where crunch-run is actually running, which
613 // might differ from what's described in the node record (see
615 func (runner *ContainerRunner) LogHostInfo() (err error) {
616 w := runner.NewLogWriter("node-info")
618 commands := []infoCommand{
620 label: "Host Information",
621 cmd: []string{"uname", "-a"},
624 label: "CPU Information",
625 cmd: []string{"cat", "/proc/cpuinfo"},
628 label: "Memory Information",
629 cmd: []string{"cat", "/proc/meminfo"},
633 cmd: []string{"df", "-m", "/", os.TempDir()},
636 label: "Disk INodes",
637 cmd: []string{"df", "-i", "/", os.TempDir()},
641 // Run commands with informational output to be logged.
642 for _, command := range commands {
643 fmt.Fprintln(w, command.label)
644 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
647 if err := cmd.Run(); err != nil {
648 err = fmt.Errorf("While running command %q: %v", command.cmd, err)
657 return fmt.Errorf("While closing node-info logs: %v", err)
662 // LogContainerRecord gets and saves the raw JSON container record from the API server
663 func (runner *ContainerRunner) LogContainerRecord() error {
664 logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
665 if !logged && err == nil {
666 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
671 // LogNodeRecord logs arvados#node record corresponding to the current host.
672 func (runner *ContainerRunner) LogNodeRecord() error {
673 hostname := os.Getenv("SLURMD_NODENAME")
675 hostname, _ = os.Hostname()
677 _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
678 // The "info" field has admin-only info when obtained
679 // with a privileged token, and should not be logged.
680 node, ok := resp.(map[string]interface{})
688 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
690 ArvClient: runner.ArvClient,
691 UUID: runner.Container.UUID,
692 loggingStream: label,
693 writeCloser: runner.LogCollection.Open(label + ".json"),
696 reader, err := runner.ArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
698 return false, fmt.Errorf("error getting %s record: %v", label, err)
702 dec := json.NewDecoder(reader)
704 var resp map[string]interface{}
705 if err = dec.Decode(&resp); err != nil {
706 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
708 items, ok := resp["items"].([]interface{})
710 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
711 } else if len(items) < 1 {
717 // Re-encode it using indentation to improve readability
718 enc := json.NewEncoder(w)
719 enc.SetIndent("", " ")
720 if err = enc.Encode(items[0]); err != nil {
721 return false, fmt.Errorf("error logging %s record: %v", label, err)
725 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
730 // AttachStreams connects the docker container stdin, stdout and stderr logs
731 // to the Arvados logger which logs to Keep and the API server logs table.
732 func (runner *ContainerRunner) AttachStreams() (err error) {
734 runner.CrunchLog.Print("Attaching container streams")
736 // If stdin mount is provided, attach it to the docker container
737 var stdinRdr arvados.File
739 if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
740 if stdinMnt.Kind == "collection" {
741 var stdinColl arvados.Collection
742 collId := stdinMnt.UUID
744 collId = stdinMnt.PortableDataHash
746 err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
748 return fmt.Errorf("While getting stding collection: %v", err)
751 stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
752 if os.IsNotExist(err) {
753 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
754 } else if err != nil {
755 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
757 } else if stdinMnt.Kind == "json" {
758 stdinJson, err = json.Marshal(stdinMnt.Content)
760 return fmt.Errorf("While encoding stdin json data: %v", err)
765 stdinUsed := stdinRdr != nil || len(stdinJson) != 0
766 response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
767 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
769 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
772 runner.loggingDone = make(chan bool)
774 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
775 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
779 runner.Stdout = stdoutFile
781 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
784 if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
785 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
789 runner.Stderr = stderrFile
791 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
796 _, err := io.Copy(response.Conn, stdinRdr)
798 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
802 response.CloseWrite()
804 } else if len(stdinJson) != 0 {
806 _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
808 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
811 response.CloseWrite()
815 go runner.ProcessDockerAttach(response.Reader)
820 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
821 stdoutPath := mntPath[len(runner.Container.OutputPath):]
822 index := strings.LastIndex(stdoutPath, "/")
824 subdirs := stdoutPath[:index]
826 st, err := os.Stat(runner.HostOutputDir)
828 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
830 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
831 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
833 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
837 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
839 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
842 return stdoutFile, nil
845 // CreateContainer creates the docker container.
846 func (runner *ContainerRunner) CreateContainer() error {
847 runner.CrunchLog.Print("Creating Docker container")
849 runner.ContainerConfig.Cmd = runner.Container.Command
850 if runner.Container.Cwd != "." {
851 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
854 for k, v := range runner.Container.Environment {
855 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
858 runner.ContainerConfig.Volumes = runner.Volumes
860 runner.HostConfig = dockercontainer.HostConfig{
862 LogConfig: dockercontainer.LogConfig{
865 Resources: dockercontainer.Resources{
866 CgroupParent: runner.setCgroupParent,
870 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
871 tok, err := runner.ContainerToken()
875 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
876 "ARVADOS_API_TOKEN="+tok,
877 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
878 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
880 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
882 if runner.enableNetwork == "always" {
883 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
885 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
889 _, stdinUsed := runner.Container.Mounts["stdin"]
890 runner.ContainerConfig.OpenStdin = stdinUsed
891 runner.ContainerConfig.StdinOnce = stdinUsed
892 runner.ContainerConfig.AttachStdin = stdinUsed
893 runner.ContainerConfig.AttachStdout = true
894 runner.ContainerConfig.AttachStderr = true
896 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
898 return fmt.Errorf("While creating container: %v", err)
901 runner.ContainerID = createdBody.ID
903 return runner.AttachStreams()
906 // StartContainer starts the docker container created by CreateContainer.
907 func (runner *ContainerRunner) StartContainer() error {
908 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
909 runner.cStateLock.Lock()
910 defer runner.cStateLock.Unlock()
911 if runner.cCancelled {
914 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
915 dockertypes.ContainerStartOptions{})
918 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
919 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])
921 return fmt.Errorf("could not start container: %v%s", err, advice)
923 runner.cStarted = true
927 // WaitFinish waits for the container to terminate, capture the exit code, and
928 // close the stdout/stderr logging.
929 func (runner *ContainerRunner) WaitFinish() (err error) {
930 runner.CrunchLog.Print("Waiting for container to finish")
932 waitOk, waitErr := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID, dockercontainer.WaitConditionNotRunning)
935 <-runner.ArvMountExit
937 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
942 var waitBody dockercontainer.ContainerWaitOKBody
944 case waitBody = <-waitOk:
945 case err = <-waitErr:
948 // Container isn't running any more
949 runner.cStarted = false
952 return fmt.Errorf("container wait: %v", err)
955 runner.CrunchLog.Printf("Container exited with code: %v", waitBody.StatusCode)
956 code := int(waitBody.StatusCode)
957 runner.ExitCode = &code
959 // wait for stdout/stderr to complete
965 var ErrNotInOutputDir = fmt.Errorf("Must point to path within the output directory")
967 func (runner *ContainerRunner) derefOutputSymlink(path string, startinfo os.FileInfo) (tgt string, readlinktgt string, info os.FileInfo, err error) {
968 // Follow symlinks if necessary
973 for followed := 0; info.Mode()&os.ModeSymlink != 0; followed++ {
974 if followed >= limitFollowSymlinks {
975 // Got stuck in a loop or just a pathological number of links, give up.
976 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
980 readlinktgt, err = os.Readlink(nextlink)
986 if !strings.HasPrefix(tgt, "/") {
987 // Relative symlink, resolve it to host path
988 tgt = filepath.Join(filepath.Dir(path), tgt)
990 if strings.HasPrefix(tgt, runner.Container.OutputPath+"/") && !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
991 // Absolute symlink to container output path, adjust it to host output path.
992 tgt = filepath.Join(runner.HostOutputDir, tgt[len(runner.Container.OutputPath):])
994 if !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
995 // After dereferencing, symlink target must either be
996 // within output directory, or must point to a
998 err = ErrNotInOutputDir
1002 info, err = os.Lstat(tgt)
1005 err = fmt.Errorf("Symlink in output %q points to invalid location %q: %v",
1006 path[len(runner.HostOutputDir):], readlinktgt, err)
1016 var limitFollowSymlinks = 10
1018 // UploadFile uploads files within the output directory, with special handling
1019 // for symlinks. If the symlink leads to a keep mount, copy the manifest text
1020 // from the keep mount into the output manifestText. Ensure that whether
1021 // symlinks are relative or absolute, every symlink target (even targets that
1022 // are symlinks themselves) must point to a path in either the output directory
1023 // or a collection mount.
1025 // Assumes initial value of "path" is absolute, and located within runner.HostOutputDir.
1026 func (runner *ContainerRunner) UploadOutputFile(
1031 walkUpload *WalkUpload,
1032 relocateFrom string,
1034 followed int) (manifestText string, err error) {
1040 if info.Mode().IsDir() {
1041 // if empty, need to create a .keep file
1042 dir, direrr := os.Open(path)
1047 names, eof := dir.Readdirnames(1)
1048 if len(names) == 0 && eof == io.EOF && path != runner.HostOutputDir {
1049 containerPath := runner.OutputPath + path[len(runner.HostOutputDir):]
1050 for _, bind := range binds {
1051 mnt := runner.Container.Mounts[bind]
1052 // Check if there is a bind for this
1053 // directory, in which case assume we don't need .keep
1054 if (containerPath == bind || strings.HasPrefix(containerPath, bind+"/")) && mnt.PortableDataHash != "d41d8cd98f00b204e9800998ecf8427e+0" {
1058 outputSuffix := path[len(runner.HostOutputDir)+1:]
1059 return fmt.Sprintf("./%v d41d8cd98f00b204e9800998ecf8427e+0 0:0:.keep\n", outputSuffix), nil
1064 if followed >= limitFollowSymlinks {
1065 // Got stuck in a loop or just a pathological number of
1066 // directory links, give up.
1067 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
1071 // "path" is the actual path we are visiting
1072 // "tgt" is the target of "path" (a non-symlink) after following symlinks
1073 // "relocated" is the path in the output manifest where the file should be placed,
1074 // but has HostOutputDir as a prefix.
1076 // The destination path in the output manifest may need to be
1077 // logically relocated to some other path in order to appear
1078 // in the correct location as a result of following a symlink.
1079 // Remove the relocateFrom prefix and replace it with
1081 relocated := relocateTo + path[len(relocateFrom):]
1083 tgt, readlinktgt, info, derefErr := runner.derefOutputSymlink(path, info)
1084 if derefErr != nil && derefErr != ErrNotInOutputDir {
1088 // go through mounts and try reverse map to collection reference
1089 for _, bind := range binds {
1090 mnt := runner.Container.Mounts[bind]
1091 if tgt == bind || strings.HasPrefix(tgt, bind+"/") {
1092 // get path relative to bind
1093 targetSuffix := tgt[len(bind):]
1095 // Copy mount and adjust the path to add path relative to the bind
1096 adjustedMount := mnt
1097 adjustedMount.Path = filepath.Join(adjustedMount.Path, targetSuffix)
1099 // Terminates in this keep mount, so add the
1100 // manifest text at appropriate location.
1101 outputSuffix := relocated[len(runner.HostOutputDir):]
1102 manifestText, err = runner.getCollectionManifestForPath(adjustedMount, outputSuffix)
1107 // If target is not a collection mount, it must be located within the
1108 // output directory, otherwise it is an error.
1109 if derefErr == ErrNotInOutputDir {
1110 err = fmt.Errorf("Symlink in output %q points to invalid location %q, must point to path within the output directory.",
1111 path[len(runner.HostOutputDir):], readlinktgt)
1115 if info.Mode().IsRegular() {
1116 return "", walkUpload.UploadFile(relocated, tgt)
1119 if info.Mode().IsDir() {
1120 // Symlink leads to directory. Walk() doesn't follow
1121 // directory symlinks, so we walk the target directory
1122 // instead. Within the walk, file paths are relocated
1123 // so they appear under the original symlink path.
1124 err = filepath.Walk(tgt, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
1126 m, walkerr = runner.UploadOutputFile(walkpath, walkinfo, walkerr,
1127 binds, walkUpload, tgt, relocated, followed+1)
1129 manifestText = manifestText + m
1139 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
1140 func (runner *ContainerRunner) CaptureOutput() error {
1141 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
1142 // Output may have been set directly by the container, so
1143 // refresh the container record to check.
1144 err := runner.ArvClient.Get("containers", runner.Container.UUID,
1145 nil, &runner.Container)
1149 if runner.Container.Output != "" {
1150 // Container output is already set.
1151 runner.OutputPDH = &runner.Container.Output
1156 if runner.HostOutputDir == "" {
1160 _, err := os.Stat(runner.HostOutputDir)
1162 return fmt.Errorf("While checking host output path: %v", err)
1165 // Pre-populate output from the configured mount points
1167 for bind, mnt := range runner.Container.Mounts {
1168 if mnt.Kind == "collection" {
1169 binds = append(binds, bind)
1174 var manifestText string
1176 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
1177 _, err = os.Stat(collectionMetafile)
1179 // Regular directory
1181 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
1182 walkUpload := cw.BeginUpload(runner.HostOutputDir, runner.CrunchLog.Logger)
1185 err = filepath.Walk(runner.HostOutputDir, func(path string, info os.FileInfo, err error) error {
1186 m, err = runner.UploadOutputFile(path, info, err, binds, walkUpload, "", "", 0)
1188 manifestText = manifestText + m
1193 cw.EndUpload(walkUpload)
1196 return fmt.Errorf("While uploading output files: %v", err)
1199 m, err = cw.ManifestText()
1200 manifestText = manifestText + m
1202 return fmt.Errorf("While uploading output files: %v", err)
1205 // FUSE mount directory
1206 file, openerr := os.Open(collectionMetafile)
1208 return fmt.Errorf("While opening FUSE metafile: %v", err)
1212 var rec arvados.Collection
1213 err = json.NewDecoder(file).Decode(&rec)
1215 return fmt.Errorf("While reading FUSE metafile: %v", err)
1217 manifestText = rec.ManifestText
1220 for _, bind := range binds {
1221 mnt := runner.Container.Mounts[bind]
1223 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
1225 if bindSuffix == bind || len(bindSuffix) <= 0 {
1226 // either does not start with OutputPath or is OutputPath itself
1230 if mnt.ExcludeFromOutput == true {
1234 // append to manifest_text
1235 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
1240 manifestText = manifestText + m
1244 var response arvados.Collection
1245 manifest := manifest.Manifest{Text: manifestText}
1246 manifestText = manifest.Extract(".", ".").Text
1247 err = runner.ArvClient.Create("collections",
1249 "ensure_unique_name": true,
1250 "collection": arvadosclient.Dict{
1252 "name": "output for " + runner.Container.UUID,
1253 "manifest_text": manifestText}},
1256 return fmt.Errorf("While creating output collection: %v", err)
1258 runner.OutputPDH = &response.PortableDataHash
1262 var outputCollections = make(map[string]arvados.Collection)
1264 // Fetch the collection for the mnt.PortableDataHash
1265 // Return the manifest_text fragment corresponding to the specified mnt.Path
1266 // after making any required updates.
1268 // If mnt.Path is not specified,
1269 // return the entire manifest_text after replacing any "." with bindSuffix
1270 // If mnt.Path corresponds to one stream,
1271 // return the manifest_text for that stream after replacing that stream name with bindSuffix
1272 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1273 // for that stream after replacing stream name with bindSuffix minus the last word
1274 // and the file name with last word of the bindSuffix
1275 // Allowed path examples:
1277 // "path":"/subdir1"
1278 // "path":"/subdir1/subdir2"
1279 // "path":"/subdir/filename" etc
1280 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1281 collection := outputCollections[mnt.PortableDataHash]
1282 if collection.PortableDataHash == "" {
1283 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1285 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1287 outputCollections[mnt.PortableDataHash] = collection
1290 if collection.ManifestText == "" {
1291 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1295 mft := manifest.Manifest{Text: collection.ManifestText}
1296 extracted := mft.Extract(mnt.Path, bindSuffix)
1297 if extracted.Err != nil {
1298 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1300 return extracted.Text, nil
1303 func (runner *ContainerRunner) CleanupDirs() {
1304 if runner.ArvMount != nil {
1306 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1307 umount.Stdout = runner.CrunchLog
1308 umount.Stderr = runner.CrunchLog
1309 runner.CrunchLog.Printf("Running %v", umount.Args)
1310 umnterr := umount.Start()
1313 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1315 // If arv-mount --unmount gets stuck for any reason, we
1316 // don't want to wait for it forever. Do Wait() in a goroutine
1317 // so it doesn't block crunch-run.
1318 umountExit := make(chan error)
1320 mnterr := umount.Wait()
1322 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1324 umountExit <- mnterr
1327 for again := true; again; {
1333 case <-runner.ArvMountExit:
1335 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1336 runner.CrunchLog.Printf("Timed out waiting for unmount")
1338 umount.Process.Kill()
1340 runner.ArvMount.Process.Kill()
1346 if runner.ArvMountPoint != "" {
1347 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1348 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1352 for _, tmpdir := range runner.CleanupTempDir {
1353 if rmerr := os.RemoveAll(tmpdir); rmerr != nil {
1354 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1359 // CommitLogs posts the collection containing the final container logs.
1360 func (runner *ContainerRunner) CommitLogs() error {
1361 runner.CrunchLog.Print(runner.finalState)
1363 if runner.arvMountLog != nil {
1364 runner.arvMountLog.Close()
1366 runner.CrunchLog.Close()
1368 // Closing CrunchLog above allows them to be committed to Keep at this
1369 // point, but re-open crunch log with ArvClient in case there are any
1370 // other further errors (such as failing to write the log to Keep!)
1371 // while shutting down
1372 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1373 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1374 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1376 if runner.LogsPDH != nil {
1377 // If we have already assigned something to LogsPDH,
1378 // we must be closing the re-opened log, which won't
1379 // end up getting attached to the container record and
1380 // therefore doesn't need to be saved as a collection
1381 // -- it exists only to send logs to other channels.
1385 mt, err := runner.LogCollection.ManifestText()
1387 return fmt.Errorf("While creating log manifest: %v", err)
1390 var response arvados.Collection
1391 err = runner.ArvClient.Create("collections",
1393 "ensure_unique_name": true,
1394 "collection": arvadosclient.Dict{
1396 "name": "logs for " + runner.Container.UUID,
1397 "manifest_text": mt}},
1400 return fmt.Errorf("While creating log collection: %v", err)
1402 runner.LogsPDH = &response.PortableDataHash
1406 // UpdateContainerRunning updates the container state to "Running"
1407 func (runner *ContainerRunner) UpdateContainerRunning() error {
1408 runner.cStateLock.Lock()
1409 defer runner.cStateLock.Unlock()
1410 if runner.cCancelled {
1413 return runner.ArvClient.Update("containers", runner.Container.UUID,
1414 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1417 // ContainerToken returns the api_token the container (and any
1418 // arv-mount processes) are allowed to use.
1419 func (runner *ContainerRunner) ContainerToken() (string, error) {
1420 if runner.token != "" {
1421 return runner.token, nil
1424 var auth arvados.APIClientAuthorization
1425 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1429 runner.token = auth.APIToken
1430 return runner.token, nil
1433 // UpdateContainerComplete updates the container record state on API
1434 // server to "Complete" or "Cancelled"
1435 func (runner *ContainerRunner) UpdateContainerFinal() error {
1436 update := arvadosclient.Dict{}
1437 update["state"] = runner.finalState
1438 if runner.LogsPDH != nil {
1439 update["log"] = *runner.LogsPDH
1441 if runner.finalState == "Complete" {
1442 if runner.ExitCode != nil {
1443 update["exit_code"] = *runner.ExitCode
1445 if runner.OutputPDH != nil {
1446 update["output"] = *runner.OutputPDH
1449 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1452 // IsCancelled returns the value of Cancelled, with goroutine safety.
1453 func (runner *ContainerRunner) IsCancelled() bool {
1454 runner.cStateLock.Lock()
1455 defer runner.cStateLock.Unlock()
1456 return runner.cCancelled
1459 // NewArvLogWriter creates an ArvLogWriter
1460 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1461 return &ArvLogWriter{
1462 ArvClient: runner.ArvClient,
1463 UUID: runner.Container.UUID,
1464 loggingStream: name,
1465 writeCloser: runner.LogCollection.Open(name + ".txt")}
1468 // Run the full container lifecycle.
1469 func (runner *ContainerRunner) Run() (err error) {
1470 runner.CrunchLog.Printf("crunch-run %s started", version)
1471 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1473 hostname, hosterr := os.Hostname()
1475 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1477 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1480 runner.finalState = "Queued"
1483 runner.stopSignals()
1484 runner.CleanupDirs()
1486 runner.CrunchLog.Printf("crunch-run finished")
1487 runner.CrunchLog.Close()
1491 // checkErr prints e (unless it's nil) and sets err to
1492 // e (unless err is already non-nil). Thus, if err
1493 // hasn't already been assigned when Run() returns,
1494 // this cleanup func will cause Run() to return the
1495 // first non-nil error that is passed to checkErr().
1496 checkErr := func(e error) {
1500 runner.CrunchLog.Print(e)
1504 if runner.finalState == "Complete" {
1505 // There was an error in the finalization.
1506 runner.finalState = "Cancelled"
1510 // Log the error encountered in Run(), if any
1513 if runner.finalState == "Queued" {
1514 runner.UpdateContainerFinal()
1518 if runner.IsCancelled() {
1519 runner.finalState = "Cancelled"
1520 // but don't return yet -- we still want to
1521 // capture partial output and write logs
1524 checkErr(runner.CaptureOutput())
1525 checkErr(runner.CommitLogs())
1526 checkErr(runner.UpdateContainerFinal())
1529 err = runner.fetchContainerRecord()
1534 // setup signal handling
1535 runner.setupSignals()
1537 // check for and/or load image
1538 err = runner.LoadImage()
1540 if !runner.checkBrokenNode(err) {
1541 // Failed to load image but not due to a "broken node"
1542 // condition, probably user error.
1543 runner.finalState = "Cancelled"
1545 err = fmt.Errorf("While loading container image: %v", err)
1549 // set up FUSE mount and binds
1550 err = runner.SetupMounts()
1552 runner.finalState = "Cancelled"
1553 err = fmt.Errorf("While setting up mounts: %v", err)
1557 err = runner.CreateContainer()
1561 err = runner.LogHostInfo()
1565 err = runner.LogNodeRecord()
1569 err = runner.LogContainerRecord()
1574 if runner.IsCancelled() {
1578 err = runner.UpdateContainerRunning()
1582 runner.finalState = "Cancelled"
1584 runner.StartCrunchstat()
1586 err = runner.StartContainer()
1588 runner.checkBrokenNode(err)
1592 err = runner.WaitFinish()
1593 if err == nil && !runner.IsCancelled() {
1594 runner.finalState = "Complete"
1599 // Fetch the current container record (uuid = runner.Container.UUID)
1600 // into runner.Container.
1601 func (runner *ContainerRunner) fetchContainerRecord() error {
1602 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1604 return fmt.Errorf("error fetching container record: %v", err)
1606 defer reader.Close()
1608 dec := json.NewDecoder(reader)
1610 err = dec.Decode(&runner.Container)
1612 return fmt.Errorf("error decoding container record: %v", err)
1617 // NewContainerRunner creates a new container runner.
1618 func NewContainerRunner(api IArvadosClient,
1620 docker ThinDockerClient,
1621 containerUUID string) *ContainerRunner {
1623 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1624 cr.NewLogWriter = cr.NewArvLogWriter
1625 cr.RunArvMount = cr.ArvMountCmd
1626 cr.MkTempDir = ioutil.TempDir
1627 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1628 cr.Container.UUID = containerUUID
1629 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1630 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1632 loadLogThrottleParams(api)
1638 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1639 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1640 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1641 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1642 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1643 enableNetwork := flag.String("container-enable-networking", "default",
1644 `Specify if networking should be enabled for container. One of 'default', 'always':
1645 default: only enable networking if container requests it.
1646 always: containers always have networking enabled
1648 networkMode := flag.String("container-network-mode", "default",
1649 `Set networking mode for container. Corresponds to Docker network mode (--net).
1651 memprofile := flag.String("memprofile", "", "write memory profile to `file` after running container")
1652 getVersion := flag.Bool("version", false, "Print version information and exit.")
1655 // Print version information if requested
1657 fmt.Printf("crunch-run %s\n", version)
1661 log.Printf("crunch-run %s started", version)
1663 containerId := flag.Arg(0)
1665 if *caCertsPath != "" {
1666 arvadosclient.CertFiles = []string{*caCertsPath}
1669 api, err := arvadosclient.MakeArvadosClient()
1671 log.Fatalf("%s: %v", containerId, err)
1675 kc, kcerr := keepclient.MakeKeepClient(api)
1677 log.Fatalf("%s: %v", containerId, kcerr)
1679 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1682 // API version 1.21 corresponds to Docker 1.9, which is currently the
1683 // minimum version we want to support.
1684 docker, dockererr := dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1686 cr := NewContainerRunner(api, kc, docker, containerId)
1687 if dockererr != nil {
1688 cr.CrunchLog.Printf("%s: %v", containerId, dockererr)
1689 cr.checkBrokenNode(dockererr)
1690 cr.CrunchLog.Close()
1694 cr.statInterval = *statInterval
1695 cr.cgroupRoot = *cgroupRoot
1696 cr.expectCgroupParent = *cgroupParent
1697 cr.enableNetwork = *enableNetwork
1698 cr.networkMode = *networkMode
1699 if *cgroupParentSubsystem != "" {
1700 p := findCgroup(*cgroupParentSubsystem)
1701 cr.setCgroupParent = p
1702 cr.expectCgroupParent = p
1707 if *memprofile != "" {
1708 f, err := os.Create(*memprofile)
1710 log.Printf("could not create memory profile: ", err)
1712 runtime.GC() // get up-to-date statistics
1713 if err := pprof.WriteHeapProfile(f); err != nil {
1714 log.Printf("could not write memory profile: ", err)
1716 closeerr := f.Close()
1717 if closeerr != nil {
1718 log.Printf("closing memprofile file: ", err)
1723 log.Fatalf("%s: %v", containerId, runerr)