1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
31 "git.curoverse.com/arvados.git/lib/crunchstat"
32 "git.curoverse.com/arvados.git/sdk/go/arvados"
33 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
34 "git.curoverse.com/arvados.git/sdk/go/keepclient"
35 "git.curoverse.com/arvados.git/sdk/go/manifest"
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 ContainerStop(ctx context.Context, container string, timeout *time.Duration) 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 // ThinDockerClientProxy is a proxy implementation of ThinDockerClient
86 // that executes the docker requests on dockerclient.Client
87 type ThinDockerClientProxy struct {
88 Docker *dockerclient.Client
91 // ContainerAttach invokes dockerclient.Client.ContainerAttach
92 func (proxy ThinDockerClientProxy) ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error) {
93 return proxy.Docker.ContainerAttach(ctx, container, options)
96 // ContainerCreate invokes dockerclient.Client.ContainerCreate
97 func (proxy ThinDockerClientProxy) ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
98 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error) {
99 return proxy.Docker.ContainerCreate(ctx, config, hostConfig, networkingConfig, containerName)
102 // ContainerStart invokes dockerclient.Client.ContainerStart
103 func (proxy ThinDockerClientProxy) ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error {
104 return proxy.Docker.ContainerStart(ctx, container, options)
107 // ContainerStop invokes dockerclient.Client.ContainerStop
108 func (proxy ThinDockerClientProxy) ContainerStop(ctx context.Context, container string, timeout *time.Duration) error {
109 return proxy.Docker.ContainerStop(ctx, container, timeout)
112 // ContainerWait invokes dockerclient.Client.ContainerWait
113 func (proxy ThinDockerClientProxy) ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error) {
114 return proxy.Docker.ContainerWait(ctx, container, condition)
117 // ImageInspectWithRaw invokes dockerclient.Client.ImageInspectWithRaw
118 func (proxy ThinDockerClientProxy) ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error) {
119 return proxy.Docker.ImageInspectWithRaw(ctx, image)
122 // ImageLoad invokes dockerclient.Client.ImageLoad
123 func (proxy ThinDockerClientProxy) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error) {
124 return proxy.Docker.ImageLoad(ctx, input, quiet)
127 // ImageRemove invokes dockerclient.Client.ImageRemove
128 func (proxy ThinDockerClientProxy) ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {
129 return proxy.Docker.ImageRemove(ctx, image, options)
132 // ContainerRunner is the main stateful struct used for a single execution of a
134 type ContainerRunner struct {
135 Docker ThinDockerClient
136 ArvClient IArvadosClient
139 ContainerConfig dockercontainer.Config
140 dockercontainer.HostConfig
145 loggingDone chan bool
146 CrunchLog *ThrottledLogger
147 Stdout io.WriteCloser
148 Stderr io.WriteCloser
149 LogCollection *CollectionWriter
156 CleanupTempDir []string
158 Volumes map[string]struct{}
160 SigChan chan os.Signal
161 ArvMountExit chan error
164 statLogger io.WriteCloser
165 statReporter *crunchstat.Reporter
166 statInterval time.Duration
168 // What we expect the container's cgroup parent to be.
169 expectCgroupParent string
170 // What we tell docker to use as the container's cgroup
171 // parent. Note: Ideally we would use the same field for both
172 // expectCgroupParent and setCgroupParent, and just make it
173 // default to "docker". However, when using docker < 1.10 with
174 // systemd, specifying a non-empty cgroup parent (even the
175 // default value "docker") hits a docker bug
176 // (https://github.com/docker/docker/issues/17126). Using two
177 // separate fields makes it possible to use the "expect cgroup
178 // parent to be X" feature even on sites where the "specify
179 // cgroup parent" feature breaks.
180 setCgroupParent string
182 cStateLock sync.Mutex
183 cStarted bool // StartContainer() succeeded
184 cCancelled bool // StopContainer() invoked
186 enableNetwork string // one of "default" or "always"
187 networkMode string // passed through to HostConfig.NetworkMode
188 arvMountLog *ThrottledLogger
191 // setupSignals sets up signal handling to gracefully terminate the underlying
192 // Docker container and update state when receiving a TERM, INT or QUIT signal.
193 func (runner *ContainerRunner) setupSignals() {
194 runner.SigChan = make(chan os.Signal, 1)
195 signal.Notify(runner.SigChan, syscall.SIGTERM)
196 signal.Notify(runner.SigChan, syscall.SIGINT)
197 signal.Notify(runner.SigChan, syscall.SIGQUIT)
199 go func(sig chan os.Signal) {
202 runner.CrunchLog.Printf("Caught signal %v", s)
208 // stop the underlying Docker container.
209 func (runner *ContainerRunner) stop() {
210 runner.cStateLock.Lock()
211 defer runner.cStateLock.Unlock()
212 if runner.cCancelled {
215 runner.cCancelled = true
217 timeout := time.Duration(10)
218 err := runner.Docker.ContainerStop(context.TODO(), runner.ContainerID, &(timeout))
220 runner.CrunchLog.Printf("StopContainer failed: %s", err)
222 // Suppress multiple calls to stop()
223 runner.cStarted = false
227 func (runner *ContainerRunner) stopSignals() {
228 if runner.SigChan != nil {
229 signal.Stop(runner.SigChan)
230 close(runner.SigChan)
234 var errorBlacklist = []string{
235 "(?ms).*[Cc]annot connect to the Docker daemon.*",
236 "(?ms).*oci runtime error.*starting container process.*container init.*mounting.*to rootfs.*no such file or directory.*",
238 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)")
240 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
241 for _, d := range errorBlacklist {
242 if m, e := regexp.MatchString(d, goterr.Error()); m && e == nil {
243 runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
244 if *brokenNodeHook == "" {
245 runner.CrunchLog.Printf("No broken node hook provided, cannot mark node as broken.")
247 runner.CrunchLog.Printf("Running broken node hook %q", *brokenNodeHook)
249 c := exec.Command(*brokenNodeHook)
250 c.Stdout = runner.CrunchLog
251 c.Stderr = runner.CrunchLog
254 runner.CrunchLog.Printf("Error running broken node hook: %v", err)
263 // LoadImage determines the docker image id from the container record and
264 // checks if it is available in the local Docker image store. If not, it loads
265 // the image from Keep.
266 func (runner *ContainerRunner) LoadImage() (err error) {
268 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
270 var collection arvados.Collection
271 err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
273 return fmt.Errorf("While getting container image collection: %v", err)
275 manifest := manifest.Manifest{Text: collection.ManifestText}
276 var img, imageID string
277 for ms := range manifest.StreamIter() {
278 img = ms.FileStreamSegments[0].Name
279 if !strings.HasSuffix(img, ".tar") {
280 return fmt.Errorf("First file in the container image collection does not end in .tar")
282 imageID = img[:len(img)-4]
285 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
287 _, _, err = runner.Docker.ImageInspectWithRaw(context.TODO(), imageID)
289 runner.CrunchLog.Print("Loading Docker image from keep")
291 var readCloser io.ReadCloser
292 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
294 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
297 response, err := runner.Docker.ImageLoad(context.TODO(), readCloser, true)
299 return fmt.Errorf("While loading container image into Docker: %v", err)
302 defer response.Body.Close()
303 rbody, err := ioutil.ReadAll(response.Body)
305 return fmt.Errorf("Reading response to image load: %v", err)
307 runner.CrunchLog.Printf("Docker response: %s", rbody)
309 runner.CrunchLog.Print("Docker image is available")
312 runner.ContainerConfig.Image = imageID
314 runner.Kc.ClearBlockCache()
319 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
320 c = exec.Command("arv-mount", arvMountCmd...)
322 // Copy our environment, but override ARVADOS_API_TOKEN with
323 // the container auth token.
325 for _, s := range os.Environ() {
326 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
327 c.Env = append(c.Env, s)
330 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
332 runner.arvMountLog = NewThrottledLogger(runner.NewLogWriter("arv-mount"))
333 c.Stdout = runner.arvMountLog
334 c.Stderr = runner.arvMountLog
336 runner.CrunchLog.Printf("Running %v", c.Args)
343 statReadme := make(chan bool)
344 runner.ArvMountExit = make(chan error)
349 time.Sleep(100 * time.Millisecond)
350 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
362 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
364 runner.ArvMountExit <- mnterr
365 close(runner.ArvMountExit)
371 case err := <-runner.ArvMountExit:
372 runner.ArvMount = nil
380 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
381 if runner.ArvMountPoint == "" {
382 runner.ArvMountPoint, err = runner.MkTempDir("", prefix)
387 func (runner *ContainerRunner) SetupMounts() (err error) {
388 err = runner.SetupArvMountPoint("keep")
390 return fmt.Errorf("While creating keep mount temp dir: %v", err)
393 token, err := runner.ContainerToken()
395 return fmt.Errorf("could not get container token: %s", err)
400 arvMountCmd := []string{
404 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
406 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
407 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
410 collectionPaths := []string{}
412 runner.Volumes = make(map[string]struct{})
413 needCertMount := true
416 for bind := range runner.Container.Mounts {
417 binds = append(binds, bind)
421 for _, bind := range binds {
422 mnt := runner.Container.Mounts[bind]
423 if bind == "stdout" || bind == "stderr" {
424 // Is it a "file" mount kind?
425 if mnt.Kind != "file" {
426 return fmt.Errorf("Unsupported mount kind '%s' for %s. Only 'file' is supported.", mnt.Kind, bind)
429 // Does path start with OutputPath?
430 prefix := runner.Container.OutputPath
431 if !strings.HasSuffix(prefix, "/") {
434 if !strings.HasPrefix(mnt.Path, prefix) {
435 return fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
440 // Is it a "collection" mount kind?
441 if mnt.Kind != "collection" && mnt.Kind != "json" {
442 return fmt.Errorf("Unsupported mount kind '%s' for stdin. Only 'collection' or 'json' are supported.", mnt.Kind)
446 if bind == "/etc/arvados/ca-certificates.crt" {
447 needCertMount = false
450 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
451 if mnt.Kind != "collection" {
452 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
457 case mnt.Kind == "collection" && bind != "stdin":
459 if mnt.UUID != "" && mnt.PortableDataHash != "" {
460 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
464 return fmt.Errorf("Writing to existing collections currently not permitted.")
467 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
468 } else if mnt.PortableDataHash != "" {
470 return fmt.Errorf("Can never write to a collection specified by portable data hash")
472 idx := strings.Index(mnt.PortableDataHash, "/")
474 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
475 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
476 runner.Container.Mounts[bind] = mnt
478 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
479 if mnt.Path != "" && mnt.Path != "." {
480 if strings.HasPrefix(mnt.Path, "./") {
481 mnt.Path = mnt.Path[2:]
482 } else if strings.HasPrefix(mnt.Path, "/") {
483 mnt.Path = mnt.Path[1:]
485 src += "/" + mnt.Path
488 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
489 arvMountCmd = append(arvMountCmd, "--mount-tmp")
490 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
494 if bind == runner.Container.OutputPath {
495 runner.HostOutputDir = src
496 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
497 return fmt.Errorf("Writable mount points are not permitted underneath the output_path: %v", bind)
499 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
501 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
503 collectionPaths = append(collectionPaths, src)
505 case mnt.Kind == "tmp":
507 tmpdir, err = runner.MkTempDir("", "")
509 return fmt.Errorf("While creating mount temp dir: %v", err)
511 st, staterr := os.Stat(tmpdir)
513 return fmt.Errorf("While Stat on temp dir: %v", staterr)
515 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
517 return fmt.Errorf("While Chmod temp dir: %v", err)
519 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
520 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", tmpdir, bind))
521 if bind == runner.Container.OutputPath {
522 runner.HostOutputDir = tmpdir
525 case mnt.Kind == "json":
526 jsondata, err := json.Marshal(mnt.Content)
528 return fmt.Errorf("encoding json data: %v", err)
530 // Create a tempdir with a single file
531 // (instead of just a tempfile): this way we
532 // can ensure the file is world-readable
533 // inside the container, without having to
534 // make it world-readable on the docker host.
535 tmpdir, err := runner.MkTempDir("", "")
537 return fmt.Errorf("creating temp dir: %v", err)
539 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
540 tmpfn := filepath.Join(tmpdir, "mountdata.json")
541 err = ioutil.WriteFile(tmpfn, jsondata, 0644)
543 return fmt.Errorf("writing temp file: %v", err)
545 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
547 case mnt.Kind == "git_tree":
548 tmpdir, err := runner.MkTempDir("", "")
550 return fmt.Errorf("creating temp dir: %v", err)
552 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
553 err = gitMount(mnt).extractTree(runner.ArvClient, tmpdir, token)
557 runner.Binds = append(runner.Binds, tmpdir+":"+bind+":ro")
561 if runner.HostOutputDir == "" {
562 return fmt.Errorf("Output path does not correspond to a writable mount point")
565 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
566 for _, certfile := range arvadosclient.CertFiles {
567 _, err := os.Stat(certfile)
569 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
576 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
578 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
580 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
582 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
584 return fmt.Errorf("While trying to start arv-mount: %v", err)
587 for _, p := range collectionPaths {
590 return fmt.Errorf("While checking that input files exist: %v", err)
597 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
598 // Handle docker log protocol
599 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
601 header := make([]byte, 8)
603 _, readerr := io.ReadAtLeast(containerReader, header, 8)
606 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
609 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
612 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
617 if readerr != io.EOF {
618 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
621 closeerr := runner.Stdout.Close()
623 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
626 closeerr = runner.Stderr.Close()
628 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
631 if runner.statReporter != nil {
632 runner.statReporter.Stop()
633 closeerr = runner.statLogger.Close()
635 runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
639 runner.loggingDone <- true
640 close(runner.loggingDone)
646 func (runner *ContainerRunner) StartCrunchstat() {
647 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
648 runner.statReporter = &crunchstat.Reporter{
649 CID: runner.ContainerID,
650 Logger: log.New(runner.statLogger, "", 0),
651 CgroupParent: runner.expectCgroupParent,
652 CgroupRoot: runner.cgroupRoot,
653 PollPeriod: runner.statInterval,
655 runner.statReporter.Start()
658 type infoCommand struct {
663 // LogNodeInfo gathers node information and logs it for debugging and
664 // accounting purposes.
665 func (runner *ContainerRunner) LogNodeInfo() (err error) {
666 w := runner.NewLogWriter("node-info")
668 hostname := os.Getenv("SLURMD_NODENAME")
670 hostname, _ = os.Hostname()
672 var nodes arvados.NodeList
673 err = runner.ArvClient.Call("GET", "nodes", "", "", map[string]interface{}{
674 "filters": [][]string{{"hostname", "=", hostname}},
677 return fmt.Errorf("Error retrieving node list: %s", err)
679 if len(nodes.Items) < 1 {
680 fmt.Fprintf(w, "Node record not available for hostname %s\n", hostname)
682 fmt.Fprintf(w, "Node properties for node %s with hostname %q\n", nodes.Items[0].UUID, hostname)
683 json.NewEncoder(w).Encode(nodes.Items[0].Properties)
687 commands := []infoCommand{
689 label: "Host Information",
690 cmd: []string{"uname", "-a"},
693 label: "CPU Information",
694 cmd: []string{"cat", "/proc/cpuinfo"},
697 label: "Memory Information",
698 cmd: []string{"cat", "/proc/meminfo"},
702 cmd: []string{"df", "-m", "/", os.TempDir()},
705 label: "Disk INodes",
706 cmd: []string{"df", "-i", "/", os.TempDir()},
710 // Run commands with informational output to be logged.
711 for _, command := range commands {
712 fmt.Fprintln(w, command.label)
713 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
716 if err := cmd.Run(); err != nil {
717 err = fmt.Errorf("While running command %q: %v", command.cmd, err)
726 return fmt.Errorf("While closing node-info logs: %v", err)
731 // LogContainerRecord gets and saves the raw JSON container record from the API server
732 func (runner *ContainerRunner) LogContainerRecord() (err error) {
734 ArvClient: runner.ArvClient,
735 UUID: runner.Container.UUID,
736 loggingStream: "container",
737 writeCloser: runner.LogCollection.Open("container.json"),
740 // Get Container record JSON from the API Server
741 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
743 return fmt.Errorf("While retrieving container record from the API server: %v", err)
747 dec := json.NewDecoder(reader)
749 var cr map[string]interface{}
750 if err = dec.Decode(&cr); err != nil {
751 return fmt.Errorf("While decoding the container record JSON response: %v", err)
753 // Re-encode it using indentation to improve readability
754 enc := json.NewEncoder(w)
755 enc.SetIndent("", " ")
756 if err = enc.Encode(cr); err != nil {
757 return fmt.Errorf("While logging the JSON container record: %v", err)
761 return fmt.Errorf("While closing container.json log: %v", err)
766 // AttachStreams connects the docker container stdin, stdout and stderr logs
767 // to the Arvados logger which logs to Keep and the API server logs table.
768 func (runner *ContainerRunner) AttachStreams() (err error) {
770 runner.CrunchLog.Print("Attaching container streams")
772 // If stdin mount is provided, attach it to the docker container
773 var stdinRdr arvados.File
775 if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
776 if stdinMnt.Kind == "collection" {
777 var stdinColl arvados.Collection
778 collId := stdinMnt.UUID
780 collId = stdinMnt.PortableDataHash
782 err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
784 return fmt.Errorf("While getting stding collection: %v", err)
787 stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
788 if os.IsNotExist(err) {
789 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
790 } else if err != nil {
791 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
793 } else if stdinMnt.Kind == "json" {
794 stdinJson, err = json.Marshal(stdinMnt.Content)
796 return fmt.Errorf("While encoding stdin json data: %v", err)
801 stdinUsed := stdinRdr != nil || len(stdinJson) != 0
802 response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
803 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
805 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
808 runner.loggingDone = make(chan bool)
810 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
811 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
815 runner.Stdout = stdoutFile
817 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
820 if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
821 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
825 runner.Stderr = stderrFile
827 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
832 _, err := io.Copy(response.Conn, stdinRdr)
834 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
838 response.CloseWrite()
840 } else if len(stdinJson) != 0 {
842 _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
844 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
847 response.CloseWrite()
851 go runner.ProcessDockerAttach(response.Reader)
856 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
857 stdoutPath := mntPath[len(runner.Container.OutputPath):]
858 index := strings.LastIndex(stdoutPath, "/")
860 subdirs := stdoutPath[:index]
862 st, err := os.Stat(runner.HostOutputDir)
864 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
866 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
867 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
869 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
873 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
875 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
878 return stdoutFile, nil
881 // CreateContainer creates the docker container.
882 func (runner *ContainerRunner) CreateContainer() error {
883 runner.CrunchLog.Print("Creating Docker container")
885 runner.ContainerConfig.Cmd = runner.Container.Command
886 if runner.Container.Cwd != "." {
887 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
890 for k, v := range runner.Container.Environment {
891 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
894 runner.ContainerConfig.Volumes = runner.Volumes
896 runner.HostConfig = dockercontainer.HostConfig{
898 LogConfig: dockercontainer.LogConfig{
901 Resources: dockercontainer.Resources{
902 CgroupParent: runner.setCgroupParent,
906 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
907 tok, err := runner.ContainerToken()
911 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
912 "ARVADOS_API_TOKEN="+tok,
913 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
914 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
916 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
918 if runner.enableNetwork == "always" {
919 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
921 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
925 _, stdinUsed := runner.Container.Mounts["stdin"]
926 runner.ContainerConfig.OpenStdin = stdinUsed
927 runner.ContainerConfig.StdinOnce = stdinUsed
928 runner.ContainerConfig.AttachStdin = stdinUsed
929 runner.ContainerConfig.AttachStdout = true
930 runner.ContainerConfig.AttachStderr = true
932 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
934 return fmt.Errorf("While creating container: %v", err)
937 runner.ContainerID = createdBody.ID
939 return runner.AttachStreams()
942 // StartContainer starts the docker container created by CreateContainer.
943 func (runner *ContainerRunner) StartContainer() error {
944 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
945 runner.cStateLock.Lock()
946 defer runner.cStateLock.Unlock()
947 if runner.cCancelled {
950 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
951 dockertypes.ContainerStartOptions{})
954 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
955 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])
957 return fmt.Errorf("could not start container: %v%s", err, advice)
959 runner.cStarted = true
963 // WaitFinish waits for the container to terminate, capture the exit code, and
964 // close the stdout/stderr logging.
965 func (runner *ContainerRunner) WaitFinish() (err error) {
966 runner.CrunchLog.Print("Waiting for container to finish")
968 waitOk, waitErr := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID, "not-running")
971 <-runner.ArvMountExit
973 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
978 var waitBody dockercontainer.ContainerWaitOKBody
980 case waitBody = <-waitOk:
981 case err = <-waitErr:
984 // Container isn't running any more
985 runner.cStarted = false
988 return fmt.Errorf("container wait: %v", err)
991 runner.CrunchLog.Printf("Container exited with code: %v", waitBody.StatusCode)
992 code := int(waitBody.StatusCode)
993 runner.ExitCode = &code
995 // wait for stdout/stderr to complete
1001 var ErrNotInOutputDir = fmt.Errorf("Must point to path within the output directory")
1003 func (runner *ContainerRunner) derefOutputSymlink(path string, startinfo os.FileInfo) (tgt string, readlinktgt string, info os.FileInfo, err error) {
1004 // Follow symlinks if necessary
1009 for followed := 0; info.Mode()&os.ModeSymlink != 0; followed++ {
1010 if followed >= limitFollowSymlinks {
1011 // Got stuck in a loop or just a pathological number of links, give up.
1012 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
1016 readlinktgt, err = os.Readlink(nextlink)
1022 if !strings.HasPrefix(tgt, "/") {
1023 // Relative symlink, resolve it to host path
1024 tgt = filepath.Join(filepath.Dir(path), tgt)
1026 if strings.HasPrefix(tgt, runner.Container.OutputPath+"/") && !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
1027 // Absolute symlink to container output path, adjust it to host output path.
1028 tgt = filepath.Join(runner.HostOutputDir, tgt[len(runner.Container.OutputPath):])
1030 if !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
1031 // After dereferencing, symlink target must either be
1032 // within output directory, or must point to a
1033 // collection mount.
1034 err = ErrNotInOutputDir
1038 info, err = os.Lstat(tgt)
1041 err = fmt.Errorf("Symlink in output %q points to invalid location %q: %v",
1042 path[len(runner.HostOutputDir):], readlinktgt, err)
1052 var limitFollowSymlinks = 10
1054 // UploadFile uploads files within the output directory, with special handling
1055 // for symlinks. If the symlink leads to a keep mount, copy the manifest text
1056 // from the keep mount into the output manifestText. Ensure that whether
1057 // symlinks are relative or absolute, every symlink target (even targets that
1058 // are symlinks themselves) must point to a path in either the output directory
1059 // or a collection mount.
1061 // Assumes initial value of "path" is absolute, and located within runner.HostOutputDir.
1062 func (runner *ContainerRunner) UploadOutputFile(
1067 walkUpload *WalkUpload,
1068 relocateFrom string,
1070 followed int) (manifestText string, err error) {
1072 if info.Mode().IsDir() {
1080 if followed >= limitFollowSymlinks {
1081 // Got stuck in a loop or just a pathological number of
1082 // directory links, give up.
1083 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
1087 // When following symlinks, the source path may need to be logically
1088 // relocated to some other path within the output collection. Remove
1089 // the relocateFrom prefix and replace it with relocateTo.
1090 relocated := relocateTo + path[len(relocateFrom):]
1092 tgt, readlinktgt, info, derefErr := runner.derefOutputSymlink(path, info)
1093 if derefErr != nil && derefErr != ErrNotInOutputDir {
1097 // go through mounts and try reverse map to collection reference
1098 for _, bind := range binds {
1099 mnt := runner.Container.Mounts[bind]
1100 if tgt == bind || strings.HasPrefix(tgt, bind+"/") {
1101 // get path relative to bind
1102 targetSuffix := tgt[len(bind):]
1104 // Copy mount and adjust the path to add path relative to the bind
1105 adjustedMount := mnt
1106 adjustedMount.Path = filepath.Join(adjustedMount.Path, targetSuffix)
1108 // Terminates in this keep mount, so add the
1109 // manifest text at appropriate location.
1110 outputSuffix := path[len(runner.HostOutputDir):]
1111 manifestText, err = runner.getCollectionManifestForPath(adjustedMount, outputSuffix)
1116 // If target is not a collection mount, it must be located within the
1117 // output directory, otherwise it is an error.
1118 if derefErr == ErrNotInOutputDir {
1119 err = fmt.Errorf("Symlink in output %q points to invalid location %q, must point to path within the output directory.",
1120 path[len(runner.HostOutputDir):], readlinktgt)
1124 if info.Mode().IsRegular() {
1125 return "", walkUpload.UploadFile(relocated, tgt)
1128 if info.Mode().IsDir() {
1129 // Symlink leads to directory. Walk() doesn't follow
1130 // directory symlinks, so we walk the target directory
1131 // instead. Within the walk, file paths are relocated
1132 // so they appear under the original symlink path.
1133 err = filepath.Walk(tgt, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
1135 m, walkerr = runner.UploadOutputFile(walkpath, walkinfo, walkerr,
1136 binds, walkUpload, tgt, relocated, followed+1)
1138 manifestText = manifestText + m
1148 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
1149 func (runner *ContainerRunner) CaptureOutput() error {
1150 if runner.finalState != "Complete" {
1154 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
1155 // Output may have been set directly by the container, so
1156 // refresh the container record to check.
1157 err := runner.ArvClient.Get("containers", runner.Container.UUID,
1158 nil, &runner.Container)
1162 if runner.Container.Output != "" {
1163 // Container output is already set.
1164 runner.OutputPDH = &runner.Container.Output
1169 if runner.HostOutputDir == "" {
1173 _, err := os.Stat(runner.HostOutputDir)
1175 return fmt.Errorf("While checking host output path: %v", err)
1178 // Pre-populate output from the configured mount points
1180 for bind, mnt := range runner.Container.Mounts {
1181 if mnt.Kind == "collection" {
1182 binds = append(binds, bind)
1187 var manifestText string
1189 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
1190 _, err = os.Stat(collectionMetafile)
1192 // Regular directory
1194 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
1195 walkUpload := cw.BeginUpload(runner.HostOutputDir, runner.CrunchLog.Logger)
1198 err = filepath.Walk(runner.HostOutputDir, func(path string, info os.FileInfo, err error) error {
1199 m, err = runner.UploadOutputFile(path, info, err, binds, walkUpload, "", "", 0)
1201 manifestText = manifestText + m
1206 cw.EndUpload(walkUpload)
1209 return fmt.Errorf("While uploading output files: %v", err)
1212 m, err = cw.ManifestText()
1213 manifestText = manifestText + m
1215 return fmt.Errorf("While uploading output files: %v", err)
1218 // FUSE mount directory
1219 file, openerr := os.Open(collectionMetafile)
1221 return fmt.Errorf("While opening FUSE metafile: %v", err)
1225 var rec arvados.Collection
1226 err = json.NewDecoder(file).Decode(&rec)
1228 return fmt.Errorf("While reading FUSE metafile: %v", err)
1230 manifestText = rec.ManifestText
1233 for _, bind := range binds {
1234 mnt := runner.Container.Mounts[bind]
1236 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
1238 if bindSuffix == bind || len(bindSuffix) <= 0 {
1239 // either does not start with OutputPath or is OutputPath itself
1243 if mnt.ExcludeFromOutput == true {
1247 // append to manifest_text
1248 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
1253 manifestText = manifestText + m
1257 var response arvados.Collection
1258 manifest := manifest.Manifest{Text: manifestText}
1259 manifestText = manifest.Extract(".", ".").Text
1260 err = runner.ArvClient.Create("collections",
1262 "ensure_unique_name": true,
1263 "collection": arvadosclient.Dict{
1265 "name": "output for " + runner.Container.UUID,
1266 "manifest_text": manifestText}},
1269 return fmt.Errorf("While creating output collection: %v", err)
1271 runner.OutputPDH = &response.PortableDataHash
1275 var outputCollections = make(map[string]arvados.Collection)
1277 // Fetch the collection for the mnt.PortableDataHash
1278 // Return the manifest_text fragment corresponding to the specified mnt.Path
1279 // after making any required updates.
1281 // If mnt.Path is not specified,
1282 // return the entire manifest_text after replacing any "." with bindSuffix
1283 // If mnt.Path corresponds to one stream,
1284 // return the manifest_text for that stream after replacing that stream name with bindSuffix
1285 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1286 // for that stream after replacing stream name with bindSuffix minus the last word
1287 // and the file name with last word of the bindSuffix
1288 // Allowed path examples:
1290 // "path":"/subdir1"
1291 // "path":"/subdir1/subdir2"
1292 // "path":"/subdir/filename" etc
1293 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1294 collection := outputCollections[mnt.PortableDataHash]
1295 if collection.PortableDataHash == "" {
1296 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1298 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1300 outputCollections[mnt.PortableDataHash] = collection
1303 if collection.ManifestText == "" {
1304 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1308 mft := manifest.Manifest{Text: collection.ManifestText}
1309 extracted := mft.Extract(mnt.Path, bindSuffix)
1310 if extracted.Err != nil {
1311 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1313 return extracted.Text, nil
1316 func (runner *ContainerRunner) CleanupDirs() {
1317 if runner.ArvMount != nil {
1319 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1320 umount.Stdout = runner.CrunchLog
1321 umount.Stderr = runner.CrunchLog
1322 runner.CrunchLog.Printf("Running %v", umount.Args)
1323 umnterr := umount.Start()
1326 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1328 // If arv-mount --unmount gets stuck for any reason, we
1329 // don't want to wait for it forever. Do Wait() in a goroutine
1330 // so it doesn't block crunch-run.
1331 umountExit := make(chan error)
1333 mnterr := umount.Wait()
1335 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1337 umountExit <- mnterr
1340 for again := true; again; {
1346 case <-runner.ArvMountExit:
1348 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1349 runner.CrunchLog.Printf("Timed out waiting for unmount")
1351 umount.Process.Kill()
1353 runner.ArvMount.Process.Kill()
1359 if runner.ArvMountPoint != "" {
1360 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1361 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1365 for _, tmpdir := range runner.CleanupTempDir {
1366 if rmerr := os.RemoveAll(tmpdir); rmerr != nil {
1367 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1372 // CommitLogs posts the collection containing the final container logs.
1373 func (runner *ContainerRunner) CommitLogs() error {
1374 runner.CrunchLog.Print(runner.finalState)
1376 if runner.arvMountLog != nil {
1377 runner.arvMountLog.Close()
1379 runner.CrunchLog.Close()
1381 // Closing CrunchLog above allows them to be committed to Keep at this
1382 // point, but re-open crunch log with ArvClient in case there are any
1383 // other further errors (such as failing to write the log to Keep!)
1384 // while shutting down
1385 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1386 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1387 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1389 if runner.LogsPDH != nil {
1390 // If we have already assigned something to LogsPDH,
1391 // we must be closing the re-opened log, which won't
1392 // end up getting attached to the container record and
1393 // therefore doesn't need to be saved as a collection
1394 // -- it exists only to send logs to other channels.
1398 mt, err := runner.LogCollection.ManifestText()
1400 return fmt.Errorf("While creating log manifest: %v", err)
1403 var response arvados.Collection
1404 err = runner.ArvClient.Create("collections",
1406 "ensure_unique_name": true,
1407 "collection": arvadosclient.Dict{
1409 "name": "logs for " + runner.Container.UUID,
1410 "manifest_text": mt}},
1413 return fmt.Errorf("While creating log collection: %v", err)
1415 runner.LogsPDH = &response.PortableDataHash
1419 // UpdateContainerRunning updates the container state to "Running"
1420 func (runner *ContainerRunner) UpdateContainerRunning() error {
1421 runner.cStateLock.Lock()
1422 defer runner.cStateLock.Unlock()
1423 if runner.cCancelled {
1426 return runner.ArvClient.Update("containers", runner.Container.UUID,
1427 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1430 // ContainerToken returns the api_token the container (and any
1431 // arv-mount processes) are allowed to use.
1432 func (runner *ContainerRunner) ContainerToken() (string, error) {
1433 if runner.token != "" {
1434 return runner.token, nil
1437 var auth arvados.APIClientAuthorization
1438 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1442 runner.token = auth.APIToken
1443 return runner.token, nil
1446 // UpdateContainerComplete updates the container record state on API
1447 // server to "Complete" or "Cancelled"
1448 func (runner *ContainerRunner) UpdateContainerFinal() error {
1449 update := arvadosclient.Dict{}
1450 update["state"] = runner.finalState
1451 if runner.LogsPDH != nil {
1452 update["log"] = *runner.LogsPDH
1454 if runner.finalState == "Complete" {
1455 if runner.ExitCode != nil {
1456 update["exit_code"] = *runner.ExitCode
1458 if runner.OutputPDH != nil {
1459 update["output"] = *runner.OutputPDH
1462 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1465 // IsCancelled returns the value of Cancelled, with goroutine safety.
1466 func (runner *ContainerRunner) IsCancelled() bool {
1467 runner.cStateLock.Lock()
1468 defer runner.cStateLock.Unlock()
1469 return runner.cCancelled
1472 // NewArvLogWriter creates an ArvLogWriter
1473 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1474 return &ArvLogWriter{
1475 ArvClient: runner.ArvClient,
1476 UUID: runner.Container.UUID,
1477 loggingStream: name,
1478 writeCloser: runner.LogCollection.Open(name + ".txt")}
1481 // Run the full container lifecycle.
1482 func (runner *ContainerRunner) Run() (err error) {
1483 runner.CrunchLog.Printf("crunch-run %s started", version)
1484 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1486 hostname, hosterr := os.Hostname()
1488 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1490 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1493 runner.finalState = "Queued"
1496 runner.stopSignals()
1497 runner.CleanupDirs()
1499 runner.CrunchLog.Printf("crunch-run finished")
1500 runner.CrunchLog.Close()
1504 // checkErr prints e (unless it's nil) and sets err to
1505 // e (unless err is already non-nil). Thus, if err
1506 // hasn't already been assigned when Run() returns,
1507 // this cleanup func will cause Run() to return the
1508 // first non-nil error that is passed to checkErr().
1509 checkErr := func(e error) {
1513 runner.CrunchLog.Print(e)
1517 if runner.finalState == "Complete" {
1518 // There was an error in the finalization.
1519 runner.finalState = "Cancelled"
1523 // Log the error encountered in Run(), if any
1526 if runner.finalState == "Queued" {
1527 runner.UpdateContainerFinal()
1531 if runner.IsCancelled() {
1532 runner.finalState = "Cancelled"
1533 // but don't return yet -- we still want to
1534 // capture partial output and write logs
1537 checkErr(runner.CaptureOutput())
1538 checkErr(runner.CommitLogs())
1539 checkErr(runner.UpdateContainerFinal())
1542 err = runner.fetchContainerRecord()
1547 // setup signal handling
1548 runner.setupSignals()
1550 // check for and/or load image
1551 err = runner.LoadImage()
1553 if !runner.checkBrokenNode(err) {
1554 // Failed to load image but not due to a "broken node"
1555 // condition, probably user error.
1556 runner.finalState = "Cancelled"
1558 err = fmt.Errorf("While loading container image: %v", err)
1562 // set up FUSE mount and binds
1563 err = runner.SetupMounts()
1565 runner.finalState = "Cancelled"
1566 err = fmt.Errorf("While setting up mounts: %v", err)
1570 err = runner.CreateContainer()
1575 // Gather and record node information
1576 err = runner.LogNodeInfo()
1580 // Save container.json record on log collection
1581 err = runner.LogContainerRecord()
1586 if runner.IsCancelled() {
1590 err = runner.UpdateContainerRunning()
1594 runner.finalState = "Cancelled"
1596 runner.StartCrunchstat()
1598 err = runner.StartContainer()
1600 runner.checkBrokenNode(err)
1604 err = runner.WaitFinish()
1606 runner.finalState = "Complete"
1611 // Fetch the current container record (uuid = runner.Container.UUID)
1612 // into runner.Container.
1613 func (runner *ContainerRunner) fetchContainerRecord() error {
1614 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1616 return fmt.Errorf("error fetching container record: %v", err)
1618 defer reader.Close()
1620 dec := json.NewDecoder(reader)
1622 err = dec.Decode(&runner.Container)
1624 return fmt.Errorf("error decoding container record: %v", err)
1629 // NewContainerRunner creates a new container runner.
1630 func NewContainerRunner(api IArvadosClient,
1632 docker ThinDockerClient,
1633 containerUUID string) *ContainerRunner {
1635 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1636 cr.NewLogWriter = cr.NewArvLogWriter
1637 cr.RunArvMount = cr.ArvMountCmd
1638 cr.MkTempDir = ioutil.TempDir
1639 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1640 cr.Container.UUID = containerUUID
1641 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1642 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1644 loadLogThrottleParams(api)
1650 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1651 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1652 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1653 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1654 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1655 enableNetwork := flag.String("container-enable-networking", "default",
1656 `Specify if networking should be enabled for container. One of 'default', 'always':
1657 default: only enable networking if container requests it.
1658 always: containers always have networking enabled
1660 networkMode := flag.String("container-network-mode", "default",
1661 `Set networking mode for container. Corresponds to Docker network mode (--net).
1663 memprofile := flag.String("memprofile", "", "write memory profile to `file` after running container")
1664 getVersion := flag.Bool("version", false, "Print version information and exit.")
1667 // Print version information if requested
1669 fmt.Printf("crunch-run %s\n", version)
1673 log.Printf("crunch-run %s started", version)
1675 containerId := flag.Arg(0)
1677 if *caCertsPath != "" {
1678 arvadosclient.CertFiles = []string{*caCertsPath}
1681 api, err := arvadosclient.MakeArvadosClient()
1683 log.Fatalf("%s: %v", containerId, err)
1687 kc, kcerr := keepclient.MakeKeepClient(api)
1689 log.Fatalf("%s: %v", containerId, kcerr)
1691 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1694 // API version 1.21 corresponds to Docker 1.9, which is currently the
1695 // minimum version we want to support.
1696 docker, dockererr := dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1697 dockerClientProxy := ThinDockerClientProxy{Docker: docker}
1699 cr := NewContainerRunner(api, kc, dockerClientProxy, containerId)
1701 if dockererr != nil {
1702 cr.CrunchLog.Printf("%s: %v", containerId, dockererr)
1703 cr.checkBrokenNode(dockererr)
1704 cr.CrunchLog.Close()
1708 cr.statInterval = *statInterval
1709 cr.cgroupRoot = *cgroupRoot
1710 cr.expectCgroupParent = *cgroupParent
1711 cr.enableNetwork = *enableNetwork
1712 cr.networkMode = *networkMode
1713 if *cgroupParentSubsystem != "" {
1714 p := findCgroup(*cgroupParentSubsystem)
1715 cr.setCgroupParent = p
1716 cr.expectCgroupParent = p
1721 if *memprofile != "" {
1722 f, err := os.Create(*memprofile)
1724 log.Printf("could not create memory profile: ", err)
1726 runtime.GC() // get up-to-date statistics
1727 if err := pprof.WriteHeapProfile(f); err != nil {
1728 log.Printf("could not write memory profile: ", err)
1730 closeerr := f.Close()
1731 if closeerr != nil {
1732 log.Printf("closing memprofile file: ", err)
1737 log.Fatalf("%s: %v", containerId, runerr)