1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
30 "git.curoverse.com/arvados.git/lib/crunchstat"
31 "git.curoverse.com/arvados.git/sdk/go/arvados"
32 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
33 "git.curoverse.com/arvados.git/sdk/go/keepclient"
34 "git.curoverse.com/arvados.git/sdk/go/manifest"
36 dockertypes "github.com/docker/docker/api/types"
37 dockercontainer "github.com/docker/docker/api/types/container"
38 dockernetwork "github.com/docker/docker/api/types/network"
39 dockerclient "github.com/docker/docker/client"
42 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
43 type IArvadosClient interface {
44 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
45 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
46 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
47 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
48 CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
49 Discovery(key string) (interface{}, error)
52 // ErrCancelled is the error returned when the container is cancelled.
53 var ErrCancelled = errors.New("Cancelled")
55 // IKeepClient is the minimal Keep API methods used by crunch-run.
56 type IKeepClient interface {
57 PutHB(hash string, buf []byte) (string, int, error)
58 ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error)
62 // NewLogWriter is a factory function to create a new log writer.
63 type NewLogWriter func(name string) io.WriteCloser
65 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
67 type MkTempDir func(string, string) (string, error)
69 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
70 type ThinDockerClient interface {
71 ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error)
72 ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
73 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error)
74 ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error
75 ContainerStop(ctx context.Context, container string, timeout *time.Duration) error
76 ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error)
77 ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error)
78 ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error)
79 ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error)
82 // ThinDockerClientProxy is a proxy implementation of ThinDockerClient
83 // that executes the docker requests on dockerclient.Client
84 type ThinDockerClientProxy struct {
85 Docker *dockerclient.Client
88 // ContainerAttach invokes dockerclient.Client.ContainerAttach
89 func (proxy ThinDockerClientProxy) ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error) {
90 return proxy.Docker.ContainerAttach(ctx, container, options)
93 // ContainerCreate invokes dockerclient.Client.ContainerCreate
94 func (proxy ThinDockerClientProxy) ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
95 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error) {
96 return proxy.Docker.ContainerCreate(ctx, config, hostConfig, networkingConfig, containerName)
99 // ContainerStart invokes dockerclient.Client.ContainerStart
100 func (proxy ThinDockerClientProxy) ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error {
101 return proxy.Docker.ContainerStart(ctx, container, options)
104 // ContainerStop invokes dockerclient.Client.ContainerStop
105 func (proxy ThinDockerClientProxy) ContainerStop(ctx context.Context, container string, timeout *time.Duration) error {
106 return proxy.Docker.ContainerStop(ctx, container, timeout)
109 // ContainerWait invokes dockerclient.Client.ContainerWait
110 func (proxy ThinDockerClientProxy) ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error) {
111 return proxy.Docker.ContainerWait(ctx, container, condition)
114 // ImageInspectWithRaw invokes dockerclient.Client.ImageInspectWithRaw
115 func (proxy ThinDockerClientProxy) ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error) {
116 return proxy.Docker.ImageInspectWithRaw(ctx, image)
119 // ImageLoad invokes dockerclient.Client.ImageLoad
120 func (proxy ThinDockerClientProxy) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error) {
121 return proxy.Docker.ImageLoad(ctx, input, quiet)
124 // ImageRemove invokes dockerclient.Client.ImageRemove
125 func (proxy ThinDockerClientProxy) ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {
126 return proxy.Docker.ImageRemove(ctx, image, options)
129 // ContainerRunner is the main stateful struct used for a single execution of a
131 type ContainerRunner struct {
132 Docker ThinDockerClient
133 ArvClient IArvadosClient
136 ContainerConfig dockercontainer.Config
137 dockercontainer.HostConfig
142 loggingDone chan bool
143 CrunchLog *ThrottledLogger
144 Stdout io.WriteCloser
145 Stderr io.WriteCloser
146 LogCollection *CollectionWriter
153 CleanupTempDir []string
155 Volumes map[string]struct{}
157 SigChan chan os.Signal
158 ArvMountExit chan error
161 statLogger io.WriteCloser
162 statReporter *crunchstat.Reporter
163 statInterval time.Duration
165 // What we expect the container's cgroup parent to be.
166 expectCgroupParent string
167 // What we tell docker to use as the container's cgroup
168 // parent. Note: Ideally we would use the same field for both
169 // expectCgroupParent and setCgroupParent, and just make it
170 // default to "docker". However, when using docker < 1.10 with
171 // systemd, specifying a non-empty cgroup parent (even the
172 // default value "docker") hits a docker bug
173 // (https://github.com/docker/docker/issues/17126). Using two
174 // separate fields makes it possible to use the "expect cgroup
175 // parent to be X" feature even on sites where the "specify
176 // cgroup parent" feature breaks.
177 setCgroupParent string
179 cStateLock sync.Mutex
180 cStarted bool // StartContainer() succeeded
181 cCancelled bool // StopContainer() invoked
183 enableNetwork string // one of "default" or "always"
184 networkMode string // passed through to HostConfig.NetworkMode
185 arvMountLog *ThrottledLogger
188 // setupSignals sets up signal handling to gracefully terminate the underlying
189 // Docker container and update state when receiving a TERM, INT or QUIT signal.
190 func (runner *ContainerRunner) setupSignals() {
191 runner.SigChan = make(chan os.Signal, 1)
192 signal.Notify(runner.SigChan, syscall.SIGTERM)
193 signal.Notify(runner.SigChan, syscall.SIGINT)
194 signal.Notify(runner.SigChan, syscall.SIGQUIT)
196 go func(sig chan os.Signal) {
199 runner.CrunchLog.Printf("Caught signal %v", s)
205 // stop the underlying Docker container.
206 func (runner *ContainerRunner) stop() {
207 runner.cStateLock.Lock()
208 defer runner.cStateLock.Unlock()
209 if runner.cCancelled {
212 runner.cCancelled = true
214 timeout := time.Duration(10)
215 err := runner.Docker.ContainerStop(context.TODO(), runner.ContainerID, &(timeout))
217 runner.CrunchLog.Printf("StopContainer failed: %s", err)
219 // Suppress multiple calls to stop()
220 runner.cStarted = false
224 func (runner *ContainerRunner) stopSignals() {
225 if runner.SigChan != nil {
226 signal.Stop(runner.SigChan)
227 close(runner.SigChan)
231 // LoadImage determines the docker image id from the container record and
232 // checks if it is available in the local Docker image store. If not, it loads
233 // the image from Keep.
234 func (runner *ContainerRunner) LoadImage() (err error) {
236 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
238 var collection arvados.Collection
239 err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
241 return fmt.Errorf("While getting container image collection: %v", err)
243 manifest := manifest.Manifest{Text: collection.ManifestText}
244 var img, imageID string
245 for ms := range manifest.StreamIter() {
246 img = ms.FileStreamSegments[0].Name
247 if !strings.HasSuffix(img, ".tar") {
248 return fmt.Errorf("First file in the container image collection does not end in .tar")
250 imageID = img[:len(img)-4]
253 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
255 _, _, err = runner.Docker.ImageInspectWithRaw(context.TODO(), imageID)
257 runner.CrunchLog.Print("Loading Docker image from keep")
259 var readCloser io.ReadCloser
260 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
262 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
265 response, err := runner.Docker.ImageLoad(context.TODO(), readCloser, true)
267 return fmt.Errorf("While loading container image into Docker: %v", err)
270 defer response.Body.Close()
271 rbody, err := ioutil.ReadAll(response.Body)
273 return fmt.Errorf("Reading response to image load: %v", err)
275 runner.CrunchLog.Printf("Docker response: %s", rbody)
277 runner.CrunchLog.Print("Docker image is available")
280 runner.ContainerConfig.Image = imageID
282 runner.Kc.ClearBlockCache()
287 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
288 c = exec.Command("arv-mount", arvMountCmd...)
290 // Copy our environment, but override ARVADOS_API_TOKEN with
291 // the container auth token.
293 for _, s := range os.Environ() {
294 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
295 c.Env = append(c.Env, s)
298 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
300 runner.arvMountLog = NewThrottledLogger(runner.NewLogWriter("arv-mount"))
301 c.Stdout = runner.arvMountLog
302 c.Stderr = runner.arvMountLog
304 runner.CrunchLog.Printf("Running %v", c.Args)
311 statReadme := make(chan bool)
312 runner.ArvMountExit = make(chan error)
317 time.Sleep(100 * time.Millisecond)
318 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
330 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
332 runner.ArvMountExit <- mnterr
333 close(runner.ArvMountExit)
339 case err := <-runner.ArvMountExit:
340 runner.ArvMount = nil
348 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
349 if runner.ArvMountPoint == "" {
350 runner.ArvMountPoint, err = runner.MkTempDir("", prefix)
355 func (runner *ContainerRunner) SetupMounts() (err error) {
356 err = runner.SetupArvMountPoint("keep")
358 return fmt.Errorf("While creating keep mount temp dir: %v", err)
363 arvMountCmd := []string{
367 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
369 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
370 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
373 collectionPaths := []string{}
375 runner.Volumes = make(map[string]struct{})
376 needCertMount := true
379 for bind := range runner.Container.Mounts {
380 binds = append(binds, bind)
384 for _, bind := range binds {
385 mnt := runner.Container.Mounts[bind]
386 if bind == "stdout" || bind == "stderr" {
387 // Is it a "file" mount kind?
388 if mnt.Kind != "file" {
389 return fmt.Errorf("Unsupported mount kind '%s' for %s. Only 'file' is supported.", mnt.Kind, bind)
392 // Does path start with OutputPath?
393 prefix := runner.Container.OutputPath
394 if !strings.HasSuffix(prefix, "/") {
397 if !strings.HasPrefix(mnt.Path, prefix) {
398 return fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
403 // Is it a "collection" mount kind?
404 if mnt.Kind != "collection" && mnt.Kind != "json" {
405 return fmt.Errorf("Unsupported mount kind '%s' for stdin. Only 'collection' or 'json' are supported.", mnt.Kind)
409 if bind == "/etc/arvados/ca-certificates.crt" {
410 needCertMount = false
413 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
414 if mnt.Kind != "collection" {
415 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
420 case mnt.Kind == "collection" && bind != "stdin":
422 if mnt.UUID != "" && mnt.PortableDataHash != "" {
423 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
427 return fmt.Errorf("Writing to existing collections currently not permitted.")
430 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
431 } else if mnt.PortableDataHash != "" {
433 return fmt.Errorf("Can never write to a collection specified by portable data hash")
435 idx := strings.Index(mnt.PortableDataHash, "/")
437 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
438 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
439 runner.Container.Mounts[bind] = mnt
441 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
442 if mnt.Path != "" && mnt.Path != "." {
443 if strings.HasPrefix(mnt.Path, "./") {
444 mnt.Path = mnt.Path[2:]
445 } else if strings.HasPrefix(mnt.Path, "/") {
446 mnt.Path = mnt.Path[1:]
448 src += "/" + mnt.Path
451 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
452 arvMountCmd = append(arvMountCmd, "--mount-tmp")
453 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
457 if bind == runner.Container.OutputPath {
458 runner.HostOutputDir = src
459 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
460 return fmt.Errorf("Writable mount points are not permitted underneath the output_path: %v", bind)
462 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
464 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
466 collectionPaths = append(collectionPaths, src)
468 case mnt.Kind == "tmp":
470 tmpdir, err = runner.MkTempDir("", "")
472 return fmt.Errorf("While creating mount temp dir: %v", err)
474 st, staterr := os.Stat(tmpdir)
476 return fmt.Errorf("While Stat on temp dir: %v", staterr)
478 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
480 return fmt.Errorf("While Chmod temp dir: %v", err)
482 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
483 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", tmpdir, bind))
484 if bind == runner.Container.OutputPath {
485 runner.HostOutputDir = tmpdir
488 case mnt.Kind == "json":
489 jsondata, err := json.Marshal(mnt.Content)
491 return fmt.Errorf("encoding json data: %v", err)
493 // Create a tempdir with a single file
494 // (instead of just a tempfile): this way we
495 // can ensure the file is world-readable
496 // inside the container, without having to
497 // make it world-readable on the docker host.
498 tmpdir, err := runner.MkTempDir("", "")
500 return fmt.Errorf("creating temp dir: %v", err)
502 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
503 tmpfn := filepath.Join(tmpdir, "mountdata.json")
504 err = ioutil.WriteFile(tmpfn, jsondata, 0644)
506 return fmt.Errorf("writing temp file: %v", err)
508 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
512 if runner.HostOutputDir == "" {
513 return fmt.Errorf("Output path does not correspond to a writable mount point")
516 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
517 for _, certfile := range arvadosclient.CertFiles {
518 _, err := os.Stat(certfile)
520 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
527 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
529 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
531 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
533 token, err := runner.ContainerToken()
535 return fmt.Errorf("could not get container token: %s", err)
538 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
540 return fmt.Errorf("While trying to start arv-mount: %v", err)
543 for _, p := range collectionPaths {
546 return fmt.Errorf("While checking that input files exist: %v", err)
553 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
554 // Handle docker log protocol
555 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
557 header := make([]byte, 8)
559 _, readerr := io.ReadAtLeast(containerReader, header, 8)
562 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
565 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
568 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
573 if readerr != io.EOF {
574 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
577 closeerr := runner.Stdout.Close()
579 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
582 closeerr = runner.Stderr.Close()
584 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
587 if runner.statReporter != nil {
588 runner.statReporter.Stop()
589 closeerr = runner.statLogger.Close()
591 runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
595 runner.loggingDone <- true
596 close(runner.loggingDone)
602 func (runner *ContainerRunner) StartCrunchstat() {
603 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
604 runner.statReporter = &crunchstat.Reporter{
605 CID: runner.ContainerID,
606 Logger: log.New(runner.statLogger, "", 0),
607 CgroupParent: runner.expectCgroupParent,
608 CgroupRoot: runner.cgroupRoot,
609 PollPeriod: runner.statInterval,
611 runner.statReporter.Start()
614 type infoCommand struct {
619 // Gather node information and store it on the log for debugging
621 func (runner *ContainerRunner) LogNodeInfo() (err error) {
622 w := runner.NewLogWriter("node-info")
623 logger := log.New(w, "node-info", 0)
625 commands := []infoCommand{
627 label: "Host Information",
628 cmd: []string{"uname", "-a"},
631 label: "CPU Information",
632 cmd: []string{"cat", "/proc/cpuinfo"},
635 label: "Memory Information",
636 cmd: []string{"cat", "/proc/meminfo"},
640 cmd: []string{"df", "-m", "/", os.TempDir()},
643 label: "Disk INodes",
644 cmd: []string{"df", "-i", "/", os.TempDir()},
648 // Run commands with informational output to be logged.
650 for _, command := range commands {
651 out, err = exec.Command(command.cmd[0], command.cmd[1:]...).CombinedOutput()
653 return fmt.Errorf("While running command %q: %v",
656 logger.Println(command.label)
657 for _, line := range strings.Split(string(out), "\n") {
658 logger.Println(" ", line)
664 return fmt.Errorf("While closing node-info logs: %v", err)
669 // Get and save the raw JSON container record from the API server
670 func (runner *ContainerRunner) LogContainerRecord() (err error) {
672 ArvClient: runner.ArvClient,
673 UUID: runner.Container.UUID,
674 loggingStream: "container",
675 writeCloser: runner.LogCollection.Open("container.json"),
678 // Get Container record JSON from the API Server
679 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
681 return fmt.Errorf("While retrieving container record from the API server: %v", err)
685 dec := json.NewDecoder(reader)
687 var cr map[string]interface{}
688 if err = dec.Decode(&cr); err != nil {
689 return fmt.Errorf("While decoding the container record JSON response: %v", err)
691 // Re-encode it using indentation to improve readability
692 enc := json.NewEncoder(w)
693 enc.SetIndent("", " ")
694 if err = enc.Encode(cr); err != nil {
695 return fmt.Errorf("While logging the JSON container record: %v", err)
699 return fmt.Errorf("While closing container.json log: %v", err)
704 // AttachStreams connects the docker container stdin, stdout and stderr logs
705 // to the Arvados logger which logs to Keep and the API server logs table.
706 func (runner *ContainerRunner) AttachStreams() (err error) {
708 runner.CrunchLog.Print("Attaching container streams")
710 // If stdin mount is provided, attach it to the docker container
711 var stdinRdr arvados.File
713 if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
714 if stdinMnt.Kind == "collection" {
715 var stdinColl arvados.Collection
716 collId := stdinMnt.UUID
718 collId = stdinMnt.PortableDataHash
720 err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
722 return fmt.Errorf("While getting stding collection: %v", err)
725 stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
726 if os.IsNotExist(err) {
727 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
728 } else if err != nil {
729 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
731 } else if stdinMnt.Kind == "json" {
732 stdinJson, err = json.Marshal(stdinMnt.Content)
734 return fmt.Errorf("While encoding stdin json data: %v", err)
739 stdinUsed := stdinRdr != nil || len(stdinJson) != 0
740 response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
741 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
743 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
746 runner.loggingDone = make(chan bool)
748 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
749 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
753 runner.Stdout = stdoutFile
755 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
758 if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
759 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
763 runner.Stderr = stderrFile
765 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
770 _, err := io.Copy(response.Conn, stdinRdr)
772 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
776 response.CloseWrite()
778 } else if len(stdinJson) != 0 {
780 _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
782 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
785 response.CloseWrite()
789 go runner.ProcessDockerAttach(response.Reader)
794 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
795 stdoutPath := mntPath[len(runner.Container.OutputPath):]
796 index := strings.LastIndex(stdoutPath, "/")
798 subdirs := stdoutPath[:index]
800 st, err := os.Stat(runner.HostOutputDir)
802 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
804 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
805 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
807 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
811 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
813 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
816 return stdoutFile, nil
819 // CreateContainer creates the docker container.
820 func (runner *ContainerRunner) CreateContainer() error {
821 runner.CrunchLog.Print("Creating Docker container")
823 runner.ContainerConfig.Cmd = runner.Container.Command
824 if runner.Container.Cwd != "." {
825 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
828 for k, v := range runner.Container.Environment {
829 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
832 runner.ContainerConfig.Volumes = runner.Volumes
834 runner.HostConfig = dockercontainer.HostConfig{
836 LogConfig: dockercontainer.LogConfig{
839 Resources: dockercontainer.Resources{
840 CgroupParent: runner.setCgroupParent,
844 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
845 tok, err := runner.ContainerToken()
849 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
850 "ARVADOS_API_TOKEN="+tok,
851 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
852 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
854 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
856 if runner.enableNetwork == "always" {
857 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
859 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
863 _, stdinUsed := runner.Container.Mounts["stdin"]
864 runner.ContainerConfig.OpenStdin = stdinUsed
865 runner.ContainerConfig.StdinOnce = stdinUsed
866 runner.ContainerConfig.AttachStdin = stdinUsed
867 runner.ContainerConfig.AttachStdout = true
868 runner.ContainerConfig.AttachStderr = true
870 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
872 return fmt.Errorf("While creating container: %v", err)
875 runner.ContainerID = createdBody.ID
877 return runner.AttachStreams()
880 // StartContainer starts the docker container created by CreateContainer.
881 func (runner *ContainerRunner) StartContainer() error {
882 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
883 runner.cStateLock.Lock()
884 defer runner.cStateLock.Unlock()
885 if runner.cCancelled {
888 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
889 dockertypes.ContainerStartOptions{})
892 if strings.Contains(err.Error(), "no such file or directory") {
893 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])
895 return fmt.Errorf("could not start container: %v%s", err, advice)
897 runner.cStarted = true
901 // WaitFinish waits for the container to terminate, capture the exit code, and
902 // close the stdout/stderr logging.
903 func (runner *ContainerRunner) WaitFinish() (err error) {
904 runner.CrunchLog.Print("Waiting for container to finish")
906 waitOk, waitErr := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID, "not-running")
909 <-runner.ArvMountExit
911 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
916 var waitBody dockercontainer.ContainerWaitOKBody
918 case waitBody = <-waitOk:
919 case err = <-waitErr:
922 // Container isn't running any more
923 runner.cStarted = false
926 return fmt.Errorf("container wait: %v", err)
929 runner.CrunchLog.Printf("Container exited with code: %v", waitBody.StatusCode)
930 code := int(waitBody.StatusCode)
931 runner.ExitCode = &code
933 // wait for stdout/stderr to complete
939 var ErrNotInOutputDir = fmt.Errorf("Must point to path within the output directory")
941 func (runner *ContainerRunner) derefOutputSymlink(path string, startinfo os.FileInfo) (tgt string, readlinktgt string, info os.FileInfo, err error) {
942 // Follow symlinks if necessary
947 for followed := 0; info.Mode()&os.ModeSymlink != 0; followed++ {
948 if followed >= limitFollowSymlinks {
949 // Got stuck in a loop or just a pathological number of links, give up.
950 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
954 readlinktgt, err = os.Readlink(nextlink)
960 if !strings.HasPrefix(tgt, "/") {
961 // Relative symlink, resolve it to host path
962 tgt = filepath.Join(filepath.Dir(path), tgt)
964 if strings.HasPrefix(tgt, runner.Container.OutputPath+"/") && !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
965 // Absolute symlink to container output path, adjust it to host output path.
966 tgt = filepath.Join(runner.HostOutputDir, tgt[len(runner.Container.OutputPath):])
968 if !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
969 // After dereferencing, symlink target must either be
970 // within output directory, or must point to a
972 err = ErrNotInOutputDir
976 info, err = os.Lstat(tgt)
979 err = fmt.Errorf("Symlink in output %q points to invalid location %q: %v",
980 path[len(runner.HostOutputDir):], readlinktgt, err)
990 var limitFollowSymlinks = 10
992 // UploadFile uploads files within the output directory, with special handling
993 // for symlinks. If the symlink leads to a keep mount, copy the manifest text
994 // from the keep mount into the output manifestText. Ensure that whether
995 // symlinks are relative or absolute, every symlink target (even targets that
996 // are symlinks themselves) must point to a path in either the output directory
997 // or a collection mount.
999 // Assumes initial value of "path" is absolute, and located within runner.HostOutputDir.
1000 func (runner *ContainerRunner) UploadOutputFile(
1005 walkUpload *WalkUpload,
1006 relocateFrom string,
1008 followed int) (manifestText string, err error) {
1010 if info.Mode().IsDir() {
1018 if followed >= limitFollowSymlinks {
1019 // Got stuck in a loop or just a pathological number of
1020 // directory links, give up.
1021 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
1025 // When following symlinks, the source path may need to be logically
1026 // relocated to some other path within the output collection. Remove
1027 // the relocateFrom prefix and replace it with relocateTo.
1028 relocated := relocateTo + path[len(relocateFrom):]
1030 tgt, readlinktgt, info, derefErr := runner.derefOutputSymlink(path, info)
1031 if derefErr != nil && derefErr != ErrNotInOutputDir {
1035 // go through mounts and try reverse map to collection reference
1036 for _, bind := range binds {
1037 mnt := runner.Container.Mounts[bind]
1038 if tgt == bind || strings.HasPrefix(tgt, bind+"/") {
1039 // get path relative to bind
1040 targetSuffix := tgt[len(bind):]
1042 // Copy mount and adjust the path to add path relative to the bind
1043 adjustedMount := mnt
1044 adjustedMount.Path = filepath.Join(adjustedMount.Path, targetSuffix)
1046 // Terminates in this keep mount, so add the
1047 // manifest text at appropriate location.
1048 outputSuffix := path[len(runner.HostOutputDir):]
1049 manifestText, err = runner.getCollectionManifestForPath(adjustedMount, outputSuffix)
1054 // If target is not a collection mount, it must be located within the
1055 // output directory, otherwise it is an error.
1056 if derefErr == ErrNotInOutputDir {
1057 err = fmt.Errorf("Symlink in output %q points to invalid location %q, must point to path within the output directory.",
1058 path[len(runner.HostOutputDir):], readlinktgt)
1062 if info.Mode().IsRegular() {
1063 return "", walkUpload.UploadFile(relocated, tgt)
1066 if info.Mode().IsDir() {
1067 // Symlink leads to directory. Walk() doesn't follow
1068 // directory symlinks, so we walk the target directory
1069 // instead. Within the walk, file paths are relocated
1070 // so they appear under the original symlink path.
1071 err = filepath.Walk(tgt, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
1073 m, walkerr = runner.UploadOutputFile(walkpath, walkinfo, walkerr,
1074 binds, walkUpload, tgt, relocated, followed+1)
1076 manifestText = manifestText + m
1086 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
1087 func (runner *ContainerRunner) CaptureOutput() error {
1088 if runner.finalState != "Complete" {
1092 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
1093 // Output may have been set directly by the container, so
1094 // refresh the container record to check.
1095 err := runner.ArvClient.Get("containers", runner.Container.UUID,
1096 nil, &runner.Container)
1100 if runner.Container.Output != "" {
1101 // Container output is already set.
1102 runner.OutputPDH = &runner.Container.Output
1107 if runner.HostOutputDir == "" {
1111 _, err := os.Stat(runner.HostOutputDir)
1113 return fmt.Errorf("While checking host output path: %v", err)
1116 // Pre-populate output from the configured mount points
1118 for bind, mnt := range runner.Container.Mounts {
1119 if mnt.Kind == "collection" {
1120 binds = append(binds, bind)
1125 var manifestText string
1127 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
1128 _, err = os.Stat(collectionMetafile)
1130 // Regular directory
1132 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
1133 walkUpload := cw.BeginUpload(runner.HostOutputDir, runner.CrunchLog.Logger)
1136 err = filepath.Walk(runner.HostOutputDir, func(path string, info os.FileInfo, err error) error {
1137 m, err = runner.UploadOutputFile(path, info, err, binds, walkUpload, "", "", 0)
1139 manifestText = manifestText + m
1144 cw.EndUpload(walkUpload)
1147 return fmt.Errorf("While uploading output files: %v", err)
1150 m, err = cw.ManifestText()
1151 manifestText = manifestText + m
1153 return fmt.Errorf("While uploading output files: %v", err)
1156 // FUSE mount directory
1157 file, openerr := os.Open(collectionMetafile)
1159 return fmt.Errorf("While opening FUSE metafile: %v", err)
1163 var rec arvados.Collection
1164 err = json.NewDecoder(file).Decode(&rec)
1166 return fmt.Errorf("While reading FUSE metafile: %v", err)
1168 manifestText = rec.ManifestText
1171 for _, bind := range binds {
1172 mnt := runner.Container.Mounts[bind]
1174 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
1176 if bindSuffix == bind || len(bindSuffix) <= 0 {
1177 // either does not start with OutputPath or is OutputPath itself
1181 if mnt.ExcludeFromOutput == true {
1185 // append to manifest_text
1186 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
1191 manifestText = manifestText + m
1195 var response arvados.Collection
1196 manifest := manifest.Manifest{Text: manifestText}
1197 manifestText = manifest.Extract(".", ".").Text
1198 err = runner.ArvClient.Create("collections",
1200 "ensure_unique_name": true,
1201 "collection": arvadosclient.Dict{
1203 "name": "output for " + runner.Container.UUID,
1204 "manifest_text": manifestText}},
1207 return fmt.Errorf("While creating output collection: %v", err)
1209 runner.OutputPDH = &response.PortableDataHash
1213 var outputCollections = make(map[string]arvados.Collection)
1215 // Fetch the collection for the mnt.PortableDataHash
1216 // Return the manifest_text fragment corresponding to the specified mnt.Path
1217 // after making any required updates.
1219 // If mnt.Path is not specified,
1220 // return the entire manifest_text after replacing any "." with bindSuffix
1221 // If mnt.Path corresponds to one stream,
1222 // return the manifest_text for that stream after replacing that stream name with bindSuffix
1223 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1224 // for that stream after replacing stream name with bindSuffix minus the last word
1225 // and the file name with last word of the bindSuffix
1226 // Allowed path examples:
1228 // "path":"/subdir1"
1229 // "path":"/subdir1/subdir2"
1230 // "path":"/subdir/filename" etc
1231 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1232 collection := outputCollections[mnt.PortableDataHash]
1233 if collection.PortableDataHash == "" {
1234 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1236 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1238 outputCollections[mnt.PortableDataHash] = collection
1241 if collection.ManifestText == "" {
1242 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1246 mft := manifest.Manifest{Text: collection.ManifestText}
1247 extracted := mft.Extract(mnt.Path, bindSuffix)
1248 if extracted.Err != nil {
1249 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1251 return extracted.Text, nil
1254 func (runner *ContainerRunner) CleanupDirs() {
1255 if runner.ArvMount != nil {
1257 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1258 umount.Stdout = runner.CrunchLog
1259 umount.Stderr = runner.CrunchLog
1260 runner.CrunchLog.Printf("Running %v", umount.Args)
1261 umnterr := umount.Start()
1264 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1266 // If arv-mount --unmount gets stuck for any reason, we
1267 // don't want to wait for it forever. Do Wait() in a goroutine
1268 // so it doesn't block crunch-run.
1269 umountExit := make(chan error)
1271 mnterr := umount.Wait()
1273 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1275 umountExit <- mnterr
1278 for again := true; again; {
1284 case <-runner.ArvMountExit:
1286 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1287 runner.CrunchLog.Printf("Timed out waiting for unmount")
1289 umount.Process.Kill()
1291 runner.ArvMount.Process.Kill()
1297 if runner.ArvMountPoint != "" {
1298 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1299 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1303 for _, tmpdir := range runner.CleanupTempDir {
1304 if rmerr := os.RemoveAll(tmpdir); rmerr != nil {
1305 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1310 // CommitLogs posts the collection containing the final container logs.
1311 func (runner *ContainerRunner) CommitLogs() error {
1312 runner.CrunchLog.Print(runner.finalState)
1314 if runner.arvMountLog != nil {
1315 runner.arvMountLog.Close()
1317 runner.CrunchLog.Close()
1319 // Closing CrunchLog above allows them to be committed to Keep at this
1320 // point, but re-open crunch log with ArvClient in case there are any
1321 // other further errors (such as failing to write the log to Keep!)
1322 // while shutting down
1323 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1324 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1325 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1327 if runner.LogsPDH != nil {
1328 // If we have already assigned something to LogsPDH,
1329 // we must be closing the re-opened log, which won't
1330 // end up getting attached to the container record and
1331 // therefore doesn't need to be saved as a collection
1332 // -- it exists only to send logs to other channels.
1336 mt, err := runner.LogCollection.ManifestText()
1338 return fmt.Errorf("While creating log manifest: %v", err)
1341 var response arvados.Collection
1342 err = runner.ArvClient.Create("collections",
1344 "ensure_unique_name": true,
1345 "collection": arvadosclient.Dict{
1347 "name": "logs for " + runner.Container.UUID,
1348 "manifest_text": mt}},
1351 return fmt.Errorf("While creating log collection: %v", err)
1353 runner.LogsPDH = &response.PortableDataHash
1357 // UpdateContainerRunning updates the container state to "Running"
1358 func (runner *ContainerRunner) UpdateContainerRunning() error {
1359 runner.cStateLock.Lock()
1360 defer runner.cStateLock.Unlock()
1361 if runner.cCancelled {
1364 return runner.ArvClient.Update("containers", runner.Container.UUID,
1365 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1368 // ContainerToken returns the api_token the container (and any
1369 // arv-mount processes) are allowed to use.
1370 func (runner *ContainerRunner) ContainerToken() (string, error) {
1371 if runner.token != "" {
1372 return runner.token, nil
1375 var auth arvados.APIClientAuthorization
1376 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1380 runner.token = auth.APIToken
1381 return runner.token, nil
1384 // UpdateContainerComplete updates the container record state on API
1385 // server to "Complete" or "Cancelled"
1386 func (runner *ContainerRunner) UpdateContainerFinal() error {
1387 update := arvadosclient.Dict{}
1388 update["state"] = runner.finalState
1389 if runner.LogsPDH != nil {
1390 update["log"] = *runner.LogsPDH
1392 if runner.finalState == "Complete" {
1393 if runner.ExitCode != nil {
1394 update["exit_code"] = *runner.ExitCode
1396 if runner.OutputPDH != nil {
1397 update["output"] = *runner.OutputPDH
1400 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1403 // IsCancelled returns the value of Cancelled, with goroutine safety.
1404 func (runner *ContainerRunner) IsCancelled() bool {
1405 runner.cStateLock.Lock()
1406 defer runner.cStateLock.Unlock()
1407 return runner.cCancelled
1410 // NewArvLogWriter creates an ArvLogWriter
1411 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1412 return &ArvLogWriter{
1413 ArvClient: runner.ArvClient,
1414 UUID: runner.Container.UUID,
1415 loggingStream: name,
1416 writeCloser: runner.LogCollection.Open(name + ".txt")}
1419 // Run the full container lifecycle.
1420 func (runner *ContainerRunner) Run() (err error) {
1421 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1423 hostname, hosterr := os.Hostname()
1425 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1427 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1430 runner.finalState = "Queued"
1433 runner.stopSignals()
1434 runner.CleanupDirs()
1436 runner.CrunchLog.Printf("crunch-run finished")
1437 runner.CrunchLog.Close()
1441 // checkErr prints e (unless it's nil) and sets err to
1442 // e (unless err is already non-nil). Thus, if err
1443 // hasn't already been assigned when Run() returns,
1444 // this cleanup func will cause Run() to return the
1445 // first non-nil error that is passed to checkErr().
1446 checkErr := func(e error) {
1450 runner.CrunchLog.Print(e)
1454 if runner.finalState == "Complete" {
1455 // There was an error in the finalization.
1456 runner.finalState = "Cancelled"
1460 // Log the error encountered in Run(), if any
1463 if runner.finalState == "Queued" {
1464 runner.UpdateContainerFinal()
1468 if runner.IsCancelled() {
1469 runner.finalState = "Cancelled"
1470 // but don't return yet -- we still want to
1471 // capture partial output and write logs
1474 checkErr(runner.CaptureOutput())
1475 checkErr(runner.CommitLogs())
1476 checkErr(runner.UpdateContainerFinal())
1479 err = runner.fetchContainerRecord()
1484 // setup signal handling
1485 runner.setupSignals()
1487 // check for and/or load image
1488 err = runner.LoadImage()
1490 runner.finalState = "Cancelled"
1491 err = fmt.Errorf("While loading container image: %v", err)
1495 // set up FUSE mount and binds
1496 err = runner.SetupMounts()
1498 runner.finalState = "Cancelled"
1499 err = fmt.Errorf("While setting up mounts: %v", err)
1503 err = runner.CreateContainer()
1508 // Gather and record node information
1509 err = runner.LogNodeInfo()
1513 // Save container.json record on log collection
1514 err = runner.LogContainerRecord()
1519 runner.StartCrunchstat()
1521 if runner.IsCancelled() {
1525 err = runner.UpdateContainerRunning()
1529 runner.finalState = "Cancelled"
1531 err = runner.StartContainer()
1536 err = runner.WaitFinish()
1538 runner.finalState = "Complete"
1543 // Fetch the current container record (uuid = runner.Container.UUID)
1544 // into runner.Container.
1545 func (runner *ContainerRunner) fetchContainerRecord() error {
1546 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1548 return fmt.Errorf("error fetching container record: %v", err)
1550 defer reader.Close()
1552 dec := json.NewDecoder(reader)
1554 err = dec.Decode(&runner.Container)
1556 return fmt.Errorf("error decoding container record: %v", err)
1561 // NewContainerRunner creates a new container runner.
1562 func NewContainerRunner(api IArvadosClient,
1564 docker ThinDockerClient,
1565 containerUUID string) *ContainerRunner {
1567 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1568 cr.NewLogWriter = cr.NewArvLogWriter
1569 cr.RunArvMount = cr.ArvMountCmd
1570 cr.MkTempDir = ioutil.TempDir
1571 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1572 cr.Container.UUID = containerUUID
1573 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1574 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1576 loadLogThrottleParams(api)
1582 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1583 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1584 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1585 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1586 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1587 enableNetwork := flag.String("container-enable-networking", "default",
1588 `Specify if networking should be enabled for container. One of 'default', 'always':
1589 default: only enable networking if container requests it.
1590 always: containers always have networking enabled
1592 networkMode := flag.String("container-network-mode", "default",
1593 `Set networking mode for container. Corresponds to Docker network mode (--net).
1595 memprofile := flag.String("memprofile", "", "write memory profile to `file` after running container")
1598 containerId := flag.Arg(0)
1600 if *caCertsPath != "" {
1601 arvadosclient.CertFiles = []string{*caCertsPath}
1604 api, err := arvadosclient.MakeArvadosClient()
1606 log.Fatalf("%s: %v", containerId, err)
1610 var kc *keepclient.KeepClient
1611 kc, err = keepclient.MakeKeepClient(api)
1613 log.Fatalf("%s: %v", containerId, err)
1615 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1618 var docker *dockerclient.Client
1619 // API version 1.21 corresponds to Docker 1.9, which is currently the
1620 // minimum version we want to support.
1621 docker, err = dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1623 log.Fatalf("%s: %v", containerId, err)
1626 dockerClientProxy := ThinDockerClientProxy{Docker: docker}
1628 cr := NewContainerRunner(api, kc, dockerClientProxy, containerId)
1629 cr.statInterval = *statInterval
1630 cr.cgroupRoot = *cgroupRoot
1631 cr.expectCgroupParent = *cgroupParent
1632 cr.enableNetwork = *enableNetwork
1633 cr.networkMode = *networkMode
1634 if *cgroupParentSubsystem != "" {
1635 p := findCgroup(*cgroupParentSubsystem)
1636 cr.setCgroupParent = p
1637 cr.expectCgroupParent = p
1642 if *memprofile != "" {
1643 f, err := os.Create(*memprofile)
1645 log.Printf("could not create memory profile: ", err)
1647 runtime.GC() // get up-to-date statistics
1648 if err := pprof.WriteHeapProfile(f); err != nil {
1649 log.Printf("could not write memory profile: ", err)
1651 closeerr := f.Close()
1652 if closeerr != nil {
1653 log.Printf("closing memprofile file: ", err)
1658 log.Fatalf("%s: %v", containerId, runerr)