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
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) {
202 // stop the underlying Docker container.
203 func (runner *ContainerRunner) stop() {
204 runner.cStateLock.Lock()
205 defer runner.cStateLock.Unlock()
206 if runner.cCancelled {
209 runner.cCancelled = true
211 timeout := time.Duration(10)
212 err := runner.Docker.ContainerStop(context.TODO(), runner.ContainerID, &(timeout))
214 log.Printf("StopContainer failed: %s", err)
219 func (runner *ContainerRunner) teardown() {
220 if runner.SigChan != nil {
221 signal.Stop(runner.SigChan)
222 close(runner.SigChan)
226 // LoadImage determines the docker image id from the container record and
227 // checks if it is available in the local Docker image store. If not, it loads
228 // the image from Keep.
229 func (runner *ContainerRunner) LoadImage() (err error) {
231 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
233 var collection arvados.Collection
234 err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
236 return fmt.Errorf("While getting container image collection: %v", err)
238 manifest := manifest.Manifest{Text: collection.ManifestText}
239 var img, imageID string
240 for ms := range manifest.StreamIter() {
241 img = ms.FileStreamSegments[0].Name
242 if !strings.HasSuffix(img, ".tar") {
243 return fmt.Errorf("First file in the container image collection does not end in .tar")
245 imageID = img[:len(img)-4]
248 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
250 _, _, err = runner.Docker.ImageInspectWithRaw(context.TODO(), imageID)
252 runner.CrunchLog.Print("Loading Docker image from keep")
254 var readCloser io.ReadCloser
255 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
257 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
260 response, err := runner.Docker.ImageLoad(context.TODO(), readCloser, true)
262 return fmt.Errorf("While loading container image into Docker: %v", err)
265 defer response.Body.Close()
266 rbody, err := ioutil.ReadAll(response.Body)
268 return fmt.Errorf("Reading response to image load: %v", err)
270 runner.CrunchLog.Printf("Docker response: %s", rbody)
272 runner.CrunchLog.Print("Docker image is available")
275 runner.ContainerConfig.Image = imageID
277 runner.Kc.ClearBlockCache()
282 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
283 c = exec.Command("arv-mount", arvMountCmd...)
285 // Copy our environment, but override ARVADOS_API_TOKEN with
286 // the container auth token.
288 for _, s := range os.Environ() {
289 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
290 c.Env = append(c.Env, s)
293 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
295 nt := NewThrottledLogger(runner.NewLogWriter("arv-mount"))
304 runner.arvMountKill = func() {
308 statReadme := make(chan bool)
309 runner.ArvMountExit = make(chan error)
314 time.Sleep(100 * time.Millisecond)
315 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
325 runner.ArvMountExit <- c.Wait()
326 close(runner.ArvMountExit)
332 case err := <-runner.ArvMountExit:
333 runner.ArvMount = nil
341 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
342 if runner.ArvMountPoint == "" {
343 runner.ArvMountPoint, err = runner.MkTempDir("", prefix)
348 func (runner *ContainerRunner) SetupMounts() (err error) {
349 err = runner.SetupArvMountPoint("keep")
351 return fmt.Errorf("While creating keep mount temp dir: %v", err)
354 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.ArvMountPoint)
358 arvMountCmd := []string{"--foreground", "--allow-other", "--read-write"}
360 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
361 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
364 collectionPaths := []string{}
366 runner.Volumes = make(map[string]struct{})
367 needCertMount := true
370 for bind := range runner.Container.Mounts {
371 binds = append(binds, bind)
375 for _, bind := range binds {
376 mnt := runner.Container.Mounts[bind]
377 if bind == "stdout" || bind == "stderr" {
378 // Is it a "file" mount kind?
379 if mnt.Kind != "file" {
380 return fmt.Errorf("Unsupported mount kind '%s' for %s. Only 'file' is supported.", mnt.Kind, bind)
383 // Does path start with OutputPath?
384 prefix := runner.Container.OutputPath
385 if !strings.HasSuffix(prefix, "/") {
388 if !strings.HasPrefix(mnt.Path, prefix) {
389 return fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
394 // Is it a "collection" mount kind?
395 if mnt.Kind != "collection" && mnt.Kind != "json" {
396 return fmt.Errorf("Unsupported mount kind '%s' for stdin. Only 'collection' or 'json' are supported.", mnt.Kind)
400 if bind == "/etc/arvados/ca-certificates.crt" {
401 needCertMount = false
404 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
405 if mnt.Kind != "collection" {
406 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
411 case mnt.Kind == "collection" && bind != "stdin":
413 if mnt.UUID != "" && mnt.PortableDataHash != "" {
414 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
418 return fmt.Errorf("Writing to existing collections currently not permitted.")
421 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
422 } else if mnt.PortableDataHash != "" {
424 return fmt.Errorf("Can never write to a collection specified by portable data hash")
426 idx := strings.Index(mnt.PortableDataHash, "/")
428 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
429 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
430 runner.Container.Mounts[bind] = mnt
432 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
433 if mnt.Path != "" && mnt.Path != "." {
434 if strings.HasPrefix(mnt.Path, "./") {
435 mnt.Path = mnt.Path[2:]
436 } else if strings.HasPrefix(mnt.Path, "/") {
437 mnt.Path = mnt.Path[1:]
439 src += "/" + mnt.Path
442 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
443 arvMountCmd = append(arvMountCmd, "--mount-tmp")
444 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
448 if bind == runner.Container.OutputPath {
449 runner.HostOutputDir = src
450 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
451 return fmt.Errorf("Writable mount points are not permitted underneath the output_path: %v", bind)
453 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
455 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
457 collectionPaths = append(collectionPaths, src)
459 case mnt.Kind == "tmp":
461 tmpdir, err = runner.MkTempDir("", "")
463 return fmt.Errorf("While creating mount temp dir: %v", err)
465 st, staterr := os.Stat(tmpdir)
467 return fmt.Errorf("While Stat on temp dir: %v", staterr)
469 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
471 return fmt.Errorf("While Chmod temp dir: %v", err)
473 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
474 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", tmpdir, bind))
475 if bind == runner.Container.OutputPath {
476 runner.HostOutputDir = tmpdir
479 case mnt.Kind == "json":
480 jsondata, err := json.Marshal(mnt.Content)
482 return fmt.Errorf("encoding json data: %v", err)
484 // Create a tempdir with a single file
485 // (instead of just a tempfile): this way we
486 // can ensure the file is world-readable
487 // inside the container, without having to
488 // make it world-readable on the docker host.
489 tmpdir, err := runner.MkTempDir("", "")
491 return fmt.Errorf("creating temp dir: %v", err)
493 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
494 tmpfn := filepath.Join(tmpdir, "mountdata.json")
495 err = ioutil.WriteFile(tmpfn, jsondata, 0644)
497 return fmt.Errorf("writing temp file: %v", err)
499 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
503 if runner.HostOutputDir == "" {
504 return fmt.Errorf("Output path does not correspond to a writable mount point")
507 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
508 for _, certfile := range arvadosclient.CertFiles {
509 _, err := os.Stat(certfile)
511 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
518 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
520 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
522 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
524 token, err := runner.ContainerToken()
526 return fmt.Errorf("could not get container token: %s", err)
529 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
531 return fmt.Errorf("While trying to start arv-mount: %v", err)
534 for _, p := range collectionPaths {
537 return fmt.Errorf("While checking that input files exist: %v", err)
544 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
545 // Handle docker log protocol
546 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
548 header := make([]byte, 8)
550 _, readerr := io.ReadAtLeast(containerReader, header, 8)
553 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
556 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
559 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
564 if readerr != io.EOF {
565 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
568 closeerr := runner.Stdout.Close()
570 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
573 closeerr = runner.Stderr.Close()
575 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
578 if runner.statReporter != nil {
579 runner.statReporter.Stop()
580 closeerr = runner.statLogger.Close()
582 runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
586 runner.loggingDone <- true
587 close(runner.loggingDone)
593 func (runner *ContainerRunner) StartCrunchstat() {
594 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
595 runner.statReporter = &crunchstat.Reporter{
596 CID: runner.ContainerID,
597 Logger: log.New(runner.statLogger, "", 0),
598 CgroupParent: runner.expectCgroupParent,
599 CgroupRoot: runner.cgroupRoot,
600 PollPeriod: runner.statInterval,
602 runner.statReporter.Start()
605 type infoCommand struct {
610 // Gather node information and store it on the log for debugging
612 func (runner *ContainerRunner) LogNodeInfo() (err error) {
613 w := runner.NewLogWriter("node-info")
614 logger := log.New(w, "node-info", 0)
616 commands := []infoCommand{
618 label: "Host Information",
619 cmd: []string{"uname", "-a"},
622 label: "CPU Information",
623 cmd: []string{"cat", "/proc/cpuinfo"},
626 label: "Memory Information",
627 cmd: []string{"cat", "/proc/meminfo"},
631 cmd: []string{"df", "-m", "/", os.TempDir()},
634 label: "Disk INodes",
635 cmd: []string{"df", "-i", "/", os.TempDir()},
639 // Run commands with informational output to be logged.
641 for _, command := range commands {
642 out, err = exec.Command(command.cmd[0], command.cmd[1:]...).CombinedOutput()
644 return fmt.Errorf("While running command %q: %v",
647 logger.Println(command.label)
648 for _, line := range strings.Split(string(out), "\n") {
649 logger.Println(" ", line)
655 return fmt.Errorf("While closing node-info logs: %v", err)
660 // Get and save the raw JSON container record from the API server
661 func (runner *ContainerRunner) LogContainerRecord() (err error) {
663 ArvClient: runner.ArvClient,
664 UUID: runner.Container.UUID,
665 loggingStream: "container",
666 writeCloser: runner.LogCollection.Open("container.json"),
669 // Get Container record JSON from the API Server
670 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
672 return fmt.Errorf("While retrieving container record from the API server: %v", err)
676 dec := json.NewDecoder(reader)
678 var cr map[string]interface{}
679 if err = dec.Decode(&cr); err != nil {
680 return fmt.Errorf("While decoding the container record JSON response: %v", err)
682 // Re-encode it using indentation to improve readability
683 enc := json.NewEncoder(w)
684 enc.SetIndent("", " ")
685 if err = enc.Encode(cr); err != nil {
686 return fmt.Errorf("While logging the JSON container record: %v", err)
690 return fmt.Errorf("While closing container.json log: %v", err)
695 // AttachStreams connects the docker container stdin, stdout and stderr logs
696 // to the Arvados logger which logs to Keep and the API server logs table.
697 func (runner *ContainerRunner) AttachStreams() (err error) {
699 runner.CrunchLog.Print("Attaching container streams")
701 // If stdin mount is provided, attach it to the docker container
702 var stdinRdr arvados.File
704 if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
705 if stdinMnt.Kind == "collection" {
706 var stdinColl arvados.Collection
707 collId := stdinMnt.UUID
709 collId = stdinMnt.PortableDataHash
711 err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
713 return fmt.Errorf("While getting stding collection: %v", err)
716 stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
717 if os.IsNotExist(err) {
718 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
719 } else if err != nil {
720 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
722 } else if stdinMnt.Kind == "json" {
723 stdinJson, err = json.Marshal(stdinMnt.Content)
725 return fmt.Errorf("While encoding stdin json data: %v", err)
730 stdinUsed := stdinRdr != nil || len(stdinJson) != 0
731 response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
732 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
734 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
737 runner.loggingDone = make(chan bool)
739 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
740 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
744 runner.Stdout = stdoutFile
746 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
749 if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
750 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
754 runner.Stderr = stderrFile
756 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
761 _, err := io.Copy(response.Conn, stdinRdr)
763 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
767 response.CloseWrite()
769 } else if len(stdinJson) != 0 {
771 _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
773 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
776 response.CloseWrite()
780 go runner.ProcessDockerAttach(response.Reader)
785 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
786 stdoutPath := mntPath[len(runner.Container.OutputPath):]
787 index := strings.LastIndex(stdoutPath, "/")
789 subdirs := stdoutPath[:index]
791 st, err := os.Stat(runner.HostOutputDir)
793 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
795 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
796 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
798 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
802 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
804 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
807 return stdoutFile, nil
810 // CreateContainer creates the docker container.
811 func (runner *ContainerRunner) CreateContainer() error {
812 runner.CrunchLog.Print("Creating Docker container")
814 runner.ContainerConfig.Cmd = runner.Container.Command
815 if runner.Container.Cwd != "." {
816 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
819 for k, v := range runner.Container.Environment {
820 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
823 runner.ContainerConfig.Volumes = runner.Volumes
825 runner.HostConfig = dockercontainer.HostConfig{
827 LogConfig: dockercontainer.LogConfig{
830 Resources: dockercontainer.Resources{
831 CgroupParent: runner.setCgroupParent,
835 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
836 tok, err := runner.ContainerToken()
840 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
841 "ARVADOS_API_TOKEN="+tok,
842 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
843 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
845 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
847 if runner.enableNetwork == "always" {
848 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
850 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
854 _, stdinUsed := runner.Container.Mounts["stdin"]
855 runner.ContainerConfig.OpenStdin = stdinUsed
856 runner.ContainerConfig.StdinOnce = stdinUsed
857 runner.ContainerConfig.AttachStdin = stdinUsed
858 runner.ContainerConfig.AttachStdout = true
859 runner.ContainerConfig.AttachStderr = true
861 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
863 return fmt.Errorf("While creating container: %v", err)
866 runner.ContainerID = createdBody.ID
868 return runner.AttachStreams()
871 // StartContainer starts the docker container created by CreateContainer.
872 func (runner *ContainerRunner) StartContainer() error {
873 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
874 runner.cStateLock.Lock()
875 defer runner.cStateLock.Unlock()
876 if runner.cCancelled {
879 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
880 dockertypes.ContainerStartOptions{})
883 if strings.Contains(err.Error(), "no such file or directory") {
884 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])
886 return fmt.Errorf("could not start container: %v%s", err, advice)
888 runner.cStarted = true
892 // WaitFinish waits for the container to terminate, capture the exit code, and
893 // close the stdout/stderr logging.
894 func (runner *ContainerRunner) WaitFinish() (err error) {
895 runner.CrunchLog.Print("Waiting for container to finish")
897 waitOk, waitErr := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID, "not-running")
899 var waitBody dockercontainer.ContainerWaitOKBody
901 case waitBody = <-waitOk:
902 case err = <-waitErr:
906 return fmt.Errorf("container wait: %v", err)
909 runner.CrunchLog.Printf("Container exited with code: %v", waitBody.StatusCode)
910 code := int(waitBody.StatusCode)
911 runner.ExitCode = &code
913 waitMount := runner.ArvMountExit
915 case err = <-waitMount:
916 runner.CrunchLog.Printf("arv-mount exited before container finished: %v", err)
922 // wait for stdout/stderr to complete
928 var ErrNotInOutputDir = fmt.Errorf("Must point to path within the output directory")
930 func (runner *ContainerRunner) derefOutputSymlink(path string, startinfo os.FileInfo) (tgt string, readlinktgt string, info os.FileInfo, err error) {
931 // Follow symlinks if necessary
936 for followed := 0; info.Mode()&os.ModeSymlink != 0; followed++ {
937 if followed >= limitFollowSymlinks {
938 // Got stuck in a loop or just a pathological number of links, give up.
939 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
943 readlinktgt, err = os.Readlink(nextlink)
949 if !strings.HasPrefix(tgt, "/") {
950 // Relative symlink, resolve it to host path
951 tgt = filepath.Join(filepath.Dir(path), tgt)
953 if strings.HasPrefix(tgt, runner.Container.OutputPath+"/") && !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
954 // Absolute symlink to container output path, adjust it to host output path.
955 tgt = filepath.Join(runner.HostOutputDir, tgt[len(runner.Container.OutputPath):])
957 if !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
958 // After dereferencing, symlink target must either be
959 // within output directory, or must point to a
961 err = ErrNotInOutputDir
965 info, err = os.Lstat(tgt)
968 err = fmt.Errorf("Symlink in output %q points to invalid location %q: %v",
969 path[len(runner.HostOutputDir):], readlinktgt, err)
979 var limitFollowSymlinks = 10
981 // UploadFile uploads files within the output directory, with special handling
982 // for symlinks. If the symlink leads to a keep mount, copy the manifest text
983 // from the keep mount into the output manifestText. Ensure that whether
984 // symlinks are relative or absolute, every symlink target (even targets that
985 // are symlinks themselves) must point to a path in either the output directory
986 // or a collection mount.
988 // Assumes initial value of "path" is absolute, and located within runner.HostOutputDir.
989 func (runner *ContainerRunner) UploadOutputFile(
994 walkUpload *WalkUpload,
997 followed int) (manifestText string, err error) {
999 if info.Mode().IsDir() {
1007 if followed >= limitFollowSymlinks {
1008 // Got stuck in a loop or just a pathological number of
1009 // directory links, give up.
1010 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
1014 // When following symlinks, the source path may need to be logically
1015 // relocated to some other path within the output collection. Remove
1016 // the relocateFrom prefix and replace it with relocateTo.
1017 relocated := relocateTo + path[len(relocateFrom):]
1019 tgt, readlinktgt, info, derefErr := runner.derefOutputSymlink(path, info)
1020 if derefErr != nil && derefErr != ErrNotInOutputDir {
1024 // go through mounts and try reverse map to collection reference
1025 for _, bind := range binds {
1026 mnt := runner.Container.Mounts[bind]
1027 if tgt == bind || strings.HasPrefix(tgt, bind+"/") {
1028 // get path relative to bind
1029 targetSuffix := tgt[len(bind):]
1031 // Copy mount and adjust the path to add path relative to the bind
1032 adjustedMount := mnt
1033 adjustedMount.Path = filepath.Join(adjustedMount.Path, targetSuffix)
1035 // Terminates in this keep mount, so add the
1036 // manifest text at appropriate location.
1037 outputSuffix := path[len(runner.HostOutputDir):]
1038 manifestText, err = runner.getCollectionManifestForPath(adjustedMount, outputSuffix)
1043 // If target is not a collection mount, it must be located within the
1044 // output directory, otherwise it is an error.
1045 if derefErr == ErrNotInOutputDir {
1046 err = fmt.Errorf("Symlink in output %q points to invalid location %q, must point to path within the output directory.",
1047 path[len(runner.HostOutputDir):], readlinktgt)
1051 if info.Mode().IsRegular() {
1052 return "", walkUpload.UploadFile(relocated, tgt)
1055 if info.Mode().IsDir() {
1056 // Symlink leads to directory. Walk() doesn't follow
1057 // directory symlinks, so we walk the target directory
1058 // instead. Within the walk, file paths are relocated
1059 // so they appear under the original symlink path.
1060 err = filepath.Walk(tgt, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
1062 m, walkerr = runner.UploadOutputFile(walkpath, walkinfo, walkerr,
1063 binds, walkUpload, tgt, relocated, followed+1)
1065 manifestText = manifestText + m
1075 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
1076 func (runner *ContainerRunner) CaptureOutput() error {
1077 if runner.finalState != "Complete" {
1081 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
1082 // Output may have been set directly by the container, so
1083 // refresh the container record to check.
1084 err := runner.ArvClient.Get("containers", runner.Container.UUID,
1085 nil, &runner.Container)
1089 if runner.Container.Output != "" {
1090 // Container output is already set.
1091 runner.OutputPDH = &runner.Container.Output
1096 if runner.HostOutputDir == "" {
1100 _, err := os.Stat(runner.HostOutputDir)
1102 return fmt.Errorf("While checking host output path: %v", err)
1105 // Pre-populate output from the configured mount points
1107 for bind, mnt := range runner.Container.Mounts {
1108 if mnt.Kind == "collection" {
1109 binds = append(binds, bind)
1114 var manifestText string
1116 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
1117 _, err = os.Stat(collectionMetafile)
1119 // Regular directory
1121 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
1122 walkUpload := cw.BeginUpload(runner.HostOutputDir, runner.CrunchLog.Logger)
1125 err = filepath.Walk(runner.HostOutputDir, func(path string, info os.FileInfo, err error) error {
1126 m, err = runner.UploadOutputFile(path, info, err, binds, walkUpload, "", "", 0)
1128 manifestText = manifestText + m
1133 cw.EndUpload(walkUpload)
1136 return fmt.Errorf("While uploading output files: %v", err)
1139 m, err = cw.ManifestText()
1140 manifestText = manifestText + m
1142 return fmt.Errorf("While uploading output files: %v", err)
1145 // FUSE mount directory
1146 file, openerr := os.Open(collectionMetafile)
1148 return fmt.Errorf("While opening FUSE metafile: %v", err)
1152 var rec arvados.Collection
1153 err = json.NewDecoder(file).Decode(&rec)
1155 return fmt.Errorf("While reading FUSE metafile: %v", err)
1157 manifestText = rec.ManifestText
1160 for _, bind := range binds {
1161 mnt := runner.Container.Mounts[bind]
1163 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
1165 if bindSuffix == bind || len(bindSuffix) <= 0 {
1166 // either does not start with OutputPath or is OutputPath itself
1170 if mnt.ExcludeFromOutput == true {
1174 // append to manifest_text
1175 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
1180 manifestText = manifestText + m
1184 var response arvados.Collection
1185 manifest := manifest.Manifest{Text: manifestText}
1186 manifestText = manifest.Extract(".", ".").Text
1187 err = runner.ArvClient.Create("collections",
1189 "ensure_unique_name": true,
1190 "collection": arvadosclient.Dict{
1192 "name": "output for " + runner.Container.UUID,
1193 "manifest_text": manifestText}},
1196 return fmt.Errorf("While creating output collection: %v", err)
1198 runner.OutputPDH = &response.PortableDataHash
1202 var outputCollections = make(map[string]arvados.Collection)
1204 // Fetch the collection for the mnt.PortableDataHash
1205 // Return the manifest_text fragment corresponding to the specified mnt.Path
1206 // after making any required updates.
1208 // If mnt.Path is not specified,
1209 // return the entire manifest_text after replacing any "." with bindSuffix
1210 // If mnt.Path corresponds to one stream,
1211 // return the manifest_text for that stream after replacing that stream name with bindSuffix
1212 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1213 // for that stream after replacing stream name with bindSuffix minus the last word
1214 // and the file name with last word of the bindSuffix
1215 // Allowed path examples:
1217 // "path":"/subdir1"
1218 // "path":"/subdir1/subdir2"
1219 // "path":"/subdir/filename" etc
1220 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1221 collection := outputCollections[mnt.PortableDataHash]
1222 if collection.PortableDataHash == "" {
1223 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1225 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1227 outputCollections[mnt.PortableDataHash] = collection
1230 if collection.ManifestText == "" {
1231 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1235 mft := manifest.Manifest{Text: collection.ManifestText}
1236 extracted := mft.Extract(mnt.Path, bindSuffix)
1237 if extracted.Err != nil {
1238 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1240 return extracted.Text, nil
1243 func (runner *ContainerRunner) CleanupDirs() {
1244 if runner.ArvMount != nil {
1245 //umount := exec.Command("fusermount", "-u", runner.ArvMountPoint)
1246 umount := exec.Command("sleep", "1")
1247 umnterr := umount.Run()
1249 log.Printf("While running fusermount: %v", umnterr)
1251 timeout := time.NewTimer(10 * time.Second)
1253 case mnterr := <-runner.ArvMountExit:
1255 log.Printf("Arv-mount exit error: %v", mnterr)
1258 log.Printf("Timeout waiting for arv-mount to end. Killing arv-mount.")
1259 runner.arvMountKill()
1260 umount = exec.Command("arv-mount", "--unmount-timeout=10", "--unmount", runner.ArvMountPoint)
1261 umnterr = umount.Run()
1263 log.Printf("While running arv-mount --unmount: %v", umnterr)
1268 for _, tmpdir := range runner.CleanupTempDir {
1269 rmerr := os.RemoveAll(tmpdir)
1271 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1276 // CommitLogs posts the collection containing the final container logs.
1277 func (runner *ContainerRunner) CommitLogs() error {
1278 runner.CrunchLog.Print(runner.finalState)
1279 runner.CrunchLog.Close()
1281 // Closing CrunchLog above allows it to be committed to Keep at this
1282 // point, but re-open crunch log with ArvClient in case there are any
1283 // other further (such as failing to write the log to Keep!) while
1285 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1286 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1288 if runner.LogsPDH != nil {
1289 // If we have already assigned something to LogsPDH,
1290 // we must be closing the re-opened log, which won't
1291 // end up getting attached to the container record and
1292 // therefore doesn't need to be saved as a collection
1293 // -- it exists only to send logs to other channels.
1297 mt, err := runner.LogCollection.ManifestText()
1299 return fmt.Errorf("While creating log manifest: %v", err)
1302 var response arvados.Collection
1303 err = runner.ArvClient.Create("collections",
1305 "ensure_unique_name": true,
1306 "collection": arvadosclient.Dict{
1308 "name": "logs for " + runner.Container.UUID,
1309 "manifest_text": mt}},
1312 return fmt.Errorf("While creating log collection: %v", err)
1314 runner.LogsPDH = &response.PortableDataHash
1318 // UpdateContainerRunning updates the container state to "Running"
1319 func (runner *ContainerRunner) UpdateContainerRunning() error {
1320 runner.cStateLock.Lock()
1321 defer runner.cStateLock.Unlock()
1322 if runner.cCancelled {
1325 return runner.ArvClient.Update("containers", runner.Container.UUID,
1326 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1329 // ContainerToken returns the api_token the container (and any
1330 // arv-mount processes) are allowed to use.
1331 func (runner *ContainerRunner) ContainerToken() (string, error) {
1332 if runner.token != "" {
1333 return runner.token, nil
1336 var auth arvados.APIClientAuthorization
1337 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1341 runner.token = auth.APIToken
1342 return runner.token, nil
1345 // UpdateContainerComplete updates the container record state on API
1346 // server to "Complete" or "Cancelled"
1347 func (runner *ContainerRunner) UpdateContainerFinal() error {
1348 update := arvadosclient.Dict{}
1349 update["state"] = runner.finalState
1350 if runner.LogsPDH != nil {
1351 update["log"] = *runner.LogsPDH
1353 if runner.finalState == "Complete" {
1354 if runner.ExitCode != nil {
1355 update["exit_code"] = *runner.ExitCode
1357 if runner.OutputPDH != nil {
1358 update["output"] = *runner.OutputPDH
1361 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1364 // IsCancelled returns the value of Cancelled, with goroutine safety.
1365 func (runner *ContainerRunner) IsCancelled() bool {
1366 runner.cStateLock.Lock()
1367 defer runner.cStateLock.Unlock()
1368 return runner.cCancelled
1371 // NewArvLogWriter creates an ArvLogWriter
1372 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1373 return &ArvLogWriter{ArvClient: runner.ArvClient, UUID: runner.Container.UUID, loggingStream: name,
1374 writeCloser: runner.LogCollection.Open(name + ".txt")}
1377 // Run the full container lifecycle.
1378 func (runner *ContainerRunner) Run() (err error) {
1379 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1381 hostname, hosterr := os.Hostname()
1383 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1385 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1388 // Clean up temporary directories _after_ finalizing
1389 // everything (if we've made any by then)
1390 defer runner.CleanupDirs()
1392 runner.finalState = "Queued"
1395 // checkErr prints e (unless it's nil) and sets err to
1396 // e (unless err is already non-nil). Thus, if err
1397 // hasn't already been assigned when Run() returns,
1398 // this cleanup func will cause Run() to return the
1399 // first non-nil error that is passed to checkErr().
1400 checkErr := func(e error) {
1404 runner.CrunchLog.Print(e)
1408 if runner.finalState == "Complete" {
1409 // There was an error in the finalization.
1410 runner.finalState = "Cancelled"
1414 // Log the error encountered in Run(), if any
1417 if runner.finalState == "Queued" {
1418 runner.CrunchLog.Close()
1419 runner.UpdateContainerFinal()
1423 if runner.IsCancelled() {
1424 runner.finalState = "Cancelled"
1425 // but don't return yet -- we still want to
1426 // capture partial output and write logs
1429 checkErr(runner.CaptureOutput())
1430 checkErr(runner.CommitLogs())
1431 checkErr(runner.UpdateContainerFinal())
1433 // The real log is already closed, but then we opened
1434 // a new one in case we needed to log anything while
1436 runner.CrunchLog.Close()
1441 err = runner.fetchContainerRecord()
1446 // setup signal handling
1447 runner.setupSignals()
1449 // check for and/or load image
1450 err = runner.LoadImage()
1452 runner.finalState = "Cancelled"
1453 err = fmt.Errorf("While loading container image: %v", err)
1457 // set up FUSE mount and binds
1458 err = runner.SetupMounts()
1460 runner.finalState = "Cancelled"
1461 err = fmt.Errorf("While setting up mounts: %v", err)
1465 err = runner.CreateContainer()
1470 // Gather and record node information
1471 err = runner.LogNodeInfo()
1475 // Save container.json record on log collection
1476 err = runner.LogContainerRecord()
1481 runner.StartCrunchstat()
1483 if runner.IsCancelled() {
1487 err = runner.UpdateContainerRunning()
1491 runner.finalState = "Cancelled"
1493 err = runner.StartContainer()
1498 err = runner.WaitFinish()
1500 runner.finalState = "Complete"
1505 // Fetch the current container record (uuid = runner.Container.UUID)
1506 // into runner.Container.
1507 func (runner *ContainerRunner) fetchContainerRecord() error {
1508 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1510 return fmt.Errorf("error fetching container record: %v", err)
1512 defer reader.Close()
1514 dec := json.NewDecoder(reader)
1516 err = dec.Decode(&runner.Container)
1518 return fmt.Errorf("error decoding container record: %v", err)
1523 // NewContainerRunner creates a new container runner.
1524 func NewContainerRunner(api IArvadosClient,
1526 docker ThinDockerClient,
1527 containerUUID string) *ContainerRunner {
1529 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1530 cr.NewLogWriter = cr.NewArvLogWriter
1531 cr.RunArvMount = cr.ArvMountCmd
1532 cr.MkTempDir = ioutil.TempDir
1533 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1534 cr.Container.UUID = containerUUID
1535 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1536 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1538 loadLogThrottleParams(api)
1544 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1545 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1546 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1547 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1548 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1549 enableNetwork := flag.String("container-enable-networking", "default",
1550 `Specify if networking should be enabled for container. One of 'default', 'always':
1551 default: only enable networking if container requests it.
1552 always: containers always have networking enabled
1554 networkMode := flag.String("container-network-mode", "default",
1555 `Set networking mode for container. Corresponds to Docker network mode (--net).
1557 memprofile := flag.String("memprofile", "", "write memory profile to `file` after running container")
1560 containerId := flag.Arg(0)
1562 if *caCertsPath != "" {
1563 arvadosclient.CertFiles = []string{*caCertsPath}
1566 api, err := arvadosclient.MakeArvadosClient()
1568 log.Fatalf("%s: %v", containerId, err)
1572 var kc *keepclient.KeepClient
1573 kc, err = keepclient.MakeKeepClient(api)
1575 log.Fatalf("%s: %v", containerId, err)
1577 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1580 var docker *dockerclient.Client
1581 // API version 1.21 corresponds to Docker 1.9, which is currently the
1582 // minimum version we want to support.
1583 docker, err = dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1585 log.Fatalf("%s: %v", containerId, err)
1588 dockerClientProxy := ThinDockerClientProxy{Docker: docker}
1590 cr := NewContainerRunner(api, kc, dockerClientProxy, containerId)
1591 cr.statInterval = *statInterval
1592 cr.cgroupRoot = *cgroupRoot
1593 cr.expectCgroupParent = *cgroupParent
1594 cr.enableNetwork = *enableNetwork
1595 cr.networkMode = *networkMode
1596 if *cgroupParentSubsystem != "" {
1597 p := findCgroup(*cgroupParentSubsystem)
1598 cr.setCgroupParent = p
1599 cr.expectCgroupParent = p
1604 if *memprofile != "" {
1605 f, err := os.Create(*memprofile)
1607 log.Printf("could not create memory profile: ", err)
1609 runtime.GC() // get up-to-date statistics
1610 if err := pprof.WriteHeapProfile(f); err != nil {
1611 log.Printf("could not write memory profile: ", err)
1613 closeerr := f.Close()
1614 if closeerr != nil {
1615 log.Printf("closing memprofile file: ", err)
1620 log.Fatalf("%s: %v", containerId, runerr)