8 "git.curoverse.com/arvados.git/lib/crunchstat"
9 "git.curoverse.com/arvados.git/sdk/go/arvados"
10 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
11 "git.curoverse.com/arvados.git/sdk/go/keepclient"
12 "git.curoverse.com/arvados.git/sdk/go/manifest"
13 "github.com/curoverse/dockerclient"
28 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
29 type IArvadosClient interface {
30 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
31 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
32 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error)
33 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) (err error)
36 // ErrCancelled is the error returned when the container is cancelled.
37 var ErrCancelled = errors.New("Cancelled")
39 // IKeepClient is the minimal Keep API methods used by crunch-run.
40 type IKeepClient interface {
41 PutHB(hash string, buf []byte) (string, int, error)
42 ManifestFileReader(m manifest.Manifest, filename string) (keepclient.ReadCloserWithLen, error)
45 // NewLogWriter is a factory function to create a new log writer.
46 type NewLogWriter func(name string) io.WriteCloser
48 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
50 type MkTempDir func(string, string) (string, error)
52 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
53 type ThinDockerClient interface {
54 StopContainer(id string, timeout int) error
55 InspectImage(id string) (*dockerclient.ImageInfo, error)
56 LoadImage(reader io.Reader) error
57 CreateContainer(config *dockerclient.ContainerConfig, name string, authConfig *dockerclient.AuthConfig) (string, error)
58 StartContainer(id string, config *dockerclient.HostConfig) error
59 AttachContainer(id string, options *dockerclient.AttachOptions) (io.ReadCloser, error)
60 Wait(id string) <-chan dockerclient.WaitResult
61 RemoveImage(name string, force bool) ([]*dockerclient.ImageDelete, error)
64 // ContainerRunner is the main stateful struct used for a single execution of a
66 type ContainerRunner struct {
67 Docker ThinDockerClient
68 ArvClient IArvadosClient
71 dockerclient.ContainerConfig
72 dockerclient.HostConfig
78 CrunchLog *ThrottledLogger
80 Stderr *ThrottledLogger
81 LogCollection *CollectionWriter
88 CleanupTempDir []string
93 SigChan chan os.Signal
94 ArvMountExit chan error
97 statLogger io.WriteCloser
98 statReporter *crunchstat.Reporter
99 statInterval time.Duration
101 // What we expect the container's cgroup parent to be.
102 expectCgroupParent string
103 // What we tell docker to use as the container's cgroup
104 // parent. Note: Ideally we would use the same field for both
105 // expectCgroupParent and setCgroupParent, and just make it
106 // default to "docker". However, when using docker < 1.10 with
107 // systemd, specifying a non-empty cgroup parent (even the
108 // default value "docker") hits a docker bug
109 // (https://github.com/docker/docker/issues/17126). Using two
110 // separate fields makes it possible to use the "expect cgroup
111 // parent to be X" feature even on sites where the "specify
112 // cgroup parent" feature breaks.
113 setCgroupParent string
116 // SetupSignals sets up signal handling to gracefully terminate the underlying
117 // Docker container and update state when receiving a TERM, INT or QUIT signal.
118 func (runner *ContainerRunner) SetupSignals() {
119 runner.SigChan = make(chan os.Signal, 1)
120 signal.Notify(runner.SigChan, syscall.SIGTERM)
121 signal.Notify(runner.SigChan, syscall.SIGINT)
122 signal.Notify(runner.SigChan, syscall.SIGQUIT)
124 go func(sig <-chan os.Signal) {
126 if !runner.Cancelled {
127 runner.CancelLock.Lock()
128 runner.Cancelled = true
129 if runner.ContainerID != "" {
130 runner.Docker.StopContainer(runner.ContainerID, 10)
132 runner.CancelLock.Unlock()
138 // LoadImage determines the docker image id from the container record and
139 // checks if it is available in the local Docker image store. If not, it loads
140 // the image from Keep.
141 func (runner *ContainerRunner) LoadImage() (err error) {
143 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
145 var collection arvados.Collection
146 err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
148 return fmt.Errorf("While getting container image collection: %v", err)
150 manifest := manifest.Manifest{Text: collection.ManifestText}
151 var img, imageID string
152 for ms := range manifest.StreamIter() {
153 img = ms.FileStreamSegments[0].Name
154 if !strings.HasSuffix(img, ".tar") {
155 return fmt.Errorf("First file in the container image collection does not end in .tar")
157 imageID = img[:len(img)-4]
160 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
162 _, err = runner.Docker.InspectImage(imageID)
164 runner.CrunchLog.Print("Loading Docker image from keep")
166 var readCloser io.ReadCloser
167 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
169 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
172 err = runner.Docker.LoadImage(readCloser)
174 return fmt.Errorf("While loading container image into Docker: %v", err)
177 runner.CrunchLog.Print("Docker image is available")
180 runner.ContainerConfig.Image = imageID
185 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
186 c = exec.Command("arv-mount", arvMountCmd...)
188 // Copy our environment, but override ARVADOS_API_TOKEN with
189 // the container auth token.
191 for _, s := range os.Environ() {
192 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
193 c.Env = append(c.Env, s)
196 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
198 nt := NewThrottledLogger(runner.NewLogWriter("arv-mount"))
207 statReadme := make(chan bool)
208 runner.ArvMountExit = make(chan error)
213 time.Sleep(100 * time.Millisecond)
214 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
224 runner.ArvMountExit <- c.Wait()
225 close(runner.ArvMountExit)
231 case err := <-runner.ArvMountExit:
232 runner.ArvMount = nil
240 func (runner *ContainerRunner) SetupMounts() (err error) {
241 runner.ArvMountPoint, err = runner.MkTempDir("", "keep")
243 return fmt.Errorf("While creating keep mount temp dir: %v", err)
246 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.ArvMountPoint)
250 arvMountCmd := []string{"--foreground", "--allow-other", "--read-write"}
251 collectionPaths := []string{}
254 for bind, mnt := range runner.Container.Mounts {
255 if bind == "stdout" {
256 // Is it a "file" mount kind?
257 if mnt.Kind != "file" {
258 return fmt.Errorf("Unsupported mount kind '%s' for stdout. Only 'file' is supported.", mnt.Kind)
261 // Does path start with OutputPath?
262 prefix := runner.Container.OutputPath
263 if !strings.HasSuffix(prefix, "/") {
266 if !strings.HasPrefix(mnt.Path, prefix) {
267 return fmt.Errorf("Stdout path does not start with OutputPath: %s, %s", mnt.Path, prefix)
272 case mnt.Kind == "collection":
274 if mnt.UUID != "" && mnt.PortableDataHash != "" {
275 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
279 return fmt.Errorf("Writing to existing collections currently not permitted.")
282 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
283 } else if mnt.PortableDataHash != "" {
285 return fmt.Errorf("Can never write to a collection specified by portable data hash")
287 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
289 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
290 arvMountCmd = append(arvMountCmd, "--mount-tmp")
291 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
295 if bind == runner.Container.OutputPath {
296 runner.HostOutputDir = src
298 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
300 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
302 collectionPaths = append(collectionPaths, src)
304 case mnt.Kind == "tmp" && bind == runner.Container.OutputPath:
305 runner.HostOutputDir, err = runner.MkTempDir("", "")
307 return fmt.Errorf("While creating mount temp dir: %v", err)
309 st, staterr := os.Stat(runner.HostOutputDir)
311 return fmt.Errorf("While Stat on temp dir: %v", staterr)
313 err = os.Chmod(runner.HostOutputDir, st.Mode()|os.ModeSetgid|0777)
315 return fmt.Errorf("While Chmod temp dir: %v", err)
317 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.HostOutputDir)
318 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", runner.HostOutputDir, bind))
320 case mnt.Kind == "tmp":
321 runner.Binds = append(runner.Binds, bind)
323 case mnt.Kind == "json":
324 jsondata, err := json.Marshal(mnt.Content)
326 return fmt.Errorf("encoding json data: %v", err)
328 // Create a tempdir with a single file
329 // (instead of just a tempfile): this way we
330 // can ensure the file is world-readable
331 // inside the container, without having to
332 // make it world-readable on the docker host.
333 tmpdir, err := runner.MkTempDir("", "")
335 return fmt.Errorf("creating temp dir: %v", err)
337 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
338 tmpfn := filepath.Join(tmpdir, "mountdata.json")
339 err = ioutil.WriteFile(tmpfn, jsondata, 0644)
341 return fmt.Errorf("writing temp file: %v", err)
343 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
347 if runner.HostOutputDir == "" {
348 return fmt.Errorf("Output path does not correspond to a writable mount point")
352 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
354 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
356 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
358 token, err := runner.ContainerToken()
360 return fmt.Errorf("could not get container token: %s", err)
363 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
365 return fmt.Errorf("While trying to start arv-mount: %v", err)
368 for _, p := range collectionPaths {
371 return fmt.Errorf("While checking that input files exist: %v", err)
378 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
379 // Handle docker log protocol
380 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
382 header := make([]byte, 8)
384 _, readerr := io.ReadAtLeast(containerReader, header, 8)
387 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
390 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
393 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
398 if readerr != io.EOF {
399 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
402 closeerr := runner.Stdout.Close()
404 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
407 closeerr = runner.Stderr.Close()
409 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
412 if runner.statReporter != nil {
413 runner.statReporter.Stop()
414 closeerr = runner.statLogger.Close()
416 runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
420 runner.loggingDone <- true
421 close(runner.loggingDone)
427 func (runner *ContainerRunner) StartCrunchstat() {
428 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
429 runner.statReporter = &crunchstat.Reporter{
430 CID: runner.ContainerID,
431 Logger: log.New(runner.statLogger, "", 0),
432 CgroupParent: runner.expectCgroupParent,
433 CgroupRoot: runner.cgroupRoot,
434 PollPeriod: runner.statInterval,
436 runner.statReporter.Start()
439 // AttachLogs connects the docker container stdout and stderr logs to the
440 // Arvados logger which logs to Keep and the API server logs table.
441 func (runner *ContainerRunner) AttachStreams() (err error) {
443 runner.CrunchLog.Print("Attaching container streams")
445 var containerReader io.Reader
446 containerReader, err = runner.Docker.AttachContainer(runner.ContainerID,
447 &dockerclient.AttachOptions{Stream: true, Stdout: true, Stderr: true})
449 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
452 runner.loggingDone = make(chan bool)
454 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
455 stdoutPath := stdoutMnt.Path[len(runner.Container.OutputPath):]
456 index := strings.LastIndex(stdoutPath, "/")
458 subdirs := stdoutPath[:index]
460 st, err := os.Stat(runner.HostOutputDir)
462 return fmt.Errorf("While Stat on temp dir: %v", err)
464 stdoutPath := path.Join(runner.HostOutputDir, subdirs)
465 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
467 return fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
471 stdoutFile, err := os.Create(path.Join(runner.HostOutputDir, stdoutPath))
473 return fmt.Errorf("While creating stdout file: %v", err)
475 runner.Stdout = stdoutFile
477 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
479 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
481 go runner.ProcessDockerAttach(containerReader)
486 // CreateContainer creates the docker container.
487 func (runner *ContainerRunner) CreateContainer() error {
488 runner.CrunchLog.Print("Creating Docker container")
490 runner.ContainerConfig.Cmd = runner.Container.Command
491 if runner.Container.Cwd != "." {
492 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
495 for k, v := range runner.Container.Environment {
496 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
498 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
499 tok, err := runner.ContainerToken()
503 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
504 "ARVADOS_API_TOKEN="+tok,
505 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
506 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
508 runner.ContainerConfig.NetworkDisabled = false
510 runner.ContainerConfig.NetworkDisabled = true
514 runner.ContainerID, err = runner.Docker.CreateContainer(&runner.ContainerConfig, "", nil)
516 return fmt.Errorf("While creating container: %v", err)
519 runner.HostConfig = dockerclient.HostConfig{
521 CgroupParent: runner.setCgroupParent,
522 LogConfig: dockerclient.LogConfig{
527 return runner.AttachStreams()
530 // StartContainer starts the docker container created by CreateContainer.
531 func (runner *ContainerRunner) StartContainer() error {
532 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
533 err := runner.Docker.StartContainer(runner.ContainerID, &runner.HostConfig)
535 return fmt.Errorf("could not start container: %v", err)
540 // WaitFinish waits for the container to terminate, capture the exit code, and
541 // close the stdout/stderr logging.
542 func (runner *ContainerRunner) WaitFinish() error {
543 runner.CrunchLog.Print("Waiting for container to finish")
545 result := runner.Docker.Wait(runner.ContainerID)
548 return fmt.Errorf("While waiting for container to finish: %v", wr.Error)
550 runner.ExitCode = &wr.ExitCode
552 // wait for stdout/stderr to complete
558 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
559 func (runner *ContainerRunner) CaptureOutput() error {
560 if runner.finalState != "Complete" {
564 if runner.HostOutputDir == "" {
568 _, err := os.Stat(runner.HostOutputDir)
570 return fmt.Errorf("While checking host output path: %v", err)
573 var manifestText string
575 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
576 _, err = os.Stat(collectionMetafile)
579 cw := CollectionWriter{runner.Kc, nil, sync.Mutex{}}
580 manifestText, err = cw.WriteTree(runner.HostOutputDir, runner.CrunchLog.Logger)
582 return fmt.Errorf("While uploading output files: %v", err)
585 // FUSE mount directory
586 file, openerr := os.Open(collectionMetafile)
588 return fmt.Errorf("While opening FUSE metafile: %v", err)
592 var rec arvados.Collection
593 err = json.NewDecoder(file).Decode(&rec)
595 return fmt.Errorf("While reading FUSE metafile: %v", err)
597 manifestText = rec.ManifestText
600 var response arvados.Collection
601 err = runner.ArvClient.Create("collections",
603 "collection": arvadosclient.Dict{
604 "manifest_text": manifestText}},
607 return fmt.Errorf("While creating output collection: %v", err)
610 runner.OutputPDH = new(string)
611 *runner.OutputPDH = response.PortableDataHash
616 func (runner *ContainerRunner) CleanupDirs() {
617 if runner.ArvMount != nil {
618 umount := exec.Command("fusermount", "-z", "-u", runner.ArvMountPoint)
619 umnterr := umount.Run()
621 runner.CrunchLog.Printf("While running fusermount: %v", umnterr)
624 mnterr := <-runner.ArvMountExit
626 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
630 for _, tmpdir := range runner.CleanupTempDir {
631 rmerr := os.RemoveAll(tmpdir)
633 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
638 // CommitLogs posts the collection containing the final container logs.
639 func (runner *ContainerRunner) CommitLogs() error {
640 runner.CrunchLog.Print(runner.finalState)
641 runner.CrunchLog.Close()
643 // Closing CrunchLog above allows it to be committed to Keep at this
644 // point, but re-open crunch log with ArvClient in case there are any
645 // other further (such as failing to write the log to Keep!) while
647 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{runner.ArvClient, runner.Container.UUID,
650 if runner.LogsPDH != nil {
651 // If we have already assigned something to LogsPDH,
652 // we must be closing the re-opened log, which won't
653 // end up getting attached to the container record and
654 // therefore doesn't need to be saved as a collection
655 // -- it exists only to send logs to other channels.
659 mt, err := runner.LogCollection.ManifestText()
661 return fmt.Errorf("While creating log manifest: %v", err)
664 var response arvados.Collection
665 err = runner.ArvClient.Create("collections",
667 "collection": arvadosclient.Dict{
668 "name": "logs for " + runner.Container.UUID,
669 "manifest_text": mt}},
672 return fmt.Errorf("While creating log collection: %v", err)
675 runner.LogsPDH = &response.PortableDataHash
680 // UpdateContainerRunning updates the container state to "Running"
681 func (runner *ContainerRunner) UpdateContainerRunning() error {
682 runner.CancelLock.Lock()
683 defer runner.CancelLock.Unlock()
684 if runner.Cancelled {
687 return runner.ArvClient.Update("containers", runner.Container.UUID,
688 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
691 // ContainerToken returns the api_token the container (and any
692 // arv-mount processes) are allowed to use.
693 func (runner *ContainerRunner) ContainerToken() (string, error) {
694 if runner.token != "" {
695 return runner.token, nil
698 var auth arvados.APIClientAuthorization
699 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
703 runner.token = auth.APIToken
704 return runner.token, nil
707 // UpdateContainerComplete updates the container record state on API
708 // server to "Complete" or "Cancelled"
709 func (runner *ContainerRunner) UpdateContainerFinal() error {
710 update := arvadosclient.Dict{}
711 update["state"] = runner.finalState
712 if runner.finalState == "Complete" {
713 if runner.LogsPDH != nil {
714 update["log"] = *runner.LogsPDH
716 if runner.ExitCode != nil {
717 update["exit_code"] = *runner.ExitCode
719 if runner.OutputPDH != nil {
720 update["output"] = *runner.OutputPDH
723 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
726 // IsCancelled returns the value of Cancelled, with goroutine safety.
727 func (runner *ContainerRunner) IsCancelled() bool {
728 runner.CancelLock.Lock()
729 defer runner.CancelLock.Unlock()
730 return runner.Cancelled
733 // NewArvLogWriter creates an ArvLogWriter
734 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
735 return &ArvLogWriter{runner.ArvClient, runner.Container.UUID, name, runner.LogCollection.Open(name + ".txt")}
738 // Run the full container lifecycle.
739 func (runner *ContainerRunner) Run() (err error) {
740 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
742 hostname, hosterr := os.Hostname()
744 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
746 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
749 // Clean up temporary directories _after_ finalizing
750 // everything (if we've made any by then)
751 defer runner.CleanupDirs()
753 runner.finalState = "Queued"
756 // checkErr prints e (unless it's nil) and sets err to
757 // e (unless err is already non-nil). Thus, if err
758 // hasn't already been assigned when Run() returns,
759 // this cleanup func will cause Run() to return the
760 // first non-nil error that is passed to checkErr().
761 checkErr := func(e error) {
765 runner.CrunchLog.Print(e)
771 // Log the error encountered in Run(), if any
774 if runner.finalState == "Queued" {
775 runner.UpdateContainerFinal()
779 if runner.IsCancelled() {
780 runner.finalState = "Cancelled"
781 // but don't return yet -- we still want to
782 // capture partial output and write logs
785 checkErr(runner.CaptureOutput())
786 checkErr(runner.CommitLogs())
787 checkErr(runner.UpdateContainerFinal())
789 // The real log is already closed, but then we opened
790 // a new one in case we needed to log anything while
792 runner.CrunchLog.Close()
795 err = runner.ArvClient.Get("containers", runner.Container.UUID, nil, &runner.Container)
797 err = fmt.Errorf("While getting container record: %v", err)
801 // setup signal handling
802 runner.SetupSignals()
804 // check for and/or load image
805 err = runner.LoadImage()
807 err = fmt.Errorf("While loading container image: %v", err)
811 // set up FUSE mount and binds
812 err = runner.SetupMounts()
814 err = fmt.Errorf("While setting up mounts: %v", err)
818 err = runner.CreateContainer()
823 runner.StartCrunchstat()
825 if runner.IsCancelled() {
829 err = runner.UpdateContainerRunning()
833 runner.finalState = "Cancelled"
835 err = runner.StartContainer()
840 err = runner.WaitFinish()
842 runner.finalState = "Complete"
847 // NewContainerRunner creates a new container runner.
848 func NewContainerRunner(api IArvadosClient,
850 docker ThinDockerClient,
851 containerUUID string) *ContainerRunner {
853 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
854 cr.NewLogWriter = cr.NewArvLogWriter
855 cr.RunArvMount = cr.ArvMountCmd
856 cr.MkTempDir = ioutil.TempDir
857 cr.LogCollection = &CollectionWriter{kc, nil, sync.Mutex{}}
858 cr.Container.UUID = containerUUID
859 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
860 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
865 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
866 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
867 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
868 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
871 containerId := flag.Arg(0)
873 api, err := arvadosclient.MakeArvadosClient()
875 log.Fatalf("%s: %v", containerId, err)
879 var kc *keepclient.KeepClient
880 kc, err = keepclient.MakeKeepClient(&api)
882 log.Fatalf("%s: %v", containerId, err)
886 var docker *dockerclient.DockerClient
887 docker, err = dockerclient.NewDockerClient("unix:///var/run/docker.sock", nil)
889 log.Fatalf("%s: %v", containerId, err)
892 cr := NewContainerRunner(api, kc, docker, containerId)
893 cr.statInterval = *statInterval
894 cr.cgroupRoot = *cgroupRoot
895 cr.expectCgroupParent = *cgroupParent
896 if *cgroupParentSubsystem != "" {
897 p := findCgroup(*cgroupParentSubsystem)
898 cr.setCgroupParent = p
899 cr.expectCgroupParent = p
904 log.Fatalf("%s: %v", containerId, err)