1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
30 "git.curoverse.com/arvados.git/lib/crunchstat"
31 "git.curoverse.com/arvados.git/sdk/go/arvados"
32 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
33 "git.curoverse.com/arvados.git/sdk/go/keepclient"
34 "git.curoverse.com/arvados.git/sdk/go/manifest"
35 arvadosVersion "git.curoverse.com/arvados.git/sdk/go/version"
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"
43 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
44 type IArvadosClient interface {
45 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
46 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
47 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
48 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
49 CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
50 Discovery(key string) (interface{}, error)
53 // ErrCancelled is the error returned when the container is cancelled.
54 var ErrCancelled = errors.New("Cancelled")
56 // IKeepClient is the minimal Keep API methods used by crunch-run.
57 type IKeepClient interface {
58 PutHB(hash string, buf []byte) (string, int, error)
59 ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error)
63 // NewLogWriter is a factory function to create a new log writer.
64 type NewLogWriter func(name string) io.WriteCloser
66 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
68 type MkTempDir func(string, string) (string, error)
70 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
71 type ThinDockerClient interface {
72 ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error)
73 ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
74 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error)
75 ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error
76 ContainerStop(ctx context.Context, container string, timeout *time.Duration) error
77 ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error)
78 ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error)
79 ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error)
80 ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error)
83 // ThinDockerClientProxy is a proxy implementation of ThinDockerClient
84 // that executes the docker requests on dockerclient.Client
85 type ThinDockerClientProxy struct {
86 Docker *dockerclient.Client
89 // ContainerAttach invokes dockerclient.Client.ContainerAttach
90 func (proxy ThinDockerClientProxy) ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error) {
91 return proxy.Docker.ContainerAttach(ctx, container, options)
94 // ContainerCreate invokes dockerclient.Client.ContainerCreate
95 func (proxy ThinDockerClientProxy) ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
96 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error) {
97 return proxy.Docker.ContainerCreate(ctx, config, hostConfig, networkingConfig, containerName)
100 // ContainerStart invokes dockerclient.Client.ContainerStart
101 func (proxy ThinDockerClientProxy) ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error {
102 return proxy.Docker.ContainerStart(ctx, container, options)
105 // ContainerStop invokes dockerclient.Client.ContainerStop
106 func (proxy ThinDockerClientProxy) ContainerStop(ctx context.Context, container string, timeout *time.Duration) error {
107 return proxy.Docker.ContainerStop(ctx, container, timeout)
110 // ContainerWait invokes dockerclient.Client.ContainerWait
111 func (proxy ThinDockerClientProxy) ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error) {
112 return proxy.Docker.ContainerWait(ctx, container, condition)
115 // ImageInspectWithRaw invokes dockerclient.Client.ImageInspectWithRaw
116 func (proxy ThinDockerClientProxy) ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error) {
117 return proxy.Docker.ImageInspectWithRaw(ctx, image)
120 // ImageLoad invokes dockerclient.Client.ImageLoad
121 func (proxy ThinDockerClientProxy) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error) {
122 return proxy.Docker.ImageLoad(ctx, input, quiet)
125 // ImageRemove invokes dockerclient.Client.ImageRemove
126 func (proxy ThinDockerClientProxy) ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {
127 return proxy.Docker.ImageRemove(ctx, image, options)
130 // ContainerRunner is the main stateful struct used for a single execution of a
132 type ContainerRunner struct {
133 Docker ThinDockerClient
134 ArvClient IArvadosClient
137 ContainerConfig dockercontainer.Config
138 dockercontainer.HostConfig
143 loggingDone chan bool
144 CrunchLog *ThrottledLogger
145 Stdout io.WriteCloser
146 Stderr io.WriteCloser
147 LogCollection *CollectionWriter
154 CleanupTempDir []string
156 Volumes map[string]struct{}
158 SigChan chan os.Signal
159 ArvMountExit chan error
162 statLogger io.WriteCloser
163 statReporter *crunchstat.Reporter
164 statInterval time.Duration
166 // What we expect the container's cgroup parent to be.
167 expectCgroupParent string
168 // What we tell docker to use as the container's cgroup
169 // parent. Note: Ideally we would use the same field for both
170 // expectCgroupParent and setCgroupParent, and just make it
171 // default to "docker". However, when using docker < 1.10 with
172 // systemd, specifying a non-empty cgroup parent (even the
173 // default value "docker") hits a docker bug
174 // (https://github.com/docker/docker/issues/17126). Using two
175 // separate fields makes it possible to use the "expect cgroup
176 // parent to be X" feature even on sites where the "specify
177 // cgroup parent" feature breaks.
178 setCgroupParent string
180 cStateLock sync.Mutex
181 cStarted bool // StartContainer() succeeded
182 cCancelled bool // StopContainer() invoked
184 enableNetwork string // one of "default" or "always"
185 networkMode string // passed through to HostConfig.NetworkMode
186 arvMountLog *ThrottledLogger
189 // setupSignals sets up signal handling to gracefully terminate the underlying
190 // Docker container and update state when receiving a TERM, INT or QUIT signal.
191 func (runner *ContainerRunner) setupSignals() {
192 runner.SigChan = make(chan os.Signal, 1)
193 signal.Notify(runner.SigChan, syscall.SIGTERM)
194 signal.Notify(runner.SigChan, syscall.SIGINT)
195 signal.Notify(runner.SigChan, syscall.SIGQUIT)
197 go func(sig chan os.Signal) {
200 runner.CrunchLog.Printf("Caught signal %v", s)
206 // stop the underlying Docker container.
207 func (runner *ContainerRunner) stop() {
208 runner.cStateLock.Lock()
209 defer runner.cStateLock.Unlock()
210 if runner.cCancelled {
213 runner.cCancelled = true
215 timeout := time.Duration(10)
216 err := runner.Docker.ContainerStop(context.TODO(), runner.ContainerID, &(timeout))
218 runner.CrunchLog.Printf("StopContainer failed: %s", err)
220 // Suppress multiple calls to stop()
221 runner.cStarted = false
225 func (runner *ContainerRunner) stopSignals() {
226 if runner.SigChan != nil {
227 signal.Stop(runner.SigChan)
228 close(runner.SigChan)
232 // LoadImage determines the docker image id from the container record and
233 // checks if it is available in the local Docker image store. If not, it loads
234 // the image from Keep.
235 func (runner *ContainerRunner) LoadImage() (err error) {
237 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
239 var collection arvados.Collection
240 err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
242 return fmt.Errorf("While getting container image collection: %v", err)
244 manifest := manifest.Manifest{Text: collection.ManifestText}
245 var img, imageID string
246 for ms := range manifest.StreamIter() {
247 img = ms.FileStreamSegments[0].Name
248 if !strings.HasSuffix(img, ".tar") {
249 return fmt.Errorf("First file in the container image collection does not end in .tar")
251 imageID = img[:len(img)-4]
254 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
256 _, _, err = runner.Docker.ImageInspectWithRaw(context.TODO(), imageID)
258 runner.CrunchLog.Print("Loading Docker image from keep")
260 var readCloser io.ReadCloser
261 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
263 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
266 response, err := runner.Docker.ImageLoad(context.TODO(), readCloser, true)
268 return fmt.Errorf("While loading container image into Docker: %v", err)
271 defer response.Body.Close()
272 rbody, err := ioutil.ReadAll(response.Body)
274 return fmt.Errorf("Reading response to image load: %v", err)
276 runner.CrunchLog.Printf("Docker response: %s", rbody)
278 runner.CrunchLog.Print("Docker image is available")
281 runner.ContainerConfig.Image = imageID
283 runner.Kc.ClearBlockCache()
288 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
289 c = exec.Command("arv-mount", arvMountCmd...)
291 // Copy our environment, but override ARVADOS_API_TOKEN with
292 // the container auth token.
294 for _, s := range os.Environ() {
295 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
296 c.Env = append(c.Env, s)
299 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
301 runner.arvMountLog = NewThrottledLogger(runner.NewLogWriter("arv-mount"))
302 c.Stdout = runner.arvMountLog
303 c.Stderr = runner.arvMountLog
305 runner.CrunchLog.Printf("Running %v", c.Args)
312 statReadme := make(chan bool)
313 runner.ArvMountExit = make(chan error)
318 time.Sleep(100 * time.Millisecond)
319 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
331 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
333 runner.ArvMountExit <- mnterr
334 close(runner.ArvMountExit)
340 case err := <-runner.ArvMountExit:
341 runner.ArvMount = nil
349 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
350 if runner.ArvMountPoint == "" {
351 runner.ArvMountPoint, err = runner.MkTempDir("", prefix)
356 func (runner *ContainerRunner) SetupMounts() (err error) {
357 err = runner.SetupArvMountPoint("keep")
359 return fmt.Errorf("While creating keep mount temp dir: %v", err)
364 arvMountCmd := []string{
368 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
370 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
371 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
374 collectionPaths := []string{}
376 runner.Volumes = make(map[string]struct{})
377 needCertMount := true
380 for bind := range runner.Container.Mounts {
381 binds = append(binds, bind)
385 for _, bind := range binds {
386 mnt := runner.Container.Mounts[bind]
387 if bind == "stdout" || bind == "stderr" {
388 // Is it a "file" mount kind?
389 if mnt.Kind != "file" {
390 return fmt.Errorf("Unsupported mount kind '%s' for %s. Only 'file' is supported.", mnt.Kind, bind)
393 // Does path start with OutputPath?
394 prefix := runner.Container.OutputPath
395 if !strings.HasSuffix(prefix, "/") {
398 if !strings.HasPrefix(mnt.Path, prefix) {
399 return fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
404 // Is it a "collection" mount kind?
405 if mnt.Kind != "collection" && mnt.Kind != "json" {
406 return fmt.Errorf("Unsupported mount kind '%s' for stdin. Only 'collection' or 'json' are supported.", mnt.Kind)
410 if bind == "/etc/arvados/ca-certificates.crt" {
411 needCertMount = false
414 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
415 if mnt.Kind != "collection" {
416 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
421 case mnt.Kind == "collection" && bind != "stdin":
423 if mnt.UUID != "" && mnt.PortableDataHash != "" {
424 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
428 return fmt.Errorf("Writing to existing collections currently not permitted.")
431 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
432 } else if mnt.PortableDataHash != "" {
434 return fmt.Errorf("Can never write to a collection specified by portable data hash")
436 idx := strings.Index(mnt.PortableDataHash, "/")
438 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
439 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
440 runner.Container.Mounts[bind] = mnt
442 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
443 if mnt.Path != "" && mnt.Path != "." {
444 if strings.HasPrefix(mnt.Path, "./") {
445 mnt.Path = mnt.Path[2:]
446 } else if strings.HasPrefix(mnt.Path, "/") {
447 mnt.Path = mnt.Path[1:]
449 src += "/" + mnt.Path
452 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
453 arvMountCmd = append(arvMountCmd, "--mount-tmp")
454 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
458 if bind == runner.Container.OutputPath {
459 runner.HostOutputDir = src
460 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
461 return fmt.Errorf("Writable mount points are not permitted underneath the output_path: %v", bind)
463 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
465 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
467 collectionPaths = append(collectionPaths, src)
469 case mnt.Kind == "tmp":
471 tmpdir, err = runner.MkTempDir("", "")
473 return fmt.Errorf("While creating mount temp dir: %v", err)
475 st, staterr := os.Stat(tmpdir)
477 return fmt.Errorf("While Stat on temp dir: %v", staterr)
479 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
481 return fmt.Errorf("While Chmod temp dir: %v", err)
483 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
484 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", tmpdir, bind))
485 if bind == runner.Container.OutputPath {
486 runner.HostOutputDir = tmpdir
489 case mnt.Kind == "json":
490 jsondata, err := json.Marshal(mnt.Content)
492 return fmt.Errorf("encoding json data: %v", err)
494 // Create a tempdir with a single file
495 // (instead of just a tempfile): this way we
496 // can ensure the file is world-readable
497 // inside the container, without having to
498 // make it world-readable on the docker host.
499 tmpdir, err := runner.MkTempDir("", "")
501 return fmt.Errorf("creating temp dir: %v", err)
503 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
504 tmpfn := filepath.Join(tmpdir, "mountdata.json")
505 err = ioutil.WriteFile(tmpfn, jsondata, 0644)
507 return fmt.Errorf("writing temp file: %v", err)
509 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
513 if runner.HostOutputDir == "" {
514 return fmt.Errorf("Output path does not correspond to a writable mount point")
517 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
518 for _, certfile := range arvadosclient.CertFiles {
519 _, err := os.Stat(certfile)
521 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
528 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
530 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
532 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
534 token, err := runner.ContainerToken()
536 return fmt.Errorf("could not get container token: %s", err)
539 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
541 return fmt.Errorf("While trying to start arv-mount: %v", err)
544 for _, p := range collectionPaths {
547 return fmt.Errorf("While checking that input files exist: %v", err)
554 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
555 // Handle docker log protocol
556 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
558 header := make([]byte, 8)
560 _, readerr := io.ReadAtLeast(containerReader, header, 8)
563 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
566 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
569 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
574 if readerr != io.EOF {
575 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
578 closeerr := runner.Stdout.Close()
580 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
583 closeerr = runner.Stderr.Close()
585 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
588 if runner.statReporter != nil {
589 runner.statReporter.Stop()
590 closeerr = runner.statLogger.Close()
592 runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
596 runner.loggingDone <- true
597 close(runner.loggingDone)
603 func (runner *ContainerRunner) StartCrunchstat() {
604 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
605 runner.statReporter = &crunchstat.Reporter{
606 CID: runner.ContainerID,
607 Logger: log.New(runner.statLogger, "", 0),
608 CgroupParent: runner.expectCgroupParent,
609 CgroupRoot: runner.cgroupRoot,
610 PollPeriod: runner.statInterval,
612 runner.statReporter.Start()
615 type infoCommand struct {
620 // Gather node information and store it on the log for debugging
622 func (runner *ContainerRunner) LogNodeInfo() (err error) {
623 w := runner.NewLogWriter("node-info")
624 logger := log.New(w, "node-info", 0)
626 commands := []infoCommand{
628 label: "Host Information",
629 cmd: []string{"uname", "-a"},
632 label: "CPU Information",
633 cmd: []string{"cat", "/proc/cpuinfo"},
636 label: "Memory Information",
637 cmd: []string{"cat", "/proc/meminfo"},
641 cmd: []string{"df", "-m", "/", os.TempDir()},
644 label: "Disk INodes",
645 cmd: []string{"df", "-i", "/", os.TempDir()},
649 // Run commands with informational output to be logged.
651 for _, command := range commands {
652 out, err = exec.Command(command.cmd[0], command.cmd[1:]...).CombinedOutput()
654 return fmt.Errorf("While running command %q: %v",
657 logger.Println(command.label)
658 for _, line := range strings.Split(string(out), "\n") {
659 logger.Println(" ", line)
665 return fmt.Errorf("While closing node-info logs: %v", err)
670 // Get and save the raw JSON container record from the API server
671 func (runner *ContainerRunner) LogContainerRecord() (err error) {
673 ArvClient: runner.ArvClient,
674 UUID: runner.Container.UUID,
675 loggingStream: "container",
676 writeCloser: runner.LogCollection.Open("container.json"),
679 // Get Container record JSON from the API Server
680 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
682 return fmt.Errorf("While retrieving container record from the API server: %v", err)
686 dec := json.NewDecoder(reader)
688 var cr map[string]interface{}
689 if err = dec.Decode(&cr); err != nil {
690 return fmt.Errorf("While decoding the container record JSON response: %v", err)
692 // Re-encode it using indentation to improve readability
693 enc := json.NewEncoder(w)
694 enc.SetIndent("", " ")
695 if err = enc.Encode(cr); err != nil {
696 return fmt.Errorf("While logging the JSON container record: %v", err)
700 return fmt.Errorf("While closing container.json log: %v", err)
705 // AttachStreams connects the docker container stdin, stdout and stderr logs
706 // to the Arvados logger which logs to Keep and the API server logs table.
707 func (runner *ContainerRunner) AttachStreams() (err error) {
709 runner.CrunchLog.Print("Attaching container streams")
711 // If stdin mount is provided, attach it to the docker container
712 var stdinRdr arvados.File
714 if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
715 if stdinMnt.Kind == "collection" {
716 var stdinColl arvados.Collection
717 collId := stdinMnt.UUID
719 collId = stdinMnt.PortableDataHash
721 err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
723 return fmt.Errorf("While getting stding collection: %v", err)
726 stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
727 if os.IsNotExist(err) {
728 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
729 } else if err != nil {
730 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
732 } else if stdinMnt.Kind == "json" {
733 stdinJson, err = json.Marshal(stdinMnt.Content)
735 return fmt.Errorf("While encoding stdin json data: %v", err)
740 stdinUsed := stdinRdr != nil || len(stdinJson) != 0
741 response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
742 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
744 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
747 runner.loggingDone = make(chan bool)
749 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
750 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
754 runner.Stdout = stdoutFile
756 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
759 if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
760 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
764 runner.Stderr = stderrFile
766 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
771 _, err := io.Copy(response.Conn, stdinRdr)
773 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
777 response.CloseWrite()
779 } else if len(stdinJson) != 0 {
781 _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
783 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
786 response.CloseWrite()
790 go runner.ProcessDockerAttach(response.Reader)
795 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
796 stdoutPath := mntPath[len(runner.Container.OutputPath):]
797 index := strings.LastIndex(stdoutPath, "/")
799 subdirs := stdoutPath[:index]
801 st, err := os.Stat(runner.HostOutputDir)
803 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
805 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
806 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
808 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
812 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
814 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
817 return stdoutFile, nil
820 // CreateContainer creates the docker container.
821 func (runner *ContainerRunner) CreateContainer() error {
822 runner.CrunchLog.Print("Creating Docker container")
824 runner.ContainerConfig.Cmd = runner.Container.Command
825 if runner.Container.Cwd != "." {
826 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
829 for k, v := range runner.Container.Environment {
830 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
833 runner.ContainerConfig.Volumes = runner.Volumes
835 runner.HostConfig = dockercontainer.HostConfig{
837 LogConfig: dockercontainer.LogConfig{
840 Resources: dockercontainer.Resources{
841 CgroupParent: runner.setCgroupParent,
845 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
846 tok, err := runner.ContainerToken()
850 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
851 "ARVADOS_API_TOKEN="+tok,
852 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
853 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
855 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
857 if runner.enableNetwork == "always" {
858 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
860 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
864 _, stdinUsed := runner.Container.Mounts["stdin"]
865 runner.ContainerConfig.OpenStdin = stdinUsed
866 runner.ContainerConfig.StdinOnce = stdinUsed
867 runner.ContainerConfig.AttachStdin = stdinUsed
868 runner.ContainerConfig.AttachStdout = true
869 runner.ContainerConfig.AttachStderr = true
871 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
873 return fmt.Errorf("While creating container: %v", err)
876 runner.ContainerID = createdBody.ID
878 return runner.AttachStreams()
881 // StartContainer starts the docker container created by CreateContainer.
882 func (runner *ContainerRunner) StartContainer() error {
883 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
884 runner.cStateLock.Lock()
885 defer runner.cStateLock.Unlock()
886 if runner.cCancelled {
889 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
890 dockertypes.ContainerStartOptions{})
893 if strings.Contains(err.Error(), "no such file or directory") {
894 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])
896 return fmt.Errorf("could not start container: %v%s", err, advice)
898 runner.cStarted = true
902 // WaitFinish waits for the container to terminate, capture the exit code, and
903 // close the stdout/stderr logging.
904 func (runner *ContainerRunner) WaitFinish() (err error) {
905 runner.CrunchLog.Print("Waiting for container to finish")
907 waitOk, waitErr := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID, "not-running")
910 <-runner.ArvMountExit
912 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
917 var waitBody dockercontainer.ContainerWaitOKBody
919 case waitBody = <-waitOk:
920 case err = <-waitErr:
923 // Container isn't running any more
924 runner.cStarted = false
927 return fmt.Errorf("container wait: %v", err)
930 runner.CrunchLog.Printf("Container exited with code: %v", waitBody.StatusCode)
931 code := int(waitBody.StatusCode)
932 runner.ExitCode = &code
934 // wait for stdout/stderr to complete
940 var ErrNotInOutputDir = fmt.Errorf("Must point to path within the output directory")
942 func (runner *ContainerRunner) derefOutputSymlink(path string, startinfo os.FileInfo) (tgt string, readlinktgt string, info os.FileInfo, err error) {
943 // Follow symlinks if necessary
948 for followed := 0; info.Mode()&os.ModeSymlink != 0; followed++ {
949 if followed >= limitFollowSymlinks {
950 // Got stuck in a loop or just a pathological number of links, give up.
951 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
955 readlinktgt, err = os.Readlink(nextlink)
961 if !strings.HasPrefix(tgt, "/") {
962 // Relative symlink, resolve it to host path
963 tgt = filepath.Join(filepath.Dir(path), tgt)
965 if strings.HasPrefix(tgt, runner.Container.OutputPath+"/") && !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
966 // Absolute symlink to container output path, adjust it to host output path.
967 tgt = filepath.Join(runner.HostOutputDir, tgt[len(runner.Container.OutputPath):])
969 if !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
970 // After dereferencing, symlink target must either be
971 // within output directory, or must point to a
973 err = ErrNotInOutputDir
977 info, err = os.Lstat(tgt)
980 err = fmt.Errorf("Symlink in output %q points to invalid location %q: %v",
981 path[len(runner.HostOutputDir):], readlinktgt, err)
991 var limitFollowSymlinks = 10
993 // UploadFile uploads files within the output directory, with special handling
994 // for symlinks. If the symlink leads to a keep mount, copy the manifest text
995 // from the keep mount into the output manifestText. Ensure that whether
996 // symlinks are relative or absolute, every symlink target (even targets that
997 // are symlinks themselves) must point to a path in either the output directory
998 // or a collection mount.
1000 // Assumes initial value of "path" is absolute, and located within runner.HostOutputDir.
1001 func (runner *ContainerRunner) UploadOutputFile(
1006 walkUpload *WalkUpload,
1007 relocateFrom string,
1009 followed int) (manifestText string, err error) {
1011 if info.Mode().IsDir() {
1019 if followed >= limitFollowSymlinks {
1020 // Got stuck in a loop or just a pathological number of
1021 // directory links, give up.
1022 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
1026 // When following symlinks, the source path may need to be logically
1027 // relocated to some other path within the output collection. Remove
1028 // the relocateFrom prefix and replace it with relocateTo.
1029 relocated := relocateTo + path[len(relocateFrom):]
1031 tgt, readlinktgt, info, derefErr := runner.derefOutputSymlink(path, info)
1032 if derefErr != nil && derefErr != ErrNotInOutputDir {
1036 // go through mounts and try reverse map to collection reference
1037 for _, bind := range binds {
1038 mnt := runner.Container.Mounts[bind]
1039 if tgt == bind || strings.HasPrefix(tgt, bind+"/") {
1040 // get path relative to bind
1041 targetSuffix := tgt[len(bind):]
1043 // Copy mount and adjust the path to add path relative to the bind
1044 adjustedMount := mnt
1045 adjustedMount.Path = filepath.Join(adjustedMount.Path, targetSuffix)
1047 // Terminates in this keep mount, so add the
1048 // manifest text at appropriate location.
1049 outputSuffix := path[len(runner.HostOutputDir):]
1050 manifestText, err = runner.getCollectionManifestForPath(adjustedMount, outputSuffix)
1055 // If target is not a collection mount, it must be located within the
1056 // output directory, otherwise it is an error.
1057 if derefErr == ErrNotInOutputDir {
1058 err = fmt.Errorf("Symlink in output %q points to invalid location %q, must point to path within the output directory.",
1059 path[len(runner.HostOutputDir):], readlinktgt)
1063 if info.Mode().IsRegular() {
1064 return "", walkUpload.UploadFile(relocated, tgt)
1067 if info.Mode().IsDir() {
1068 // Symlink leads to directory. Walk() doesn't follow
1069 // directory symlinks, so we walk the target directory
1070 // instead. Within the walk, file paths are relocated
1071 // so they appear under the original symlink path.
1072 err = filepath.Walk(tgt, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
1074 m, walkerr = runner.UploadOutputFile(walkpath, walkinfo, walkerr,
1075 binds, walkUpload, tgt, relocated, followed+1)
1077 manifestText = manifestText + m
1087 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
1088 func (runner *ContainerRunner) CaptureOutput() error {
1089 if runner.finalState != "Complete" {
1093 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
1094 // Output may have been set directly by the container, so
1095 // refresh the container record to check.
1096 err := runner.ArvClient.Get("containers", runner.Container.UUID,
1097 nil, &runner.Container)
1101 if runner.Container.Output != "" {
1102 // Container output is already set.
1103 runner.OutputPDH = &runner.Container.Output
1108 if runner.HostOutputDir == "" {
1112 _, err := os.Stat(runner.HostOutputDir)
1114 return fmt.Errorf("While checking host output path: %v", err)
1117 // Pre-populate output from the configured mount points
1119 for bind, mnt := range runner.Container.Mounts {
1120 if mnt.Kind == "collection" {
1121 binds = append(binds, bind)
1126 var manifestText string
1128 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
1129 _, err = os.Stat(collectionMetafile)
1131 // Regular directory
1133 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
1134 walkUpload := cw.BeginUpload(runner.HostOutputDir, runner.CrunchLog.Logger)
1137 err = filepath.Walk(runner.HostOutputDir, func(path string, info os.FileInfo, err error) error {
1138 m, err = runner.UploadOutputFile(path, info, err, binds, walkUpload, "", "", 0)
1140 manifestText = manifestText + m
1145 cw.EndUpload(walkUpload)
1148 return fmt.Errorf("While uploading output files: %v", err)
1151 m, err = cw.ManifestText()
1152 manifestText = manifestText + m
1154 return fmt.Errorf("While uploading output files: %v", err)
1157 // FUSE mount directory
1158 file, openerr := os.Open(collectionMetafile)
1160 return fmt.Errorf("While opening FUSE metafile: %v", err)
1164 var rec arvados.Collection
1165 err = json.NewDecoder(file).Decode(&rec)
1167 return fmt.Errorf("While reading FUSE metafile: %v", err)
1169 manifestText = rec.ManifestText
1172 for _, bind := range binds {
1173 mnt := runner.Container.Mounts[bind]
1175 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
1177 if bindSuffix == bind || len(bindSuffix) <= 0 {
1178 // either does not start with OutputPath or is OutputPath itself
1182 if mnt.ExcludeFromOutput == true {
1186 // append to manifest_text
1187 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
1192 manifestText = manifestText + m
1196 var response arvados.Collection
1197 manifest := manifest.Manifest{Text: manifestText}
1198 manifestText = manifest.Extract(".", ".").Text
1199 err = runner.ArvClient.Create("collections",
1201 "ensure_unique_name": true,
1202 "collection": arvadosclient.Dict{
1204 "name": "output for " + runner.Container.UUID,
1205 "manifest_text": manifestText}},
1208 return fmt.Errorf("While creating output collection: %v", err)
1210 runner.OutputPDH = &response.PortableDataHash
1214 var outputCollections = make(map[string]arvados.Collection)
1216 // Fetch the collection for the mnt.PortableDataHash
1217 // Return the manifest_text fragment corresponding to the specified mnt.Path
1218 // after making any required updates.
1220 // If mnt.Path is not specified,
1221 // return the entire manifest_text after replacing any "." with bindSuffix
1222 // If mnt.Path corresponds to one stream,
1223 // return the manifest_text for that stream after replacing that stream name with bindSuffix
1224 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1225 // for that stream after replacing stream name with bindSuffix minus the last word
1226 // and the file name with last word of the bindSuffix
1227 // Allowed path examples:
1229 // "path":"/subdir1"
1230 // "path":"/subdir1/subdir2"
1231 // "path":"/subdir/filename" etc
1232 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1233 collection := outputCollections[mnt.PortableDataHash]
1234 if collection.PortableDataHash == "" {
1235 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1237 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1239 outputCollections[mnt.PortableDataHash] = collection
1242 if collection.ManifestText == "" {
1243 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1247 mft := manifest.Manifest{Text: collection.ManifestText}
1248 extracted := mft.Extract(mnt.Path, bindSuffix)
1249 if extracted.Err != nil {
1250 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1252 return extracted.Text, nil
1255 func (runner *ContainerRunner) CleanupDirs() {
1256 if runner.ArvMount != nil {
1258 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1259 umount.Stdout = runner.CrunchLog
1260 umount.Stderr = runner.CrunchLog
1261 runner.CrunchLog.Printf("Running %v", umount.Args)
1262 umnterr := umount.Start()
1265 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1267 // If arv-mount --unmount gets stuck for any reason, we
1268 // don't want to wait for it forever. Do Wait() in a goroutine
1269 // so it doesn't block crunch-run.
1270 umountExit := make(chan error)
1272 mnterr := umount.Wait()
1274 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1276 umountExit <- mnterr
1279 for again := true; again; {
1285 case <-runner.ArvMountExit:
1287 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1288 runner.CrunchLog.Printf("Timed out waiting for unmount")
1290 umount.Process.Kill()
1292 runner.ArvMount.Process.Kill()
1298 if runner.ArvMountPoint != "" {
1299 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1300 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1304 for _, tmpdir := range runner.CleanupTempDir {
1305 if rmerr := os.RemoveAll(tmpdir); rmerr != nil {
1306 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1311 // CommitLogs posts the collection containing the final container logs.
1312 func (runner *ContainerRunner) CommitLogs() error {
1313 runner.CrunchLog.Print(runner.finalState)
1315 if runner.arvMountLog != nil {
1316 runner.arvMountLog.Close()
1318 runner.CrunchLog.Close()
1320 // Closing CrunchLog above allows them to be committed to Keep at this
1321 // point, but re-open crunch log with ArvClient in case there are any
1322 // other further errors (such as failing to write the log to Keep!)
1323 // while shutting down
1324 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1325 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1326 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1328 if runner.LogsPDH != nil {
1329 // If we have already assigned something to LogsPDH,
1330 // we must be closing the re-opened log, which won't
1331 // end up getting attached to the container record and
1332 // therefore doesn't need to be saved as a collection
1333 // -- it exists only to send logs to other channels.
1337 mt, err := runner.LogCollection.ManifestText()
1339 return fmt.Errorf("While creating log manifest: %v", err)
1342 var response arvados.Collection
1343 err = runner.ArvClient.Create("collections",
1345 "ensure_unique_name": true,
1346 "collection": arvadosclient.Dict{
1348 "name": "logs for " + runner.Container.UUID,
1349 "manifest_text": mt}},
1352 return fmt.Errorf("While creating log collection: %v", err)
1354 runner.LogsPDH = &response.PortableDataHash
1358 // UpdateContainerRunning updates the container state to "Running"
1359 func (runner *ContainerRunner) UpdateContainerRunning() error {
1360 runner.cStateLock.Lock()
1361 defer runner.cStateLock.Unlock()
1362 if runner.cCancelled {
1365 return runner.ArvClient.Update("containers", runner.Container.UUID,
1366 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1369 // ContainerToken returns the api_token the container (and any
1370 // arv-mount processes) are allowed to use.
1371 func (runner *ContainerRunner) ContainerToken() (string, error) {
1372 if runner.token != "" {
1373 return runner.token, nil
1376 var auth arvados.APIClientAuthorization
1377 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1381 runner.token = auth.APIToken
1382 return runner.token, nil
1385 // UpdateContainerComplete updates the container record state on API
1386 // server to "Complete" or "Cancelled"
1387 func (runner *ContainerRunner) UpdateContainerFinal() error {
1388 update := arvadosclient.Dict{}
1389 update["state"] = runner.finalState
1390 if runner.LogsPDH != nil {
1391 update["log"] = *runner.LogsPDH
1393 if runner.finalState == "Complete" {
1394 if runner.ExitCode != nil {
1395 update["exit_code"] = *runner.ExitCode
1397 if runner.OutputPDH != nil {
1398 update["output"] = *runner.OutputPDH
1401 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1404 // IsCancelled returns the value of Cancelled, with goroutine safety.
1405 func (runner *ContainerRunner) IsCancelled() bool {
1406 runner.cStateLock.Lock()
1407 defer runner.cStateLock.Unlock()
1408 return runner.cCancelled
1411 // NewArvLogWriter creates an ArvLogWriter
1412 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1413 return &ArvLogWriter{
1414 ArvClient: runner.ArvClient,
1415 UUID: runner.Container.UUID,
1416 loggingStream: name,
1417 writeCloser: runner.LogCollection.Open(name + ".txt")}
1420 // Run the full container lifecycle.
1421 func (runner *ContainerRunner) Run() (err error) {
1422 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1424 hostname, hosterr := os.Hostname()
1426 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1428 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1431 runner.finalState = "Queued"
1434 runner.stopSignals()
1435 runner.CleanupDirs()
1437 runner.CrunchLog.Printf("crunch-run finished")
1438 runner.CrunchLog.Close()
1442 // checkErr prints e (unless it's nil) and sets err to
1443 // e (unless err is already non-nil). Thus, if err
1444 // hasn't already been assigned when Run() returns,
1445 // this cleanup func will cause Run() to return the
1446 // first non-nil error that is passed to checkErr().
1447 checkErr := func(e error) {
1451 runner.CrunchLog.Print(e)
1455 if runner.finalState == "Complete" {
1456 // There was an error in the finalization.
1457 runner.finalState = "Cancelled"
1461 // Log the error encountered in Run(), if any
1464 if runner.finalState == "Queued" {
1465 runner.UpdateContainerFinal()
1469 if runner.IsCancelled() {
1470 runner.finalState = "Cancelled"
1471 // but don't return yet -- we still want to
1472 // capture partial output and write logs
1475 checkErr(runner.CaptureOutput())
1476 checkErr(runner.CommitLogs())
1477 checkErr(runner.UpdateContainerFinal())
1480 err = runner.fetchContainerRecord()
1485 // setup signal handling
1486 runner.setupSignals()
1488 // check for and/or load image
1489 err = runner.LoadImage()
1491 runner.finalState = "Cancelled"
1492 err = fmt.Errorf("While loading container image: %v", err)
1496 // set up FUSE mount and binds
1497 err = runner.SetupMounts()
1499 runner.finalState = "Cancelled"
1500 err = fmt.Errorf("While setting up mounts: %v", err)
1504 err = runner.CreateContainer()
1509 // Gather and record node information
1510 err = runner.LogNodeInfo()
1514 // Save container.json record on log collection
1515 err = runner.LogContainerRecord()
1520 runner.StartCrunchstat()
1522 if runner.IsCancelled() {
1526 err = runner.UpdateContainerRunning()
1530 runner.finalState = "Cancelled"
1532 err = runner.StartContainer()
1537 err = runner.WaitFinish()
1539 runner.finalState = "Complete"
1544 // Fetch the current container record (uuid = runner.Container.UUID)
1545 // into runner.Container.
1546 func (runner *ContainerRunner) fetchContainerRecord() error {
1547 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1549 return fmt.Errorf("error fetching container record: %v", err)
1551 defer reader.Close()
1553 dec := json.NewDecoder(reader)
1555 err = dec.Decode(&runner.Container)
1557 return fmt.Errorf("error decoding container record: %v", err)
1562 // NewContainerRunner creates a new container runner.
1563 func NewContainerRunner(api IArvadosClient,
1565 docker ThinDockerClient,
1566 containerUUID string) *ContainerRunner {
1568 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1569 cr.NewLogWriter = cr.NewArvLogWriter
1570 cr.RunArvMount = cr.ArvMountCmd
1571 cr.MkTempDir = ioutil.TempDir
1572 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1573 cr.Container.UUID = containerUUID
1574 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1575 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1577 loadLogThrottleParams(api)
1583 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1584 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1585 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1586 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1587 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1588 enableNetwork := flag.String("container-enable-networking", "default",
1589 `Specify if networking should be enabled for container. One of 'default', 'always':
1590 default: only enable networking if container requests it.
1591 always: containers always have networking enabled
1593 networkMode := flag.String("container-network-mode", "default",
1594 `Set networking mode for container. Corresponds to Docker network mode (--net).
1596 memprofile := flag.String("memprofile", "", "write memory profile to `file` after running container")
1597 getVersion := flags.Bool("version", false, "Print version information and exit.")
1600 // Print version information if requested
1602 fmt.Printf("Version: %s\n", arvadosVersion.GetVersion())
1606 log.Printf("crunch-run %q started", arvadosVersion.GetVersion())
1608 containerId := flag.Arg(0)
1610 if *caCertsPath != "" {
1611 arvadosclient.CertFiles = []string{*caCertsPath}
1614 api, err := arvadosclient.MakeArvadosClient()
1616 log.Fatalf("%s: %v", containerId, err)
1620 var kc *keepclient.KeepClient
1621 kc, err = keepclient.MakeKeepClient(api)
1623 log.Fatalf("%s: %v", containerId, err)
1625 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1628 var docker *dockerclient.Client
1629 // API version 1.21 corresponds to Docker 1.9, which is currently the
1630 // minimum version we want to support.
1631 docker, err = dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1633 log.Fatalf("%s: %v", containerId, err)
1636 dockerClientProxy := ThinDockerClientProxy{Docker: docker}
1638 cr := NewContainerRunner(api, kc, dockerClientProxy, containerId)
1639 cr.statInterval = *statInterval
1640 cr.cgroupRoot = *cgroupRoot
1641 cr.expectCgroupParent = *cgroupParent
1642 cr.enableNetwork = *enableNetwork
1643 cr.networkMode = *networkMode
1644 if *cgroupParentSubsystem != "" {
1645 p := findCgroup(*cgroupParentSubsystem)
1646 cr.setCgroupParent = p
1647 cr.expectCgroupParent = p
1652 if *memprofile != "" {
1653 f, err := os.Create(*memprofile)
1655 log.Printf("could not create memory profile: ", err)
1657 runtime.GC() // get up-to-date statistics
1658 if err := pprof.WriteHeapProfile(f); err != nil {
1659 log.Printf("could not write memory profile: ", err)
1661 closeerr := f.Close()
1662 if closeerr != nil {
1663 log.Printf("closing memprofile file: ", err)
1668 log.Fatalf("%s: %v", containerId, runerr)