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"
36 dockertypes "github.com/docker/docker/api/types"
37 dockercontainer "github.com/docker/docker/api/types/container"
38 dockernetwork "github.com/docker/docker/api/types/network"
39 dockerclient "github.com/docker/docker/client"
42 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
43 type IArvadosClient interface {
44 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
45 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
46 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
47 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
48 CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
49 Discovery(key string) (interface{}, error)
52 // ErrCancelled is the error returned when the container is cancelled.
53 var ErrCancelled = errors.New("Cancelled")
55 // IKeepClient is the minimal Keep API methods used by crunch-run.
56 type IKeepClient interface {
57 PutHB(hash string, buf []byte) (string, int, error)
58 ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error)
62 // NewLogWriter is a factory function to create a new log writer.
63 type NewLogWriter func(name string) io.WriteCloser
65 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
67 type MkTempDir func(string, string) (string, error)
69 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
70 type ThinDockerClient interface {
71 ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error)
72 ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
73 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error)
74 ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error
75 ContainerStop(ctx context.Context, container string, timeout *time.Duration) error
76 ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error)
77 ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error)
78 ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error)
79 ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error)
82 // ThinDockerClientProxy is a proxy implementation of ThinDockerClient
83 // that executes the docker requests on dockerclient.Client
84 type ThinDockerClientProxy struct {
85 Docker *dockerclient.Client
88 // ContainerAttach invokes dockerclient.Client.ContainerAttach
89 func (proxy ThinDockerClientProxy) ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error) {
90 return proxy.Docker.ContainerAttach(ctx, container, options)
93 // ContainerCreate invokes dockerclient.Client.ContainerCreate
94 func (proxy ThinDockerClientProxy) ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
95 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error) {
96 return proxy.Docker.ContainerCreate(ctx, config, hostConfig, networkingConfig, containerName)
99 // ContainerStart invokes dockerclient.Client.ContainerStart
100 func (proxy ThinDockerClientProxy) ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error {
101 return proxy.Docker.ContainerStart(ctx, container, options)
104 // ContainerStop invokes dockerclient.Client.ContainerStop
105 func (proxy ThinDockerClientProxy) ContainerStop(ctx context.Context, container string, timeout *time.Duration) error {
106 return proxy.Docker.ContainerStop(ctx, container, timeout)
109 // ContainerWait invokes dockerclient.Client.ContainerWait
110 func (proxy ThinDockerClientProxy) ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error) {
111 return proxy.Docker.ContainerWait(ctx, container, condition)
114 // ImageInspectWithRaw invokes dockerclient.Client.ImageInspectWithRaw
115 func (proxy ThinDockerClientProxy) ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error) {
116 return proxy.Docker.ImageInspectWithRaw(ctx, image)
119 // ImageLoad invokes dockerclient.Client.ImageLoad
120 func (proxy ThinDockerClientProxy) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error) {
121 return proxy.Docker.ImageLoad(ctx, input, quiet)
124 // ImageRemove invokes dockerclient.Client.ImageRemove
125 func (proxy ThinDockerClientProxy) ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {
126 return proxy.Docker.ImageRemove(ctx, image, options)
129 // ContainerRunner is the main stateful struct used for a single execution of a
131 type ContainerRunner struct {
132 Docker ThinDockerClient
133 ArvClient IArvadosClient
136 ContainerConfig dockercontainer.Config
137 dockercontainer.HostConfig
142 loggingDone chan bool
143 CrunchLog *ThrottledLogger
144 Stdout io.WriteCloser
145 Stderr io.WriteCloser
146 LogCollection *CollectionWriter
153 CleanupTempDir []string
155 Volumes map[string]struct{}
157 SigChan chan os.Signal
158 ArvMountExit chan error
161 statLogger io.WriteCloser
162 statReporter *crunchstat.Reporter
163 statInterval time.Duration
165 // What we expect the container's cgroup parent to be.
166 expectCgroupParent string
167 // What we tell docker to use as the container's cgroup
168 // parent. Note: Ideally we would use the same field for both
169 // expectCgroupParent and setCgroupParent, and just make it
170 // default to "docker". However, when using docker < 1.10 with
171 // systemd, specifying a non-empty cgroup parent (even the
172 // default value "docker") hits a docker bug
173 // (https://github.com/docker/docker/issues/17126). Using two
174 // separate fields makes it possible to use the "expect cgroup
175 // parent to be X" feature even on sites where the "specify
176 // cgroup parent" feature breaks.
177 setCgroupParent string
179 cStateLock sync.Mutex
180 cStarted bool // StartContainer() succeeded
181 cCancelled bool // StopContainer() invoked
183 enableNetwork string // one of "default" or "always"
184 networkMode string // passed through to HostConfig.NetworkMode
185 arvMountLog *ThrottledLogger
188 // setupSignals sets up signal handling to gracefully terminate the underlying
189 // Docker container and update state when receiving a TERM, INT or QUIT signal.
190 func (runner *ContainerRunner) setupSignals() {
191 runner.SigChan = make(chan os.Signal, 1)
192 signal.Notify(runner.SigChan, syscall.SIGTERM)
193 signal.Notify(runner.SigChan, syscall.SIGINT)
194 signal.Notify(runner.SigChan, syscall.SIGQUIT)
196 go func(sig chan os.Signal) {
199 runner.CrunchLog.Printf("Caught signal %v", s)
205 // stop the underlying Docker container.
206 func (runner *ContainerRunner) stop() {
207 runner.cStateLock.Lock()
208 defer runner.cStateLock.Unlock()
209 if runner.cCancelled {
212 runner.cCancelled = true
214 timeout := time.Duration(10)
215 err := runner.Docker.ContainerStop(context.TODO(), runner.ContainerID, &(timeout))
217 runner.CrunchLog.Printf("StopContainer failed: %s", err)
219 // Suppress multiple calls to stop()
220 runner.cStarted = false
224 func (runner *ContainerRunner) stopSignals() {
225 if runner.SigChan != nil {
226 signal.Stop(runner.SigChan)
227 close(runner.SigChan)
231 var errorBlacklist = []string{"Cannot connect to the Docker daemon"}
232 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)")
234 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
235 for _, d := range errorBlacklist {
236 if strings.Index(goterr.Error(), d) != -1 {
237 runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
238 if *brokenNodeHook == "" {
239 runner.CrunchLog.Printf("No broken node hook provided, cannot mark node as broken.")
241 runner.CrunchLog.Printf("Running broken node hook %q", *brokenNodeHook)
243 c := exec.Command(*brokenNodeHook)
244 c.Stdout = runner.CrunchLog
245 c.Stderr = runner.CrunchLog
248 runner.CrunchLog.Printf("Error running broken node hook: %v", err)
257 // LoadImage determines the docker image id from the container record and
258 // checks if it is available in the local Docker image store. If not, it loads
259 // the image from Keep.
260 func (runner *ContainerRunner) LoadImage() (err error) {
262 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
264 var collection arvados.Collection
265 err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
267 return fmt.Errorf("While getting container image collection: %v", err)
269 manifest := manifest.Manifest{Text: collection.ManifestText}
270 var img, imageID string
271 for ms := range manifest.StreamIter() {
272 img = ms.FileStreamSegments[0].Name
273 if !strings.HasSuffix(img, ".tar") {
274 return fmt.Errorf("First file in the container image collection does not end in .tar")
276 imageID = img[:len(img)-4]
279 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
281 _, _, err = runner.Docker.ImageInspectWithRaw(context.TODO(), imageID)
283 runner.CrunchLog.Print("Loading Docker image from keep")
285 var readCloser io.ReadCloser
286 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
288 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
291 response, err := runner.Docker.ImageLoad(context.TODO(), readCloser, true)
293 return fmt.Errorf("While loading container image into Docker: %v", err)
296 defer response.Body.Close()
297 rbody, err := ioutil.ReadAll(response.Body)
299 return fmt.Errorf("Reading response to image load: %v", err)
301 runner.CrunchLog.Printf("Docker response: %s", rbody)
303 runner.CrunchLog.Print("Docker image is available")
306 runner.ContainerConfig.Image = imageID
308 runner.Kc.ClearBlockCache()
313 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
314 c = exec.Command("arv-mount", arvMountCmd...)
316 // Copy our environment, but override ARVADOS_API_TOKEN with
317 // the container auth token.
319 for _, s := range os.Environ() {
320 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
321 c.Env = append(c.Env, s)
324 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
326 runner.arvMountLog = NewThrottledLogger(runner.NewLogWriter("arv-mount"))
327 c.Stdout = runner.arvMountLog
328 c.Stderr = runner.arvMountLog
330 runner.CrunchLog.Printf("Running %v", c.Args)
337 statReadme := make(chan bool)
338 runner.ArvMountExit = make(chan error)
343 time.Sleep(100 * time.Millisecond)
344 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
356 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
358 runner.ArvMountExit <- mnterr
359 close(runner.ArvMountExit)
365 case err := <-runner.ArvMountExit:
366 runner.ArvMount = nil
374 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
375 if runner.ArvMountPoint == "" {
376 runner.ArvMountPoint, err = runner.MkTempDir("", prefix)
381 func (runner *ContainerRunner) SetupMounts() (err error) {
382 err = runner.SetupArvMountPoint("keep")
384 return fmt.Errorf("While creating keep mount temp dir: %v", err)
389 arvMountCmd := []string{
393 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
395 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
396 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
399 collectionPaths := []string{}
401 runner.Volumes = make(map[string]struct{})
402 needCertMount := true
405 for bind := range runner.Container.Mounts {
406 binds = append(binds, bind)
410 for _, bind := range binds {
411 mnt := runner.Container.Mounts[bind]
412 if bind == "stdout" || bind == "stderr" {
413 // Is it a "file" mount kind?
414 if mnt.Kind != "file" {
415 return fmt.Errorf("Unsupported mount kind '%s' for %s. Only 'file' is supported.", mnt.Kind, bind)
418 // Does path start with OutputPath?
419 prefix := runner.Container.OutputPath
420 if !strings.HasSuffix(prefix, "/") {
423 if !strings.HasPrefix(mnt.Path, prefix) {
424 return fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
429 // Is it a "collection" mount kind?
430 if mnt.Kind != "collection" && mnt.Kind != "json" {
431 return fmt.Errorf("Unsupported mount kind '%s' for stdin. Only 'collection' or 'json' are supported.", mnt.Kind)
435 if bind == "/etc/arvados/ca-certificates.crt" {
436 needCertMount = false
439 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
440 if mnt.Kind != "collection" {
441 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
446 case mnt.Kind == "collection" && bind != "stdin":
448 if mnt.UUID != "" && mnt.PortableDataHash != "" {
449 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
453 return fmt.Errorf("Writing to existing collections currently not permitted.")
456 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
457 } else if mnt.PortableDataHash != "" {
459 return fmt.Errorf("Can never write to a collection specified by portable data hash")
461 idx := strings.Index(mnt.PortableDataHash, "/")
463 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
464 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
465 runner.Container.Mounts[bind] = mnt
467 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
468 if mnt.Path != "" && mnt.Path != "." {
469 if strings.HasPrefix(mnt.Path, "./") {
470 mnt.Path = mnt.Path[2:]
471 } else if strings.HasPrefix(mnt.Path, "/") {
472 mnt.Path = mnt.Path[1:]
474 src += "/" + mnt.Path
477 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
478 arvMountCmd = append(arvMountCmd, "--mount-tmp")
479 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
483 if bind == runner.Container.OutputPath {
484 runner.HostOutputDir = src
485 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
486 return fmt.Errorf("Writable mount points are not permitted underneath the output_path: %v", bind)
488 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
490 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
492 collectionPaths = append(collectionPaths, src)
494 case mnt.Kind == "tmp":
496 tmpdir, err = runner.MkTempDir("", "")
498 return fmt.Errorf("While creating mount temp dir: %v", err)
500 st, staterr := os.Stat(tmpdir)
502 return fmt.Errorf("While Stat on temp dir: %v", staterr)
504 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
506 return fmt.Errorf("While Chmod temp dir: %v", err)
508 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
509 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", tmpdir, bind))
510 if bind == runner.Container.OutputPath {
511 runner.HostOutputDir = tmpdir
514 case mnt.Kind == "json":
515 jsondata, err := json.Marshal(mnt.Content)
517 return fmt.Errorf("encoding json data: %v", err)
519 // Create a tempdir with a single file
520 // (instead of just a tempfile): this way we
521 // can ensure the file is world-readable
522 // inside the container, without having to
523 // make it world-readable on the docker host.
524 tmpdir, err := runner.MkTempDir("", "")
526 return fmt.Errorf("creating temp dir: %v", err)
528 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
529 tmpfn := filepath.Join(tmpdir, "mountdata.json")
530 err = ioutil.WriteFile(tmpfn, jsondata, 0644)
532 return fmt.Errorf("writing temp file: %v", err)
534 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
538 if runner.HostOutputDir == "" {
539 return fmt.Errorf("Output path does not correspond to a writable mount point")
542 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
543 for _, certfile := range arvadosclient.CertFiles {
544 _, err := os.Stat(certfile)
546 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
553 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
555 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
557 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
559 token, err := runner.ContainerToken()
561 return fmt.Errorf("could not get container token: %s", err)
564 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
566 return fmt.Errorf("While trying to start arv-mount: %v", err)
569 for _, p := range collectionPaths {
572 return fmt.Errorf("While checking that input files exist: %v", err)
579 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
580 // Handle docker log protocol
581 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
583 header := make([]byte, 8)
585 _, readerr := io.ReadAtLeast(containerReader, header, 8)
588 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
591 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
594 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
599 if readerr != io.EOF {
600 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
603 closeerr := runner.Stdout.Close()
605 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
608 closeerr = runner.Stderr.Close()
610 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
613 if runner.statReporter != nil {
614 runner.statReporter.Stop()
615 closeerr = runner.statLogger.Close()
617 runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
621 runner.loggingDone <- true
622 close(runner.loggingDone)
628 func (runner *ContainerRunner) StartCrunchstat() {
629 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
630 runner.statReporter = &crunchstat.Reporter{
631 CID: runner.ContainerID,
632 Logger: log.New(runner.statLogger, "", 0),
633 CgroupParent: runner.expectCgroupParent,
634 CgroupRoot: runner.cgroupRoot,
635 PollPeriod: runner.statInterval,
637 runner.statReporter.Start()
640 type infoCommand struct {
645 // Gather node information and store it on the log for debugging
647 func (runner *ContainerRunner) LogNodeInfo() (err error) {
648 w := runner.NewLogWriter("node-info")
649 logger := log.New(w, "node-info", 0)
651 commands := []infoCommand{
653 label: "Host Information",
654 cmd: []string{"uname", "-a"},
657 label: "CPU Information",
658 cmd: []string{"cat", "/proc/cpuinfo"},
661 label: "Memory Information",
662 cmd: []string{"cat", "/proc/meminfo"},
666 cmd: []string{"df", "-m", "/", os.TempDir()},
669 label: "Disk INodes",
670 cmd: []string{"df", "-i", "/", os.TempDir()},
674 // Run commands with informational output to be logged.
676 for _, command := range commands {
677 out, err = exec.Command(command.cmd[0], command.cmd[1:]...).CombinedOutput()
679 return fmt.Errorf("While running command %q: %v",
682 logger.Println(command.label)
683 for _, line := range strings.Split(string(out), "\n") {
684 logger.Println(" ", line)
690 return fmt.Errorf("While closing node-info logs: %v", err)
695 // Get and save the raw JSON container record from the API server
696 func (runner *ContainerRunner) LogContainerRecord() (err error) {
698 ArvClient: runner.ArvClient,
699 UUID: runner.Container.UUID,
700 loggingStream: "container",
701 writeCloser: runner.LogCollection.Open("container.json"),
704 // Get Container record JSON from the API Server
705 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
707 return fmt.Errorf("While retrieving container record from the API server: %v", err)
711 dec := json.NewDecoder(reader)
713 var cr map[string]interface{}
714 if err = dec.Decode(&cr); err != nil {
715 return fmt.Errorf("While decoding the container record JSON response: %v", err)
717 // Re-encode it using indentation to improve readability
718 enc := json.NewEncoder(w)
719 enc.SetIndent("", " ")
720 if err = enc.Encode(cr); err != nil {
721 return fmt.Errorf("While logging the JSON container record: %v", err)
725 return fmt.Errorf("While closing container.json log: %v", 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 strings.Contains(err.Error(), "no such file or directory") {
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, "not-running")
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) {
1036 if info.Mode().IsDir() {
1044 if followed >= limitFollowSymlinks {
1045 // Got stuck in a loop or just a pathological number of
1046 // directory links, give up.
1047 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
1051 // When following symlinks, the source path may need to be logically
1052 // relocated to some other path within the output collection. Remove
1053 // the relocateFrom prefix and replace it with relocateTo.
1054 relocated := relocateTo + path[len(relocateFrom):]
1056 tgt, readlinktgt, info, derefErr := runner.derefOutputSymlink(path, info)
1057 if derefErr != nil && derefErr != ErrNotInOutputDir {
1061 // go through mounts and try reverse map to collection reference
1062 for _, bind := range binds {
1063 mnt := runner.Container.Mounts[bind]
1064 if tgt == bind || strings.HasPrefix(tgt, bind+"/") {
1065 // get path relative to bind
1066 targetSuffix := tgt[len(bind):]
1068 // Copy mount and adjust the path to add path relative to the bind
1069 adjustedMount := mnt
1070 adjustedMount.Path = filepath.Join(adjustedMount.Path, targetSuffix)
1072 // Terminates in this keep mount, so add the
1073 // manifest text at appropriate location.
1074 outputSuffix := path[len(runner.HostOutputDir):]
1075 manifestText, err = runner.getCollectionManifestForPath(adjustedMount, outputSuffix)
1080 // If target is not a collection mount, it must be located within the
1081 // output directory, otherwise it is an error.
1082 if derefErr == ErrNotInOutputDir {
1083 err = fmt.Errorf("Symlink in output %q points to invalid location %q, must point to path within the output directory.",
1084 path[len(runner.HostOutputDir):], readlinktgt)
1088 if info.Mode().IsRegular() {
1089 return "", walkUpload.UploadFile(relocated, tgt)
1092 if info.Mode().IsDir() {
1093 // Symlink leads to directory. Walk() doesn't follow
1094 // directory symlinks, so we walk the target directory
1095 // instead. Within the walk, file paths are relocated
1096 // so they appear under the original symlink path.
1097 err = filepath.Walk(tgt, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
1099 m, walkerr = runner.UploadOutputFile(walkpath, walkinfo, walkerr,
1100 binds, walkUpload, tgt, relocated, followed+1)
1102 manifestText = manifestText + m
1112 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
1113 func (runner *ContainerRunner) CaptureOutput() error {
1114 if runner.finalState != "Complete" {
1118 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
1119 // Output may have been set directly by the container, so
1120 // refresh the container record to check.
1121 err := runner.ArvClient.Get("containers", runner.Container.UUID,
1122 nil, &runner.Container)
1126 if runner.Container.Output != "" {
1127 // Container output is already set.
1128 runner.OutputPDH = &runner.Container.Output
1133 if runner.HostOutputDir == "" {
1137 _, err := os.Stat(runner.HostOutputDir)
1139 return fmt.Errorf("While checking host output path: %v", err)
1142 // Pre-populate output from the configured mount points
1144 for bind, mnt := range runner.Container.Mounts {
1145 if mnt.Kind == "collection" {
1146 binds = append(binds, bind)
1151 var manifestText string
1153 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
1154 _, err = os.Stat(collectionMetafile)
1156 // Regular directory
1158 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
1159 walkUpload := cw.BeginUpload(runner.HostOutputDir, runner.CrunchLog.Logger)
1162 err = filepath.Walk(runner.HostOutputDir, func(path string, info os.FileInfo, err error) error {
1163 m, err = runner.UploadOutputFile(path, info, err, binds, walkUpload, "", "", 0)
1165 manifestText = manifestText + m
1170 cw.EndUpload(walkUpload)
1173 return fmt.Errorf("While uploading output files: %v", err)
1176 m, err = cw.ManifestText()
1177 manifestText = manifestText + m
1179 return fmt.Errorf("While uploading output files: %v", err)
1182 // FUSE mount directory
1183 file, openerr := os.Open(collectionMetafile)
1185 return fmt.Errorf("While opening FUSE metafile: %v", err)
1189 var rec arvados.Collection
1190 err = json.NewDecoder(file).Decode(&rec)
1192 return fmt.Errorf("While reading FUSE metafile: %v", err)
1194 manifestText = rec.ManifestText
1197 for _, bind := range binds {
1198 mnt := runner.Container.Mounts[bind]
1200 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
1202 if bindSuffix == bind || len(bindSuffix) <= 0 {
1203 // either does not start with OutputPath or is OutputPath itself
1207 if mnt.ExcludeFromOutput == true {
1211 // append to manifest_text
1212 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
1217 manifestText = manifestText + m
1221 var response arvados.Collection
1222 manifest := manifest.Manifest{Text: manifestText}
1223 manifestText = manifest.Extract(".", ".").Text
1224 err = runner.ArvClient.Create("collections",
1226 "ensure_unique_name": true,
1227 "collection": arvadosclient.Dict{
1229 "name": "output for " + runner.Container.UUID,
1230 "manifest_text": manifestText}},
1233 return fmt.Errorf("While creating output collection: %v", err)
1235 runner.OutputPDH = &response.PortableDataHash
1239 var outputCollections = make(map[string]arvados.Collection)
1241 // Fetch the collection for the mnt.PortableDataHash
1242 // Return the manifest_text fragment corresponding to the specified mnt.Path
1243 // after making any required updates.
1245 // If mnt.Path is not specified,
1246 // return the entire manifest_text after replacing any "." with bindSuffix
1247 // If mnt.Path corresponds to one stream,
1248 // return the manifest_text for that stream after replacing that stream name with bindSuffix
1249 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1250 // for that stream after replacing stream name with bindSuffix minus the last word
1251 // and the file name with last word of the bindSuffix
1252 // Allowed path examples:
1254 // "path":"/subdir1"
1255 // "path":"/subdir1/subdir2"
1256 // "path":"/subdir/filename" etc
1257 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1258 collection := outputCollections[mnt.PortableDataHash]
1259 if collection.PortableDataHash == "" {
1260 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1262 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1264 outputCollections[mnt.PortableDataHash] = collection
1267 if collection.ManifestText == "" {
1268 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1272 mft := manifest.Manifest{Text: collection.ManifestText}
1273 extracted := mft.Extract(mnt.Path, bindSuffix)
1274 if extracted.Err != nil {
1275 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1277 return extracted.Text, nil
1280 func (runner *ContainerRunner) CleanupDirs() {
1281 if runner.ArvMount != nil {
1283 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1284 umount.Stdout = runner.CrunchLog
1285 umount.Stderr = runner.CrunchLog
1286 runner.CrunchLog.Printf("Running %v", umount.Args)
1287 umnterr := umount.Start()
1290 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1292 // If arv-mount --unmount gets stuck for any reason, we
1293 // don't want to wait for it forever. Do Wait() in a goroutine
1294 // so it doesn't block crunch-run.
1295 umountExit := make(chan error)
1297 mnterr := umount.Wait()
1299 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1301 umountExit <- mnterr
1304 for again := true; again; {
1310 case <-runner.ArvMountExit:
1312 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1313 runner.CrunchLog.Printf("Timed out waiting for unmount")
1315 umount.Process.Kill()
1317 runner.ArvMount.Process.Kill()
1323 if runner.ArvMountPoint != "" {
1324 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1325 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1329 for _, tmpdir := range runner.CleanupTempDir {
1330 if rmerr := os.RemoveAll(tmpdir); rmerr != nil {
1331 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1336 // CommitLogs posts the collection containing the final container logs.
1337 func (runner *ContainerRunner) CommitLogs() error {
1338 runner.CrunchLog.Print(runner.finalState)
1340 if runner.arvMountLog != nil {
1341 runner.arvMountLog.Close()
1343 runner.CrunchLog.Close()
1345 // Closing CrunchLog above allows them to be committed to Keep at this
1346 // point, but re-open crunch log with ArvClient in case there are any
1347 // other further errors (such as failing to write the log to Keep!)
1348 // while shutting down
1349 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1350 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1351 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1353 if runner.LogsPDH != nil {
1354 // If we have already assigned something to LogsPDH,
1355 // we must be closing the re-opened log, which won't
1356 // end up getting attached to the container record and
1357 // therefore doesn't need to be saved as a collection
1358 // -- it exists only to send logs to other channels.
1362 mt, err := runner.LogCollection.ManifestText()
1364 return fmt.Errorf("While creating log manifest: %v", err)
1367 var response arvados.Collection
1368 err = runner.ArvClient.Create("collections",
1370 "ensure_unique_name": true,
1371 "collection": arvadosclient.Dict{
1373 "name": "logs for " + runner.Container.UUID,
1374 "manifest_text": mt}},
1377 return fmt.Errorf("While creating log collection: %v", err)
1379 runner.LogsPDH = &response.PortableDataHash
1383 // UpdateContainerRunning updates the container state to "Running"
1384 func (runner *ContainerRunner) UpdateContainerRunning() error {
1385 runner.cStateLock.Lock()
1386 defer runner.cStateLock.Unlock()
1387 if runner.cCancelled {
1390 return runner.ArvClient.Update("containers", runner.Container.UUID,
1391 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1394 // ContainerToken returns the api_token the container (and any
1395 // arv-mount processes) are allowed to use.
1396 func (runner *ContainerRunner) ContainerToken() (string, error) {
1397 if runner.token != "" {
1398 return runner.token, nil
1401 var auth arvados.APIClientAuthorization
1402 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1406 runner.token = auth.APIToken
1407 return runner.token, nil
1410 // UpdateContainerComplete updates the container record state on API
1411 // server to "Complete" or "Cancelled"
1412 func (runner *ContainerRunner) UpdateContainerFinal() error {
1413 update := arvadosclient.Dict{}
1414 update["state"] = runner.finalState
1415 if runner.LogsPDH != nil {
1416 update["log"] = *runner.LogsPDH
1418 if runner.finalState == "Complete" {
1419 if runner.ExitCode != nil {
1420 update["exit_code"] = *runner.ExitCode
1422 if runner.OutputPDH != nil {
1423 update["output"] = *runner.OutputPDH
1426 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1429 // IsCancelled returns the value of Cancelled, with goroutine safety.
1430 func (runner *ContainerRunner) IsCancelled() bool {
1431 runner.cStateLock.Lock()
1432 defer runner.cStateLock.Unlock()
1433 return runner.cCancelled
1436 // NewArvLogWriter creates an ArvLogWriter
1437 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1438 return &ArvLogWriter{
1439 ArvClient: runner.ArvClient,
1440 UUID: runner.Container.UUID,
1441 loggingStream: name,
1442 writeCloser: runner.LogCollection.Open(name + ".txt")}
1445 // Run the full container lifecycle.
1446 func (runner *ContainerRunner) Run() (err error) {
1447 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1449 hostname, hosterr := os.Hostname()
1451 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1453 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1456 runner.finalState = "Queued"
1459 runner.stopSignals()
1460 runner.CleanupDirs()
1462 runner.CrunchLog.Printf("crunch-run finished")
1463 runner.CrunchLog.Close()
1467 // checkErr prints e (unless it's nil) and sets err to
1468 // e (unless err is already non-nil). Thus, if err
1469 // hasn't already been assigned when Run() returns,
1470 // this cleanup func will cause Run() to return the
1471 // first non-nil error that is passed to checkErr().
1472 checkErr := func(e error) {
1476 runner.CrunchLog.Print(e)
1480 if runner.finalState == "Complete" {
1481 // There was an error in the finalization.
1482 runner.finalState = "Cancelled"
1486 // Log the error encountered in Run(), if any
1489 if runner.finalState == "Queued" {
1490 runner.UpdateContainerFinal()
1494 if runner.IsCancelled() {
1495 runner.finalState = "Cancelled"
1496 // but don't return yet -- we still want to
1497 // capture partial output and write logs
1500 checkErr(runner.CaptureOutput())
1501 checkErr(runner.CommitLogs())
1502 checkErr(runner.UpdateContainerFinal())
1505 err = runner.fetchContainerRecord()
1510 // setup signal handling
1511 runner.setupSignals()
1513 // check for and/or load image
1514 err = runner.LoadImage()
1516 if !runner.checkBrokenNode(err) {
1517 // Failed to load image but not due to a "broken node"
1518 // condition, probably user error.
1519 runner.finalState = "Cancelled"
1521 err = fmt.Errorf("While loading container image: %v", err)
1525 // set up FUSE mount and binds
1526 err = runner.SetupMounts()
1528 runner.finalState = "Cancelled"
1529 err = fmt.Errorf("While setting up mounts: %v", err)
1533 err = runner.CreateContainer()
1538 // Gather and record node information
1539 err = runner.LogNodeInfo()
1543 // Save container.json record on log collection
1544 err = runner.LogContainerRecord()
1549 if runner.IsCancelled() {
1553 err = runner.UpdateContainerRunning()
1557 runner.finalState = "Cancelled"
1559 runner.StartCrunchstat()
1561 err = runner.StartContainer()
1563 runner.checkBrokenNode(err)
1567 err = runner.WaitFinish()
1569 runner.finalState = "Complete"
1574 // Fetch the current container record (uuid = runner.Container.UUID)
1575 // into runner.Container.
1576 func (runner *ContainerRunner) fetchContainerRecord() error {
1577 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1579 return fmt.Errorf("error fetching container record: %v", err)
1581 defer reader.Close()
1583 dec := json.NewDecoder(reader)
1585 err = dec.Decode(&runner.Container)
1587 return fmt.Errorf("error decoding container record: %v", err)
1592 // NewContainerRunner creates a new container runner.
1593 func NewContainerRunner(api IArvadosClient,
1595 docker ThinDockerClient,
1596 containerUUID string) *ContainerRunner {
1598 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1599 cr.NewLogWriter = cr.NewArvLogWriter
1600 cr.RunArvMount = cr.ArvMountCmd
1601 cr.MkTempDir = ioutil.TempDir
1602 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1603 cr.Container.UUID = containerUUID
1604 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1605 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1607 loadLogThrottleParams(api)
1613 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1614 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1615 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1616 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1617 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1618 enableNetwork := flag.String("container-enable-networking", "default",
1619 `Specify if networking should be enabled for container. One of 'default', 'always':
1620 default: only enable networking if container requests it.
1621 always: containers always have networking enabled
1623 networkMode := flag.String("container-network-mode", "default",
1624 `Set networking mode for container. Corresponds to Docker network mode (--net).
1626 memprofile := flag.String("memprofile", "", "write memory profile to `file` after running container")
1629 containerId := flag.Arg(0)
1631 if *caCertsPath != "" {
1632 arvadosclient.CertFiles = []string{*caCertsPath}
1635 api, err := arvadosclient.MakeArvadosClient()
1637 log.Fatalf("%s: %v", containerId, err)
1641 kc, kcerr := keepclient.MakeKeepClient(api)
1643 log.Fatalf("%s: %v", containerId, kcerr)
1645 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1648 // API version 1.21 corresponds to Docker 1.9, which is currently the
1649 // minimum version we want to support.
1650 docker, dockererr := dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1651 dockerClientProxy := ThinDockerClientProxy{Docker: docker}
1653 cr := NewContainerRunner(api, kc, dockerClientProxy, containerId)
1655 if dockererr != nil {
1656 cr.CrunchLog.Printf("%s: %v", containerId, dockererr)
1657 cr.checkBrokenNode(dockererr)
1658 cr.CrunchLog.Close()
1662 cr.statInterval = *statInterval
1663 cr.cgroupRoot = *cgroupRoot
1664 cr.expectCgroupParent = *cgroupParent
1665 cr.enableNetwork = *enableNetwork
1666 cr.networkMode = *networkMode
1667 if *cgroupParentSubsystem != "" {
1668 p := findCgroup(*cgroupParentSubsystem)
1669 cr.setCgroupParent = p
1670 cr.expectCgroupParent = p
1675 if *memprofile != "" {
1676 f, err := os.Create(*memprofile)
1678 log.Printf("could not create memory profile: ", err)
1680 runtime.GC() // get up-to-date statistics
1681 if err := pprof.WriteHeapProfile(f); err != nil {
1682 log.Printf("could not write memory profile: ", err)
1684 closeerr := f.Close()
1685 if closeerr != nil {
1686 log.Printf("closing memprofile file: ", err)
1691 log.Fatalf("%s: %v", containerId, runerr)