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"
44 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
45 type IArvadosClient interface {
46 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
47 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
48 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
49 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
50 CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
51 Discovery(key string) (interface{}, error)
54 // ErrCancelled is the error returned when the container is cancelled.
55 var ErrCancelled = errors.New("Cancelled")
57 // IKeepClient is the minimal Keep API methods used by crunch-run.
58 type IKeepClient interface {
59 PutHB(hash string, buf []byte) (string, int, error)
60 ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error)
64 // NewLogWriter is a factory function to create a new log writer.
65 type NewLogWriter func(name string) io.WriteCloser
67 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
69 type MkTempDir func(string, string) (string, error)
71 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
72 type ThinDockerClient interface {
73 ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error)
74 ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
75 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error)
76 ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error
77 ContainerStop(ctx context.Context, container string, timeout *time.Duration) error
78 ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error)
79 ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error)
80 ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error)
81 ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error)
84 // ThinDockerClientProxy is a proxy implementation of ThinDockerClient
85 // that executes the docker requests on dockerclient.Client
86 type ThinDockerClientProxy struct {
87 Docker *dockerclient.Client
90 // ContainerAttach invokes dockerclient.Client.ContainerAttach
91 func (proxy ThinDockerClientProxy) ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error) {
92 return proxy.Docker.ContainerAttach(ctx, container, options)
95 // ContainerCreate invokes dockerclient.Client.ContainerCreate
96 func (proxy ThinDockerClientProxy) ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
97 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error) {
98 return proxy.Docker.ContainerCreate(ctx, config, hostConfig, networkingConfig, containerName)
101 // ContainerStart invokes dockerclient.Client.ContainerStart
102 func (proxy ThinDockerClientProxy) ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error {
103 return proxy.Docker.ContainerStart(ctx, container, options)
106 // ContainerStop invokes dockerclient.Client.ContainerStop
107 func (proxy ThinDockerClientProxy) ContainerStop(ctx context.Context, container string, timeout *time.Duration) error {
108 return proxy.Docker.ContainerStop(ctx, container, timeout)
111 // ContainerWait invokes dockerclient.Client.ContainerWait
112 func (proxy ThinDockerClientProxy) ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error) {
113 return proxy.Docker.ContainerWait(ctx, container, condition)
116 // ImageInspectWithRaw invokes dockerclient.Client.ImageInspectWithRaw
117 func (proxy ThinDockerClientProxy) ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error) {
118 return proxy.Docker.ImageInspectWithRaw(ctx, image)
121 // ImageLoad invokes dockerclient.Client.ImageLoad
122 func (proxy ThinDockerClientProxy) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error) {
123 return proxy.Docker.ImageLoad(ctx, input, quiet)
126 // ImageRemove invokes dockerclient.Client.ImageRemove
127 func (proxy ThinDockerClientProxy) ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {
128 return proxy.Docker.ImageRemove(ctx, image, options)
131 // ContainerRunner is the main stateful struct used for a single execution of a
133 type ContainerRunner struct {
134 Docker ThinDockerClient
135 ArvClient IArvadosClient
138 ContainerConfig dockercontainer.Config
139 dockercontainer.HostConfig
144 loggingDone chan bool
145 CrunchLog *ThrottledLogger
146 Stdout io.WriteCloser
147 Stderr io.WriteCloser
148 LogCollection *CollectionWriter
155 CleanupTempDir []string
157 Volumes map[string]struct{}
159 SigChan chan os.Signal
160 ArvMountExit chan error
163 statLogger io.WriteCloser
164 statReporter *crunchstat.Reporter
165 statInterval time.Duration
167 // What we expect the container's cgroup parent to be.
168 expectCgroupParent string
169 // What we tell docker to use as the container's cgroup
170 // parent. Note: Ideally we would use the same field for both
171 // expectCgroupParent and setCgroupParent, and just make it
172 // default to "docker". However, when using docker < 1.10 with
173 // systemd, specifying a non-empty cgroup parent (even the
174 // default value "docker") hits a docker bug
175 // (https://github.com/docker/docker/issues/17126). Using two
176 // separate fields makes it possible to use the "expect cgroup
177 // parent to be X" feature even on sites where the "specify
178 // cgroup parent" feature breaks.
179 setCgroupParent string
181 cStateLock sync.Mutex
182 cStarted bool // StartContainer() succeeded
183 cCancelled bool // StopContainer() invoked
185 enableNetwork string // one of "default" or "always"
186 networkMode string // passed through to HostConfig.NetworkMode
187 arvMountLog *ThrottledLogger
190 // setupSignals sets up signal handling to gracefully terminate the underlying
191 // Docker container and update state when receiving a TERM, INT or QUIT signal.
192 func (runner *ContainerRunner) setupSignals() {
193 runner.SigChan = make(chan os.Signal, 1)
194 signal.Notify(runner.SigChan, syscall.SIGTERM)
195 signal.Notify(runner.SigChan, syscall.SIGINT)
196 signal.Notify(runner.SigChan, syscall.SIGQUIT)
198 go func(sig chan os.Signal) {
201 runner.CrunchLog.Printf("Caught signal %v", s)
207 // stop the underlying Docker container.
208 func (runner *ContainerRunner) stop() {
209 runner.cStateLock.Lock()
210 defer runner.cStateLock.Unlock()
211 if runner.cCancelled {
214 runner.cCancelled = true
216 timeout := time.Duration(10)
217 err := runner.Docker.ContainerStop(context.TODO(), runner.ContainerID, &(timeout))
219 runner.CrunchLog.Printf("StopContainer failed: %s", err)
221 // Suppress multiple calls to stop()
222 runner.cStarted = false
226 func (runner *ContainerRunner) stopSignals() {
227 if runner.SigChan != nil {
228 signal.Stop(runner.SigChan)
229 close(runner.SigChan)
233 // LoadImage determines the docker image id from the container record and
234 // checks if it is available in the local Docker image store. If not, it loads
235 // the image from Keep.
236 func (runner *ContainerRunner) LoadImage() (err error) {
238 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
240 var collection arvados.Collection
241 err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
243 return fmt.Errorf("While getting container image collection: %v", err)
245 manifest := manifest.Manifest{Text: collection.ManifestText}
246 var img, imageID string
247 for ms := range manifest.StreamIter() {
248 img = ms.FileStreamSegments[0].Name
249 if !strings.HasSuffix(img, ".tar") {
250 return fmt.Errorf("First file in the container image collection does not end in .tar")
252 imageID = img[:len(img)-4]
255 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
257 _, _, err = runner.Docker.ImageInspectWithRaw(context.TODO(), imageID)
259 runner.CrunchLog.Print("Loading Docker image from keep")
261 var readCloser io.ReadCloser
262 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
264 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
267 response, err := runner.Docker.ImageLoad(context.TODO(), readCloser, true)
269 return fmt.Errorf("While loading container image into Docker: %v", err)
272 defer response.Body.Close()
273 rbody, err := ioutil.ReadAll(response.Body)
275 return fmt.Errorf("Reading response to image load: %v", err)
277 runner.CrunchLog.Printf("Docker response: %s", rbody)
279 runner.CrunchLog.Print("Docker image is available")
282 runner.ContainerConfig.Image = imageID
284 runner.Kc.ClearBlockCache()
289 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
290 c = exec.Command("arv-mount", arvMountCmd...)
292 // Copy our environment, but override ARVADOS_API_TOKEN with
293 // the container auth token.
295 for _, s := range os.Environ() {
296 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
297 c.Env = append(c.Env, s)
300 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
302 runner.arvMountLog = NewThrottledLogger(runner.NewLogWriter("arv-mount"))
303 c.Stdout = runner.arvMountLog
304 c.Stderr = runner.arvMountLog
306 runner.CrunchLog.Printf("Running %v", c.Args)
313 statReadme := make(chan bool)
314 runner.ArvMountExit = make(chan error)
319 time.Sleep(100 * time.Millisecond)
320 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
332 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
334 runner.ArvMountExit <- mnterr
335 close(runner.ArvMountExit)
341 case err := <-runner.ArvMountExit:
342 runner.ArvMount = nil
350 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
351 if runner.ArvMountPoint == "" {
352 runner.ArvMountPoint, err = runner.MkTempDir("", prefix)
357 func (runner *ContainerRunner) SetupMounts() (err error) {
358 err = runner.SetupArvMountPoint("keep")
360 return fmt.Errorf("While creating keep mount temp dir: %v", err)
365 arvMountCmd := []string{
369 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
371 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
372 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
375 collectionPaths := []string{}
377 runner.Volumes = make(map[string]struct{})
378 needCertMount := true
381 for bind := range runner.Container.Mounts {
382 binds = append(binds, bind)
386 for _, bind := range binds {
387 mnt := runner.Container.Mounts[bind]
388 if bind == "stdout" || bind == "stderr" {
389 // Is it a "file" mount kind?
390 if mnt.Kind != "file" {
391 return fmt.Errorf("Unsupported mount kind '%s' for %s. Only 'file' is supported.", mnt.Kind, bind)
394 // Does path start with OutputPath?
395 prefix := runner.Container.OutputPath
396 if !strings.HasSuffix(prefix, "/") {
399 if !strings.HasPrefix(mnt.Path, prefix) {
400 return fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
405 // Is it a "collection" mount kind?
406 if mnt.Kind != "collection" && mnt.Kind != "json" {
407 return fmt.Errorf("Unsupported mount kind '%s' for stdin. Only 'collection' or 'json' are supported.", mnt.Kind)
411 if bind == "/etc/arvados/ca-certificates.crt" {
412 needCertMount = false
415 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
416 if mnt.Kind != "collection" {
417 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
422 case mnt.Kind == "collection" && bind != "stdin":
424 if mnt.UUID != "" && mnt.PortableDataHash != "" {
425 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
429 return fmt.Errorf("Writing to existing collections currently not permitted.")
432 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
433 } else if mnt.PortableDataHash != "" {
435 return fmt.Errorf("Can never write to a collection specified by portable data hash")
437 idx := strings.Index(mnt.PortableDataHash, "/")
439 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
440 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
441 runner.Container.Mounts[bind] = mnt
443 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
444 if mnt.Path != "" && mnt.Path != "." {
445 if strings.HasPrefix(mnt.Path, "./") {
446 mnt.Path = mnt.Path[2:]
447 } else if strings.HasPrefix(mnt.Path, "/") {
448 mnt.Path = mnt.Path[1:]
450 src += "/" + mnt.Path
453 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
454 arvMountCmd = append(arvMountCmd, "--mount-tmp")
455 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
459 if bind == runner.Container.OutputPath {
460 runner.HostOutputDir = src
461 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
462 return fmt.Errorf("Writable mount points are not permitted underneath the output_path: %v", bind)
464 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
466 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
468 collectionPaths = append(collectionPaths, src)
470 case mnt.Kind == "tmp":
472 tmpdir, err = runner.MkTempDir("", "")
474 return fmt.Errorf("While creating mount temp dir: %v", err)
476 st, staterr := os.Stat(tmpdir)
478 return fmt.Errorf("While Stat on temp dir: %v", staterr)
480 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
482 return fmt.Errorf("While Chmod temp dir: %v", err)
484 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
485 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", tmpdir, bind))
486 if bind == runner.Container.OutputPath {
487 runner.HostOutputDir = tmpdir
490 case mnt.Kind == "json":
491 jsondata, err := json.Marshal(mnt.Content)
493 return fmt.Errorf("encoding json data: %v", err)
495 // Create a tempdir with a single file
496 // (instead of just a tempfile): this way we
497 // can ensure the file is world-readable
498 // inside the container, without having to
499 // make it world-readable on the docker host.
500 tmpdir, err := runner.MkTempDir("", "")
502 return fmt.Errorf("creating temp dir: %v", err)
504 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
505 tmpfn := filepath.Join(tmpdir, "mountdata.json")
506 err = ioutil.WriteFile(tmpfn, jsondata, 0644)
508 return fmt.Errorf("writing temp file: %v", err)
510 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
514 if runner.HostOutputDir == "" {
515 return fmt.Errorf("Output path does not correspond to a writable mount point")
518 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
519 for _, certfile := range arvadosclient.CertFiles {
520 _, err := os.Stat(certfile)
522 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
529 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
531 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
533 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
535 token, err := runner.ContainerToken()
537 return fmt.Errorf("could not get container token: %s", err)
540 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
542 return fmt.Errorf("While trying to start arv-mount: %v", err)
545 for _, p := range collectionPaths {
548 return fmt.Errorf("While checking that input files exist: %v", err)
555 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
556 // Handle docker log protocol
557 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
559 header := make([]byte, 8)
561 _, readerr := io.ReadAtLeast(containerReader, header, 8)
564 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
567 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
570 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
575 if readerr != io.EOF {
576 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
579 closeerr := runner.Stdout.Close()
581 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
584 closeerr = runner.Stderr.Close()
586 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
589 if runner.statReporter != nil {
590 runner.statReporter.Stop()
591 closeerr = runner.statLogger.Close()
593 runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
597 runner.loggingDone <- true
598 close(runner.loggingDone)
604 func (runner *ContainerRunner) StartCrunchstat() {
605 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
606 runner.statReporter = &crunchstat.Reporter{
607 CID: runner.ContainerID,
608 Logger: log.New(runner.statLogger, "", 0),
609 CgroupParent: runner.expectCgroupParent,
610 CgroupRoot: runner.cgroupRoot,
611 PollPeriod: runner.statInterval,
613 runner.statReporter.Start()
616 type infoCommand struct {
621 // LogNodeInfo gathers node information and store it on the log for debugging
623 func (runner *ContainerRunner) LogNodeInfo() (err error) {
624 w := runner.NewLogWriter("node-info")
625 logger := log.New(w, "node-info", 0)
627 commands := []infoCommand{
629 label: "Host Information",
630 cmd: []string{"uname", "-a"},
633 label: "CPU Information",
634 cmd: []string{"cat", "/proc/cpuinfo"},
637 label: "Memory Information",
638 cmd: []string{"cat", "/proc/meminfo"},
642 cmd: []string{"df", "-m", "/", os.TempDir()},
645 label: "Disk INodes",
646 cmd: []string{"df", "-i", "/", os.TempDir()},
650 // Run commands with informational output to be logged.
652 for _, command := range commands {
653 out, err = exec.Command(command.cmd[0], command.cmd[1:]...).CombinedOutput()
655 return fmt.Errorf("While running command %q: %v",
658 logger.Println(command.label)
659 for _, line := range strings.Split(string(out), "\n") {
660 logger.Println(" ", line)
666 return fmt.Errorf("While closing node-info logs: %v", err)
671 // LogContainerRecord gets and saves the raw JSON container record from the API server
672 func (runner *ContainerRunner) LogContainerRecord() (err error) {
674 ArvClient: runner.ArvClient,
675 UUID: runner.Container.UUID,
676 loggingStream: "container",
677 writeCloser: runner.LogCollection.Open("container.json"),
680 // Get Container record JSON from the API Server
681 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
683 return fmt.Errorf("While retrieving container record from the API server: %v", err)
687 dec := json.NewDecoder(reader)
689 var cr map[string]interface{}
690 if err = dec.Decode(&cr); err != nil {
691 return fmt.Errorf("While decoding the container record JSON response: %v", err)
693 // Re-encode it using indentation to improve readability
694 enc := json.NewEncoder(w)
695 enc.SetIndent("", " ")
696 if err = enc.Encode(cr); err != nil {
697 return fmt.Errorf("While logging the JSON container record: %v", err)
701 return fmt.Errorf("While closing container.json log: %v", err)
706 // AttachStreams connects the docker container stdin, stdout and stderr logs
707 // to the Arvados logger which logs to Keep and the API server logs table.
708 func (runner *ContainerRunner) AttachStreams() (err error) {
710 runner.CrunchLog.Print("Attaching container streams")
712 // If stdin mount is provided, attach it to the docker container
713 var stdinRdr arvados.File
715 if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
716 if stdinMnt.Kind == "collection" {
717 var stdinColl arvados.Collection
718 collId := stdinMnt.UUID
720 collId = stdinMnt.PortableDataHash
722 err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
724 return fmt.Errorf("While getting stding collection: %v", err)
727 stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
728 if os.IsNotExist(err) {
729 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
730 } else if err != nil {
731 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
733 } else if stdinMnt.Kind == "json" {
734 stdinJson, err = json.Marshal(stdinMnt.Content)
736 return fmt.Errorf("While encoding stdin json data: %v", err)
741 stdinUsed := stdinRdr != nil || len(stdinJson) != 0
742 response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
743 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
745 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
748 runner.loggingDone = make(chan bool)
750 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
751 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
755 runner.Stdout = stdoutFile
757 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
760 if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
761 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
765 runner.Stderr = stderrFile
767 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
772 _, err := io.Copy(response.Conn, stdinRdr)
774 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
778 response.CloseWrite()
780 } else if len(stdinJson) != 0 {
782 _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
784 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
787 response.CloseWrite()
791 go runner.ProcessDockerAttach(response.Reader)
796 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
797 stdoutPath := mntPath[len(runner.Container.OutputPath):]
798 index := strings.LastIndex(stdoutPath, "/")
800 subdirs := stdoutPath[:index]
802 st, err := os.Stat(runner.HostOutputDir)
804 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
806 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
807 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
809 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
813 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
815 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
818 return stdoutFile, nil
821 // CreateContainer creates the docker container.
822 func (runner *ContainerRunner) CreateContainer() error {
823 runner.CrunchLog.Print("Creating Docker container")
825 runner.ContainerConfig.Cmd = runner.Container.Command
826 if runner.Container.Cwd != "." {
827 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
830 for k, v := range runner.Container.Environment {
831 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
834 runner.ContainerConfig.Volumes = runner.Volumes
836 runner.HostConfig = dockercontainer.HostConfig{
838 LogConfig: dockercontainer.LogConfig{
841 Resources: dockercontainer.Resources{
842 CgroupParent: runner.setCgroupParent,
846 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
847 tok, err := runner.ContainerToken()
851 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
852 "ARVADOS_API_TOKEN="+tok,
853 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
854 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
856 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
858 if runner.enableNetwork == "always" {
859 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
861 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
865 _, stdinUsed := runner.Container.Mounts["stdin"]
866 runner.ContainerConfig.OpenStdin = stdinUsed
867 runner.ContainerConfig.StdinOnce = stdinUsed
868 runner.ContainerConfig.AttachStdin = stdinUsed
869 runner.ContainerConfig.AttachStdout = true
870 runner.ContainerConfig.AttachStderr = true
872 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
874 return fmt.Errorf("While creating container: %v", err)
877 runner.ContainerID = createdBody.ID
879 return runner.AttachStreams()
882 // StartContainer starts the docker container created by CreateContainer.
883 func (runner *ContainerRunner) StartContainer() error {
884 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
885 runner.cStateLock.Lock()
886 defer runner.cStateLock.Unlock()
887 if runner.cCancelled {
890 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
891 dockertypes.ContainerStartOptions{})
894 if strings.Contains(err.Error(), "no such file or directory") {
895 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])
897 return fmt.Errorf("could not start container: %v%s", err, advice)
899 runner.cStarted = true
903 // WaitFinish waits for the container to terminate, capture the exit code, and
904 // close the stdout/stderr logging.
905 func (runner *ContainerRunner) WaitFinish() (err error) {
906 runner.CrunchLog.Print("Waiting for container to finish")
908 waitOk, waitErr := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID, "not-running")
911 <-runner.ArvMountExit
913 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
918 var waitBody dockercontainer.ContainerWaitOKBody
920 case waitBody = <-waitOk:
921 case err = <-waitErr:
924 // Container isn't running any more
925 runner.cStarted = false
928 return fmt.Errorf("container wait: %v", err)
931 runner.CrunchLog.Printf("Container exited with code: %v", waitBody.StatusCode)
932 code := int(waitBody.StatusCode)
933 runner.ExitCode = &code
935 // wait for stdout/stderr to complete
941 var ErrNotInOutputDir = fmt.Errorf("Must point to path within the output directory")
943 func (runner *ContainerRunner) derefOutputSymlink(path string, startinfo os.FileInfo) (tgt string, readlinktgt string, info os.FileInfo, err error) {
944 // Follow symlinks if necessary
949 for followed := 0; info.Mode()&os.ModeSymlink != 0; followed++ {
950 if followed >= limitFollowSymlinks {
951 // Got stuck in a loop or just a pathological number of links, give up.
952 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
956 readlinktgt, err = os.Readlink(nextlink)
962 if !strings.HasPrefix(tgt, "/") {
963 // Relative symlink, resolve it to host path
964 tgt = filepath.Join(filepath.Dir(path), tgt)
966 if strings.HasPrefix(tgt, runner.Container.OutputPath+"/") && !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
967 // Absolute symlink to container output path, adjust it to host output path.
968 tgt = filepath.Join(runner.HostOutputDir, tgt[len(runner.Container.OutputPath):])
970 if !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
971 // After dereferencing, symlink target must either be
972 // within output directory, or must point to a
974 err = ErrNotInOutputDir
978 info, err = os.Lstat(tgt)
981 err = fmt.Errorf("Symlink in output %q points to invalid location %q: %v",
982 path[len(runner.HostOutputDir):], readlinktgt, err)
992 var limitFollowSymlinks = 10
994 // UploadFile uploads files within the output directory, with special handling
995 // for symlinks. If the symlink leads to a keep mount, copy the manifest text
996 // from the keep mount into the output manifestText. Ensure that whether
997 // symlinks are relative or absolute, every symlink target (even targets that
998 // are symlinks themselves) must point to a path in either the output directory
999 // or a collection mount.
1001 // Assumes initial value of "path" is absolute, and located within runner.HostOutputDir.
1002 func (runner *ContainerRunner) UploadOutputFile(
1007 walkUpload *WalkUpload,
1008 relocateFrom string,
1010 followed int) (manifestText string, err error) {
1012 if info.Mode().IsDir() {
1020 if followed >= limitFollowSymlinks {
1021 // Got stuck in a loop or just a pathological number of
1022 // directory links, give up.
1023 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
1027 // When following symlinks, the source path may need to be logically
1028 // relocated to some other path within the output collection. Remove
1029 // the relocateFrom prefix and replace it with relocateTo.
1030 relocated := relocateTo + path[len(relocateFrom):]
1032 tgt, readlinktgt, info, derefErr := runner.derefOutputSymlink(path, info)
1033 if derefErr != nil && derefErr != ErrNotInOutputDir {
1037 // go through mounts and try reverse map to collection reference
1038 for _, bind := range binds {
1039 mnt := runner.Container.Mounts[bind]
1040 if tgt == bind || strings.HasPrefix(tgt, bind+"/") {
1041 // get path relative to bind
1042 targetSuffix := tgt[len(bind):]
1044 // Copy mount and adjust the path to add path relative to the bind
1045 adjustedMount := mnt
1046 adjustedMount.Path = filepath.Join(adjustedMount.Path, targetSuffix)
1048 // Terminates in this keep mount, so add the
1049 // manifest text at appropriate location.
1050 outputSuffix := path[len(runner.HostOutputDir):]
1051 manifestText, err = runner.getCollectionManifestForPath(adjustedMount, outputSuffix)
1056 // If target is not a collection mount, it must be located within the
1057 // output directory, otherwise it is an error.
1058 if derefErr == ErrNotInOutputDir {
1059 err = fmt.Errorf("Symlink in output %q points to invalid location %q, must point to path within the output directory.",
1060 path[len(runner.HostOutputDir):], readlinktgt)
1064 if info.Mode().IsRegular() {
1065 return "", walkUpload.UploadFile(relocated, tgt)
1068 if info.Mode().IsDir() {
1069 // Symlink leads to directory. Walk() doesn't follow
1070 // directory symlinks, so we walk the target directory
1071 // instead. Within the walk, file paths are relocated
1072 // so they appear under the original symlink path.
1073 err = filepath.Walk(tgt, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
1075 m, walkerr = runner.UploadOutputFile(walkpath, walkinfo, walkerr,
1076 binds, walkUpload, tgt, relocated, followed+1)
1078 manifestText = manifestText + m
1088 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
1089 func (runner *ContainerRunner) CaptureOutput() error {
1090 if runner.finalState != "Complete" {
1094 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
1095 // Output may have been set directly by the container, so
1096 // refresh the container record to check.
1097 err := runner.ArvClient.Get("containers", runner.Container.UUID,
1098 nil, &runner.Container)
1102 if runner.Container.Output != "" {
1103 // Container output is already set.
1104 runner.OutputPDH = &runner.Container.Output
1109 if runner.HostOutputDir == "" {
1113 _, err := os.Stat(runner.HostOutputDir)
1115 return fmt.Errorf("While checking host output path: %v", err)
1118 // Pre-populate output from the configured mount points
1120 for bind, mnt := range runner.Container.Mounts {
1121 if mnt.Kind == "collection" {
1122 binds = append(binds, bind)
1127 var manifestText string
1129 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
1130 _, err = os.Stat(collectionMetafile)
1132 // Regular directory
1134 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
1135 walkUpload := cw.BeginUpload(runner.HostOutputDir, runner.CrunchLog.Logger)
1138 err = filepath.Walk(runner.HostOutputDir, func(path string, info os.FileInfo, err error) error {
1139 m, err = runner.UploadOutputFile(path, info, err, binds, walkUpload, "", "", 0)
1141 manifestText = manifestText + m
1146 cw.EndUpload(walkUpload)
1149 return fmt.Errorf("While uploading output files: %v", err)
1152 m, err = cw.ManifestText()
1153 manifestText = manifestText + m
1155 return fmt.Errorf("While uploading output files: %v", err)
1158 // FUSE mount directory
1159 file, openerr := os.Open(collectionMetafile)
1161 return fmt.Errorf("While opening FUSE metafile: %v", err)
1165 var rec arvados.Collection
1166 err = json.NewDecoder(file).Decode(&rec)
1168 return fmt.Errorf("While reading FUSE metafile: %v", err)
1170 manifestText = rec.ManifestText
1173 for _, bind := range binds {
1174 mnt := runner.Container.Mounts[bind]
1176 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
1178 if bindSuffix == bind || len(bindSuffix) <= 0 {
1179 // either does not start with OutputPath or is OutputPath itself
1183 if mnt.ExcludeFromOutput == true {
1187 // append to manifest_text
1188 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
1193 manifestText = manifestText + m
1197 var response arvados.Collection
1198 manifest := manifest.Manifest{Text: manifestText}
1199 manifestText = manifest.Extract(".", ".").Text
1200 err = runner.ArvClient.Create("collections",
1202 "ensure_unique_name": true,
1203 "collection": arvadosclient.Dict{
1205 "name": "output for " + runner.Container.UUID,
1206 "manifest_text": manifestText}},
1209 return fmt.Errorf("While creating output collection: %v", err)
1211 runner.OutputPDH = &response.PortableDataHash
1215 var outputCollections = make(map[string]arvados.Collection)
1217 // Fetch the collection for the mnt.PortableDataHash
1218 // Return the manifest_text fragment corresponding to the specified mnt.Path
1219 // after making any required updates.
1221 // If mnt.Path is not specified,
1222 // return the entire manifest_text after replacing any "." with bindSuffix
1223 // If mnt.Path corresponds to one stream,
1224 // return the manifest_text for that stream after replacing that stream name with bindSuffix
1225 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1226 // for that stream after replacing stream name with bindSuffix minus the last word
1227 // and the file name with last word of the bindSuffix
1228 // Allowed path examples:
1230 // "path":"/subdir1"
1231 // "path":"/subdir1/subdir2"
1232 // "path":"/subdir/filename" etc
1233 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1234 collection := outputCollections[mnt.PortableDataHash]
1235 if collection.PortableDataHash == "" {
1236 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1238 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1240 outputCollections[mnt.PortableDataHash] = collection
1243 if collection.ManifestText == "" {
1244 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1248 mft := manifest.Manifest{Text: collection.ManifestText}
1249 extracted := mft.Extract(mnt.Path, bindSuffix)
1250 if extracted.Err != nil {
1251 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1253 return extracted.Text, nil
1256 func (runner *ContainerRunner) CleanupDirs() {
1257 if runner.ArvMount != nil {
1259 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1260 umount.Stdout = runner.CrunchLog
1261 umount.Stderr = runner.CrunchLog
1262 runner.CrunchLog.Printf("Running %v", umount.Args)
1263 umnterr := umount.Start()
1266 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1268 // If arv-mount --unmount gets stuck for any reason, we
1269 // don't want to wait for it forever. Do Wait() in a goroutine
1270 // so it doesn't block crunch-run.
1271 umountExit := make(chan error)
1273 mnterr := umount.Wait()
1275 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1277 umountExit <- mnterr
1280 for again := true; again; {
1286 case <-runner.ArvMountExit:
1288 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1289 runner.CrunchLog.Printf("Timed out waiting for unmount")
1291 umount.Process.Kill()
1293 runner.ArvMount.Process.Kill()
1299 if runner.ArvMountPoint != "" {
1300 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1301 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1305 for _, tmpdir := range runner.CleanupTempDir {
1306 if rmerr := os.RemoveAll(tmpdir); rmerr != nil {
1307 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1312 // CommitLogs posts the collection containing the final container logs.
1313 func (runner *ContainerRunner) CommitLogs() error {
1314 runner.CrunchLog.Print(runner.finalState)
1316 if runner.arvMountLog != nil {
1317 runner.arvMountLog.Close()
1319 runner.CrunchLog.Close()
1321 // Closing CrunchLog above allows them to be committed to Keep at this
1322 // point, but re-open crunch log with ArvClient in case there are any
1323 // other further errors (such as failing to write the log to Keep!)
1324 // while shutting down
1325 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1326 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1327 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1329 if runner.LogsPDH != nil {
1330 // If we have already assigned something to LogsPDH,
1331 // we must be closing the re-opened log, which won't
1332 // end up getting attached to the container record and
1333 // therefore doesn't need to be saved as a collection
1334 // -- it exists only to send logs to other channels.
1338 mt, err := runner.LogCollection.ManifestText()
1340 return fmt.Errorf("While creating log manifest: %v", err)
1343 var response arvados.Collection
1344 err = runner.ArvClient.Create("collections",
1346 "ensure_unique_name": true,
1347 "collection": arvadosclient.Dict{
1349 "name": "logs for " + runner.Container.UUID,
1350 "manifest_text": mt}},
1353 return fmt.Errorf("While creating log collection: %v", err)
1355 runner.LogsPDH = &response.PortableDataHash
1359 // UpdateContainerRunning updates the container state to "Running"
1360 func (runner *ContainerRunner) UpdateContainerRunning() error {
1361 runner.cStateLock.Lock()
1362 defer runner.cStateLock.Unlock()
1363 if runner.cCancelled {
1366 return runner.ArvClient.Update("containers", runner.Container.UUID,
1367 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1370 // ContainerToken returns the api_token the container (and any
1371 // arv-mount processes) are allowed to use.
1372 func (runner *ContainerRunner) ContainerToken() (string, error) {
1373 if runner.token != "" {
1374 return runner.token, nil
1377 var auth arvados.APIClientAuthorization
1378 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1382 runner.token = auth.APIToken
1383 return runner.token, nil
1386 // UpdateContainerComplete updates the container record state on API
1387 // server to "Complete" or "Cancelled"
1388 func (runner *ContainerRunner) UpdateContainerFinal() error {
1389 update := arvadosclient.Dict{}
1390 update["state"] = runner.finalState
1391 if runner.LogsPDH != nil {
1392 update["log"] = *runner.LogsPDH
1394 if runner.finalState == "Complete" {
1395 if runner.ExitCode != nil {
1396 update["exit_code"] = *runner.ExitCode
1398 if runner.OutputPDH != nil {
1399 update["output"] = *runner.OutputPDH
1402 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1405 // IsCancelled returns the value of Cancelled, with goroutine safety.
1406 func (runner *ContainerRunner) IsCancelled() bool {
1407 runner.cStateLock.Lock()
1408 defer runner.cStateLock.Unlock()
1409 return runner.cCancelled
1412 // NewArvLogWriter creates an ArvLogWriter
1413 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1414 return &ArvLogWriter{
1415 ArvClient: runner.ArvClient,
1416 UUID: runner.Container.UUID,
1417 loggingStream: name,
1418 writeCloser: runner.LogCollection.Open(name + ".txt")}
1421 // Run the full container lifecycle.
1422 func (runner *ContainerRunner) Run() (err error) {
1423 runner.CrunchLog.Printf("crunch-run %q started", version)
1424 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1426 hostname, hosterr := os.Hostname()
1428 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1430 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1433 runner.finalState = "Queued"
1436 runner.stopSignals()
1437 runner.CleanupDirs()
1439 runner.CrunchLog.Printf("crunch-run finished")
1440 runner.CrunchLog.Close()
1444 // checkErr prints e (unless it's nil) and sets err to
1445 // e (unless err is already non-nil). Thus, if err
1446 // hasn't already been assigned when Run() returns,
1447 // this cleanup func will cause Run() to return the
1448 // first non-nil error that is passed to checkErr().
1449 checkErr := func(e error) {
1453 runner.CrunchLog.Print(e)
1457 if runner.finalState == "Complete" {
1458 // There was an error in the finalization.
1459 runner.finalState = "Cancelled"
1463 // Log the error encountered in Run(), if any
1466 if runner.finalState == "Queued" {
1467 runner.UpdateContainerFinal()
1471 if runner.IsCancelled() {
1472 runner.finalState = "Cancelled"
1473 // but don't return yet -- we still want to
1474 // capture partial output and write logs
1477 checkErr(runner.CaptureOutput())
1478 checkErr(runner.CommitLogs())
1479 checkErr(runner.UpdateContainerFinal())
1482 err = runner.fetchContainerRecord()
1487 // setup signal handling
1488 runner.setupSignals()
1490 // check for and/or load image
1491 err = runner.LoadImage()
1493 runner.finalState = "Cancelled"
1494 err = fmt.Errorf("While loading container image: %v", err)
1498 // set up FUSE mount and binds
1499 err = runner.SetupMounts()
1501 runner.finalState = "Cancelled"
1502 err = fmt.Errorf("While setting up mounts: %v", err)
1506 err = runner.CreateContainer()
1511 // Gather and record node information
1512 err = runner.LogNodeInfo()
1516 // Save container.json record on log collection
1517 err = runner.LogContainerRecord()
1522 runner.StartCrunchstat()
1524 if runner.IsCancelled() {
1528 err = runner.UpdateContainerRunning()
1532 runner.finalState = "Cancelled"
1534 err = runner.StartContainer()
1539 err = runner.WaitFinish()
1541 runner.finalState = "Complete"
1546 // Fetch the current container record (uuid = runner.Container.UUID)
1547 // into runner.Container.
1548 func (runner *ContainerRunner) fetchContainerRecord() error {
1549 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1551 return fmt.Errorf("error fetching container record: %v", err)
1553 defer reader.Close()
1555 dec := json.NewDecoder(reader)
1557 err = dec.Decode(&runner.Container)
1559 return fmt.Errorf("error decoding container record: %v", err)
1564 // NewContainerRunner creates a new container runner.
1565 func NewContainerRunner(api IArvadosClient,
1567 docker ThinDockerClient,
1568 containerUUID string) *ContainerRunner {
1570 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1571 cr.NewLogWriter = cr.NewArvLogWriter
1572 cr.RunArvMount = cr.ArvMountCmd
1573 cr.MkTempDir = ioutil.TempDir
1574 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1575 cr.Container.UUID = containerUUID
1576 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1577 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1579 loadLogThrottleParams(api)
1585 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1586 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1587 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1588 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1589 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1590 enableNetwork := flag.String("container-enable-networking", "default",
1591 `Specify if networking should be enabled for container. One of 'default', 'always':
1592 default: only enable networking if container requests it.
1593 always: containers always have networking enabled
1595 networkMode := flag.String("container-network-mode", "default",
1596 `Set networking mode for container. Corresponds to Docker network mode (--net).
1598 memprofile := flag.String("memprofile", "", "write memory profile to `file` after running container")
1599 getVersion := flag.Bool("version", false, "Print version information and exit.")
1602 // Print version information if requested
1604 fmt.Printf("Version: %s\n", version)
1608 log.Printf("crunch-run %q started", version)
1610 containerId := flag.Arg(0)
1612 if *caCertsPath != "" {
1613 arvadosclient.CertFiles = []string{*caCertsPath}
1616 api, err := arvadosclient.MakeArvadosClient()
1618 log.Fatalf("%s: %v", containerId, err)
1622 var kc *keepclient.KeepClient
1623 kc, err = keepclient.MakeKeepClient(api)
1625 log.Fatalf("%s: %v", containerId, err)
1627 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1630 var docker *dockerclient.Client
1631 // API version 1.21 corresponds to Docker 1.9, which is currently the
1632 // minimum version we want to support.
1633 docker, err = dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1635 log.Fatalf("%s: %v", containerId, err)
1638 dockerClientProxy := ThinDockerClientProxy{Docker: docker}
1640 cr := NewContainerRunner(api, kc, dockerClientProxy, containerId)
1641 cr.statInterval = *statInterval
1642 cr.cgroupRoot = *cgroupRoot
1643 cr.expectCgroupParent = *cgroupParent
1644 cr.enableNetwork = *enableNetwork
1645 cr.networkMode = *networkMode
1646 if *cgroupParentSubsystem != "" {
1647 p := findCgroup(*cgroupParentSubsystem)
1648 cr.setCgroupParent = p
1649 cr.expectCgroupParent = p
1654 if *memprofile != "" {
1655 f, err := os.Create(*memprofile)
1657 log.Printf("could not create memory profile: ", err)
1659 runtime.GC() // get up-to-date statistics
1660 if err := pprof.WriteHeapProfile(f); err != nil {
1661 log.Printf("could not write memory profile: ", err)
1663 closeerr := f.Close()
1664 if closeerr != nil {
1665 log.Printf("closing memprofile file: ", err)
1670 log.Fatalf("%s: %v", containerId, runerr)