1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
28 "git.curoverse.com/arvados.git/lib/crunchstat"
29 "git.curoverse.com/arvados.git/sdk/go/arvados"
30 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
31 "git.curoverse.com/arvados.git/sdk/go/keepclient"
32 "git.curoverse.com/arvados.git/sdk/go/manifest"
34 dockertypes "github.com/docker/docker/api/types"
35 dockercontainer "github.com/docker/docker/api/types/container"
36 dockernetwork "github.com/docker/docker/api/types/network"
37 dockerclient "github.com/docker/docker/client"
40 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
41 type IArvadosClient interface {
42 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
43 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
44 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
45 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
46 CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
47 Discovery(key string) (interface{}, error)
50 // ErrCancelled is the error returned when the container is cancelled.
51 var ErrCancelled = errors.New("Cancelled")
53 // IKeepClient is the minimal Keep API methods used by crunch-run.
54 type IKeepClient interface {
55 PutHB(hash string, buf []byte) (string, int, error)
56 ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error)
59 // NewLogWriter is a factory function to create a new log writer.
60 type NewLogWriter func(name string) io.WriteCloser
62 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
64 type MkTempDir func(string, string) (string, error)
66 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
67 type ThinDockerClient interface {
68 ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error)
69 ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
70 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error)
71 ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error
72 ContainerStop(ctx context.Context, container string, timeout *time.Duration) error
73 ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error)
74 ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error)
75 ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error)
76 ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error)
79 // ThinDockerClientProxy is a proxy implementation of ThinDockerClient
80 // that executes the docker requests on dockerclient.Client
81 type ThinDockerClientProxy struct {
82 Docker *dockerclient.Client
85 // ContainerAttach invokes dockerclient.Client.ContainerAttach
86 func (proxy ThinDockerClientProxy) ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error) {
87 return proxy.Docker.ContainerAttach(ctx, container, options)
90 // ContainerCreate invokes dockerclient.Client.ContainerCreate
91 func (proxy ThinDockerClientProxy) ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
92 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error) {
93 return proxy.Docker.ContainerCreate(ctx, config, hostConfig, networkingConfig, containerName)
96 // ContainerStart invokes dockerclient.Client.ContainerStart
97 func (proxy ThinDockerClientProxy) ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error {
98 return proxy.Docker.ContainerStart(ctx, container, options)
101 // ContainerStop invokes dockerclient.Client.ContainerStop
102 func (proxy ThinDockerClientProxy) ContainerStop(ctx context.Context, container string, timeout *time.Duration) error {
103 return proxy.Docker.ContainerStop(ctx, container, timeout)
106 // ContainerWait invokes dockerclient.Client.ContainerWait
107 func (proxy ThinDockerClientProxy) ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error) {
108 return proxy.Docker.ContainerWait(ctx, container, condition)
111 // ImageInspectWithRaw invokes dockerclient.Client.ImageInspectWithRaw
112 func (proxy ThinDockerClientProxy) ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error) {
113 return proxy.Docker.ImageInspectWithRaw(ctx, image)
116 // ImageLoad invokes dockerclient.Client.ImageLoad
117 func (proxy ThinDockerClientProxy) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error) {
118 return proxy.Docker.ImageLoad(ctx, input, quiet)
121 // ImageRemove invokes dockerclient.Client.ImageRemove
122 func (proxy ThinDockerClientProxy) ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {
123 return proxy.Docker.ImageRemove(ctx, image, options)
126 // ContainerRunner is the main stateful struct used for a single execution of a
128 type ContainerRunner struct {
129 Docker ThinDockerClient
130 ArvClient IArvadosClient
133 ContainerConfig dockercontainer.Config
134 dockercontainer.HostConfig
139 loggingDone chan bool
140 CrunchLog *ThrottledLogger
141 Stdout io.WriteCloser
142 Stderr io.WriteCloser
143 LogCollection *CollectionWriter
150 CleanupTempDir []string
152 Volumes map[string]struct{}
154 SigChan chan os.Signal
155 ArvMountExit chan error
158 statLogger io.WriteCloser
159 statReporter *crunchstat.Reporter
160 statInterval time.Duration
162 // What we expect the container's cgroup parent to be.
163 expectCgroupParent string
164 // What we tell docker to use as the container's cgroup
165 // parent. Note: Ideally we would use the same field for both
166 // expectCgroupParent and setCgroupParent, and just make it
167 // default to "docker". However, when using docker < 1.10 with
168 // systemd, specifying a non-empty cgroup parent (even the
169 // default value "docker") hits a docker bug
170 // (https://github.com/docker/docker/issues/17126). Using two
171 // separate fields makes it possible to use the "expect cgroup
172 // parent to be X" feature even on sites where the "specify
173 // cgroup parent" feature breaks.
174 setCgroupParent string
176 cStateLock sync.Mutex
177 cStarted bool // StartContainer() succeeded
178 cCancelled bool // StopContainer() invoked
180 enableNetwork string // one of "default" or "always"
181 networkMode string // passed through to HostConfig.NetworkMode
184 // SetupSignals sets up signal handling to gracefully terminate the underlying
185 // Docker container and update state when receiving a TERM, INT or QUIT signal.
186 func (runner *ContainerRunner) SetupSignals() {
187 runner.SigChan = make(chan os.Signal, 1)
188 signal.Notify(runner.SigChan, syscall.SIGTERM)
189 signal.Notify(runner.SigChan, syscall.SIGINT)
190 signal.Notify(runner.SigChan, syscall.SIGQUIT)
192 go func(sig chan os.Signal) {
199 // stop the underlying Docker container.
200 func (runner *ContainerRunner) stop() {
201 runner.cStateLock.Lock()
202 defer runner.cStateLock.Unlock()
203 if runner.cCancelled {
206 runner.cCancelled = true
208 timeout := time.Duration(10)
209 err := runner.Docker.ContainerStop(context.TODO(), runner.ContainerID, &(timeout))
211 log.Printf("StopContainer failed: %s", err)
216 // LoadImage determines the docker image id from the container record and
217 // checks if it is available in the local Docker image store. If not, it loads
218 // the image from Keep.
219 func (runner *ContainerRunner) LoadImage() (err error) {
221 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
223 var collection arvados.Collection
224 err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
226 return fmt.Errorf("While getting container image collection: %v", err)
228 manifest := manifest.Manifest{Text: collection.ManifestText}
229 var img, imageID string
230 for ms := range manifest.StreamIter() {
231 img = ms.FileStreamSegments[0].Name
232 if !strings.HasSuffix(img, ".tar") {
233 return fmt.Errorf("First file in the container image collection does not end in .tar")
235 imageID = img[:len(img)-4]
238 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
240 _, _, err = runner.Docker.ImageInspectWithRaw(context.TODO(), imageID)
242 runner.CrunchLog.Print("Loading Docker image from keep")
244 var readCloser io.ReadCloser
245 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
247 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
250 response, err := runner.Docker.ImageLoad(context.TODO(), readCloser, false)
252 return fmt.Errorf("While loading container image into Docker: %v", err)
254 response.Body.Close()
256 runner.CrunchLog.Print("Docker image is available")
259 runner.ContainerConfig.Image = imageID
264 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
265 c = exec.Command("arv-mount", arvMountCmd...)
267 // Copy our environment, but override ARVADOS_API_TOKEN with
268 // the container auth token.
270 for _, s := range os.Environ() {
271 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
272 c.Env = append(c.Env, s)
275 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
277 nt := NewThrottledLogger(runner.NewLogWriter("arv-mount"))
286 statReadme := make(chan bool)
287 runner.ArvMountExit = make(chan error)
292 time.Sleep(100 * time.Millisecond)
293 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
303 runner.ArvMountExit <- c.Wait()
304 close(runner.ArvMountExit)
310 case err := <-runner.ArvMountExit:
311 runner.ArvMount = nil
319 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
320 if runner.ArvMountPoint == "" {
321 runner.ArvMountPoint, err = runner.MkTempDir("", prefix)
326 func (runner *ContainerRunner) SetupMounts() (err error) {
327 err = runner.SetupArvMountPoint("keep")
329 return fmt.Errorf("While creating keep mount temp dir: %v", err)
332 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.ArvMountPoint)
336 arvMountCmd := []string{"--foreground", "--allow-other", "--read-write"}
338 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
339 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
342 collectionPaths := []string{}
344 runner.Volumes = make(map[string]struct{})
345 needCertMount := true
348 for bind, _ := range runner.Container.Mounts {
349 binds = append(binds, bind)
353 for _, bind := range binds {
354 mnt := runner.Container.Mounts[bind]
355 if bind == "stdout" || bind == "stderr" {
356 // Is it a "file" mount kind?
357 if mnt.Kind != "file" {
358 return fmt.Errorf("Unsupported mount kind '%s' for %s. Only 'file' is supported.", mnt.Kind, bind)
361 // Does path start with OutputPath?
362 prefix := runner.Container.OutputPath
363 if !strings.HasSuffix(prefix, "/") {
366 if !strings.HasPrefix(mnt.Path, prefix) {
367 return fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
372 // Is it a "collection" mount kind?
373 if mnt.Kind != "collection" && mnt.Kind != "json" {
374 return fmt.Errorf("Unsupported mount kind '%s' for stdin. Only 'collection' or 'json' are supported.", mnt.Kind)
378 if bind == "/etc/arvados/ca-certificates.crt" {
379 needCertMount = false
382 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
383 if mnt.Kind != "collection" {
384 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
389 case mnt.Kind == "collection" && bind != "stdin":
391 if mnt.UUID != "" && mnt.PortableDataHash != "" {
392 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
396 return fmt.Errorf("Writing to existing collections currently not permitted.")
399 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
400 } else if mnt.PortableDataHash != "" {
402 return fmt.Errorf("Can never write to a collection specified by portable data hash")
404 idx := strings.Index(mnt.PortableDataHash, "/")
406 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
407 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
408 runner.Container.Mounts[bind] = mnt
410 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
411 if mnt.Path != "" && mnt.Path != "." {
412 if strings.HasPrefix(mnt.Path, "./") {
413 mnt.Path = mnt.Path[2:]
414 } else if strings.HasPrefix(mnt.Path, "/") {
415 mnt.Path = mnt.Path[1:]
417 src += "/" + mnt.Path
420 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
421 arvMountCmd = append(arvMountCmd, "--mount-tmp")
422 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
426 if bind == runner.Container.OutputPath {
427 runner.HostOutputDir = src
428 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
429 return fmt.Errorf("Writable mount points are not permitted underneath the output_path: %v", bind)
431 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
433 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
435 collectionPaths = append(collectionPaths, src)
437 case mnt.Kind == "tmp":
439 tmpdir, err = runner.MkTempDir("", "")
441 return fmt.Errorf("While creating mount temp dir: %v", err)
443 st, staterr := os.Stat(tmpdir)
445 return fmt.Errorf("While Stat on temp dir: %v", staterr)
447 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
449 return fmt.Errorf("While Chmod temp dir: %v", err)
451 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
452 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", tmpdir, bind))
453 if bind == runner.Container.OutputPath {
454 runner.HostOutputDir = tmpdir
457 case mnt.Kind == "json":
458 jsondata, err := json.Marshal(mnt.Content)
460 return fmt.Errorf("encoding json data: %v", err)
462 // Create a tempdir with a single file
463 // (instead of just a tempfile): this way we
464 // can ensure the file is world-readable
465 // inside the container, without having to
466 // make it world-readable on the docker host.
467 tmpdir, err := runner.MkTempDir("", "")
469 return fmt.Errorf("creating temp dir: %v", err)
471 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
472 tmpfn := filepath.Join(tmpdir, "mountdata.json")
473 err = ioutil.WriteFile(tmpfn, jsondata, 0644)
475 return fmt.Errorf("writing temp file: %v", err)
477 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
481 if runner.HostOutputDir == "" {
482 return fmt.Errorf("Output path does not correspond to a writable mount point")
485 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
486 for _, certfile := range arvadosclient.CertFiles {
487 _, err := os.Stat(certfile)
489 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
496 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
498 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
500 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
502 token, err := runner.ContainerToken()
504 return fmt.Errorf("could not get container token: %s", err)
507 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
509 return fmt.Errorf("While trying to start arv-mount: %v", err)
512 for _, p := range collectionPaths {
515 return fmt.Errorf("While checking that input files exist: %v", err)
522 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
523 // Handle docker log protocol
524 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
526 header := make([]byte, 8)
528 _, readerr := io.ReadAtLeast(containerReader, header, 8)
531 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
534 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
537 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
542 if readerr != io.EOF {
543 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
546 closeerr := runner.Stdout.Close()
548 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
551 closeerr = runner.Stderr.Close()
553 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
556 if runner.statReporter != nil {
557 runner.statReporter.Stop()
558 closeerr = runner.statLogger.Close()
560 runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
564 runner.loggingDone <- true
565 close(runner.loggingDone)
571 func (runner *ContainerRunner) StartCrunchstat() {
572 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
573 runner.statReporter = &crunchstat.Reporter{
574 CID: runner.ContainerID,
575 Logger: log.New(runner.statLogger, "", 0),
576 CgroupParent: runner.expectCgroupParent,
577 CgroupRoot: runner.cgroupRoot,
578 PollPeriod: runner.statInterval,
580 runner.statReporter.Start()
583 type infoCommand struct {
588 // Gather node information and store it on the log for debugging
590 func (runner *ContainerRunner) LogNodeInfo() (err error) {
591 w := runner.NewLogWriter("node-info")
592 logger := log.New(w, "node-info", 0)
594 commands := []infoCommand{
596 label: "Host Information",
597 cmd: []string{"uname", "-a"},
600 label: "CPU Information",
601 cmd: []string{"cat", "/proc/cpuinfo"},
604 label: "Memory Information",
605 cmd: []string{"cat", "/proc/meminfo"},
609 cmd: []string{"df", "-m", "/", os.TempDir()},
612 label: "Disk INodes",
613 cmd: []string{"df", "-i", "/", os.TempDir()},
617 // Run commands with informational output to be logged.
619 for _, command := range commands {
620 out, err = exec.Command(command.cmd[0], command.cmd[1:]...).CombinedOutput()
622 return fmt.Errorf("While running command %q: %v",
625 logger.Println(command.label)
626 for _, line := range strings.Split(string(out), "\n") {
627 logger.Println(" ", line)
633 return fmt.Errorf("While closing node-info logs: %v", err)
638 // Get and save the raw JSON container record from the API server
639 func (runner *ContainerRunner) LogContainerRecord() (err error) {
641 ArvClient: runner.ArvClient,
642 UUID: runner.Container.UUID,
643 loggingStream: "container",
644 writeCloser: runner.LogCollection.Open("container.json"),
647 // Get Container record JSON from the API Server
648 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
650 return fmt.Errorf("While retrieving container record from the API server: %v", err)
653 // Read the API server response as []byte
654 json_bytes, err := ioutil.ReadAll(reader)
656 return fmt.Errorf("While reading container record API server response: %v", err)
658 // Decode the JSON []byte
659 var cr map[string]interface{}
660 if err = json.Unmarshal(json_bytes, &cr); err != nil {
661 return fmt.Errorf("While decoding the container record JSON response: %v", err)
663 // Re-encode it using indentation to improve readability
664 enc := json.NewEncoder(w)
665 enc.SetIndent("", " ")
666 if err = enc.Encode(cr); err != nil {
667 return fmt.Errorf("While logging the JSON container record: %v", err)
671 return fmt.Errorf("While closing container.json log: %v", err)
676 // AttachStreams connects the docker container stdin, stdout and stderr logs
677 // to the Arvados logger which logs to Keep and the API server logs table.
678 func (runner *ContainerRunner) AttachStreams() (err error) {
680 runner.CrunchLog.Print("Attaching container streams")
682 // If stdin mount is provided, attach it to the docker container
683 var stdinRdr arvados.File
685 if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
686 if stdinMnt.Kind == "collection" {
687 var stdinColl arvados.Collection
688 collId := stdinMnt.UUID
690 collId = stdinMnt.PortableDataHash
692 err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
694 return fmt.Errorf("While getting stding collection: %v", err)
697 stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
698 if os.IsNotExist(err) {
699 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
700 } else if err != nil {
701 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
703 } else if stdinMnt.Kind == "json" {
704 stdinJson, err = json.Marshal(stdinMnt.Content)
706 return fmt.Errorf("While encoding stdin json data: %v", err)
711 stdinUsed := stdinRdr != nil || len(stdinJson) != 0
712 response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
713 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
715 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
718 runner.loggingDone = make(chan bool)
720 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
721 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
725 runner.Stdout = stdoutFile
727 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
730 if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
731 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
735 runner.Stderr = stderrFile
737 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
742 _, err := io.Copy(response.Conn, stdinRdr)
744 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
748 response.CloseWrite()
750 } else if len(stdinJson) != 0 {
752 _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
754 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
757 response.CloseWrite()
761 go runner.ProcessDockerAttach(response.Reader)
766 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
767 stdoutPath := mntPath[len(runner.Container.OutputPath):]
768 index := strings.LastIndex(stdoutPath, "/")
770 subdirs := stdoutPath[:index]
772 st, err := os.Stat(runner.HostOutputDir)
774 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
776 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
777 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
779 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
783 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
785 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
788 return stdoutFile, nil
791 // CreateContainer creates the docker container.
792 func (runner *ContainerRunner) CreateContainer() error {
793 runner.CrunchLog.Print("Creating Docker container")
795 runner.ContainerConfig.Cmd = runner.Container.Command
796 if runner.Container.Cwd != "." {
797 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
800 for k, v := range runner.Container.Environment {
801 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
804 runner.ContainerConfig.Volumes = runner.Volumes
806 runner.HostConfig = dockercontainer.HostConfig{
808 LogConfig: dockercontainer.LogConfig{
811 Resources: dockercontainer.Resources{
812 CgroupParent: runner.setCgroupParent,
816 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
817 tok, err := runner.ContainerToken()
821 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
822 "ARVADOS_API_TOKEN="+tok,
823 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
824 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
826 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
828 if runner.enableNetwork == "always" {
829 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
831 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
835 _, stdinUsed := runner.Container.Mounts["stdin"]
836 runner.ContainerConfig.OpenStdin = stdinUsed
837 runner.ContainerConfig.StdinOnce = stdinUsed
838 runner.ContainerConfig.AttachStdin = stdinUsed
839 runner.ContainerConfig.AttachStdout = true
840 runner.ContainerConfig.AttachStderr = true
842 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
844 return fmt.Errorf("While creating container: %v", err)
847 runner.ContainerID = createdBody.ID
849 return runner.AttachStreams()
852 // StartContainer starts the docker container created by CreateContainer.
853 func (runner *ContainerRunner) StartContainer() error {
854 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
855 runner.cStateLock.Lock()
856 defer runner.cStateLock.Unlock()
857 if runner.cCancelled {
860 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
861 dockertypes.ContainerStartOptions{})
863 return fmt.Errorf("could not start container: %v", err)
865 runner.cStarted = true
869 // WaitFinish waits for the container to terminate, capture the exit code, and
870 // close the stdout/stderr logging.
871 func (runner *ContainerRunner) WaitFinish() (err error) {
872 runner.CrunchLog.Print("Waiting for container to finish")
874 waitOk, waitErr := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID, "not-running")
876 var waitBody dockercontainer.ContainerWaitOKBody
878 case waitBody = <-waitOk:
879 case err = <-waitErr:
883 return fmt.Errorf("container wait: %v", err)
886 runner.CrunchLog.Printf("Container exited with code: %v", waitBody.StatusCode)
887 code := int(waitBody.StatusCode)
888 runner.ExitCode = &code
890 waitMount := runner.ArvMountExit
892 case err = <-waitMount:
893 runner.CrunchLog.Printf("arv-mount exited before container finished: %v", err)
899 // wait for stdout/stderr to complete
905 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
906 func (runner *ContainerRunner) CaptureOutput() error {
907 if runner.finalState != "Complete" {
911 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
912 // Output may have been set directly by the container, so
913 // refresh the container record to check.
914 err := runner.ArvClient.Get("containers", runner.Container.UUID,
915 nil, &runner.Container)
919 if runner.Container.Output != "" {
920 // Container output is already set.
921 runner.OutputPDH = &runner.Container.Output
926 if runner.HostOutputDir == "" {
930 _, err := os.Stat(runner.HostOutputDir)
932 return fmt.Errorf("While checking host output path: %v", err)
935 // Pre-populate output from the configured mount points
937 for bind, mnt := range runner.Container.Mounts {
938 if mnt.Kind == "collection" {
939 binds = append(binds, bind)
944 var manifestText string
946 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
947 _, err = os.Stat(collectionMetafile)
951 // Find symlinks to arv-mounted files & dirs.
952 err = filepath.Walk(runner.HostOutputDir, func(path string, info os.FileInfo, err error) error {
956 if info.Mode()&os.ModeSymlink == 0 {
959 // read link to get container internal path
960 // only support 1 level of symlinking here.
962 tgt, err = os.Readlink(path)
967 // get path relative to output dir
968 outputSuffix := path[len(runner.HostOutputDir):]
970 if strings.HasPrefix(tgt, "/") {
971 // go through mounts and try reverse map to collection reference
972 for _, bind := range binds {
973 mnt := runner.Container.Mounts[bind]
974 if tgt == bind || strings.HasPrefix(tgt, bind+"/") {
975 // get path relative to bind
976 targetSuffix := tgt[len(bind):]
978 // Copy mount and adjust the path to add path relative to the bind
980 adjustedMount.Path = filepath.Join(adjustedMount.Path, targetSuffix)
984 m, err = runner.getCollectionManifestForPath(adjustedMount, outputSuffix)
988 manifestText = manifestText + m
989 // delete symlink so WriteTree won't try to to dereference it.
996 // Not a link to a mount. Must be dereferencible and
997 // point into the output directory.
998 tgt, err = filepath.EvalSymlinks(path)
1004 // Symlink target must be within the output directory otherwise it's an error.
1005 if !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
1007 return fmt.Errorf("Output directory symlink %q points to invalid location %q, must point to mount or output directory.",
1013 return fmt.Errorf("While checking output symlinks: %v", err)
1016 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
1018 m, err = cw.WriteTree(runner.HostOutputDir, runner.CrunchLog.Logger)
1019 manifestText = manifestText + m
1021 return fmt.Errorf("While uploading output files: %v", err)
1024 // FUSE mount directory
1025 file, openerr := os.Open(collectionMetafile)
1027 return fmt.Errorf("While opening FUSE metafile: %v", err)
1031 var rec arvados.Collection
1032 err = json.NewDecoder(file).Decode(&rec)
1034 return fmt.Errorf("While reading FUSE metafile: %v", err)
1036 manifestText = rec.ManifestText
1039 for _, bind := range binds {
1040 mnt := runner.Container.Mounts[bind]
1042 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
1044 if bindSuffix == bind || len(bindSuffix) <= 0 {
1045 // either does not start with OutputPath or is OutputPath itself
1049 if mnt.ExcludeFromOutput == true {
1053 // append to manifest_text
1054 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
1059 manifestText = manifestText + m
1063 var response arvados.Collection
1064 manifest := manifest.Manifest{Text: manifestText}
1065 manifestText = manifest.Extract(".", ".").Text
1066 err = runner.ArvClient.Create("collections",
1068 "ensure_unique_name": true,
1069 "collection": arvadosclient.Dict{
1071 "name": "output for " + runner.Container.UUID,
1072 "manifest_text": manifestText}},
1075 return fmt.Errorf("While creating output collection: %v", err)
1077 runner.OutputPDH = &response.PortableDataHash
1081 var outputCollections = make(map[string]arvados.Collection)
1083 // Fetch the collection for the mnt.PortableDataHash
1084 // Return the manifest_text fragment corresponding to the specified mnt.Path
1085 // after making any required updates.
1087 // If mnt.Path is not specified,
1088 // return the entire manifest_text after replacing any "." with bindSuffix
1089 // If mnt.Path corresponds to one stream,
1090 // return the manifest_text for that stream after replacing that stream name with bindSuffix
1091 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1092 // for that stream after replacing stream name with bindSuffix minus the last word
1093 // and the file name with last word of the bindSuffix
1094 // Allowed path examples:
1096 // "path":"/subdir1"
1097 // "path":"/subdir1/subdir2"
1098 // "path":"/subdir/filename" etc
1099 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1100 collection := outputCollections[mnt.PortableDataHash]
1101 if collection.PortableDataHash == "" {
1102 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1104 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1106 outputCollections[mnt.PortableDataHash] = collection
1109 if collection.ManifestText == "" {
1110 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1114 mft := manifest.Manifest{Text: collection.ManifestText}
1115 extracted := mft.Extract(mnt.Path, bindSuffix)
1116 if extracted.Err != nil {
1117 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1119 return extracted.Text, nil
1122 func (runner *ContainerRunner) CleanupDirs() {
1123 if runner.ArvMount != nil {
1124 umount := exec.Command("fusermount", "-z", "-u", runner.ArvMountPoint)
1125 umnterr := umount.Run()
1127 runner.CrunchLog.Printf("While running fusermount: %v", umnterr)
1130 mnterr := <-runner.ArvMountExit
1132 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
1136 for _, tmpdir := range runner.CleanupTempDir {
1137 rmerr := os.RemoveAll(tmpdir)
1139 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1144 // CommitLogs posts the collection containing the final container logs.
1145 func (runner *ContainerRunner) CommitLogs() error {
1146 runner.CrunchLog.Print(runner.finalState)
1147 runner.CrunchLog.Close()
1149 // Closing CrunchLog above allows it to be committed to Keep at this
1150 // point, but re-open crunch log with ArvClient in case there are any
1151 // other further (such as failing to write the log to Keep!) while
1153 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1154 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1156 if runner.LogsPDH != nil {
1157 // If we have already assigned something to LogsPDH,
1158 // we must be closing the re-opened log, which won't
1159 // end up getting attached to the container record and
1160 // therefore doesn't need to be saved as a collection
1161 // -- it exists only to send logs to other channels.
1165 mt, err := runner.LogCollection.ManifestText()
1167 return fmt.Errorf("While creating log manifest: %v", err)
1170 var response arvados.Collection
1171 err = runner.ArvClient.Create("collections",
1173 "ensure_unique_name": true,
1174 "collection": arvadosclient.Dict{
1176 "name": "logs for " + runner.Container.UUID,
1177 "manifest_text": mt}},
1180 return fmt.Errorf("While creating log collection: %v", err)
1182 runner.LogsPDH = &response.PortableDataHash
1186 // UpdateContainerRunning updates the container state to "Running"
1187 func (runner *ContainerRunner) UpdateContainerRunning() error {
1188 runner.cStateLock.Lock()
1189 defer runner.cStateLock.Unlock()
1190 if runner.cCancelled {
1193 return runner.ArvClient.Update("containers", runner.Container.UUID,
1194 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1197 // ContainerToken returns the api_token the container (and any
1198 // arv-mount processes) are allowed to use.
1199 func (runner *ContainerRunner) ContainerToken() (string, error) {
1200 if runner.token != "" {
1201 return runner.token, nil
1204 var auth arvados.APIClientAuthorization
1205 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1209 runner.token = auth.APIToken
1210 return runner.token, nil
1213 // UpdateContainerComplete updates the container record state on API
1214 // server to "Complete" or "Cancelled"
1215 func (runner *ContainerRunner) UpdateContainerFinal() error {
1216 update := arvadosclient.Dict{}
1217 update["state"] = runner.finalState
1218 if runner.LogsPDH != nil {
1219 update["log"] = *runner.LogsPDH
1221 if runner.finalState == "Complete" {
1222 if runner.ExitCode != nil {
1223 update["exit_code"] = *runner.ExitCode
1225 if runner.OutputPDH != nil {
1226 update["output"] = *runner.OutputPDH
1229 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1232 // IsCancelled returns the value of Cancelled, with goroutine safety.
1233 func (runner *ContainerRunner) IsCancelled() bool {
1234 runner.cStateLock.Lock()
1235 defer runner.cStateLock.Unlock()
1236 return runner.cCancelled
1239 // NewArvLogWriter creates an ArvLogWriter
1240 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1241 return &ArvLogWriter{ArvClient: runner.ArvClient, UUID: runner.Container.UUID, loggingStream: name,
1242 writeCloser: runner.LogCollection.Open(name + ".txt")}
1245 // Run the full container lifecycle.
1246 func (runner *ContainerRunner) Run() (err error) {
1247 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1249 hostname, hosterr := os.Hostname()
1251 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1253 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1256 // Clean up temporary directories _after_ finalizing
1257 // everything (if we've made any by then)
1258 defer runner.CleanupDirs()
1260 runner.finalState = "Queued"
1263 // checkErr prints e (unless it's nil) and sets err to
1264 // e (unless err is already non-nil). Thus, if err
1265 // hasn't already been assigned when Run() returns,
1266 // this cleanup func will cause Run() to return the
1267 // first non-nil error that is passed to checkErr().
1268 checkErr := func(e error) {
1272 runner.CrunchLog.Print(e)
1276 if runner.finalState == "Complete" {
1277 // There was an error in the finalization.
1278 runner.finalState = "Cancelled"
1282 // Log the error encountered in Run(), if any
1285 if runner.finalState == "Queued" {
1286 runner.CrunchLog.Close()
1287 runner.UpdateContainerFinal()
1291 if runner.IsCancelled() {
1292 runner.finalState = "Cancelled"
1293 // but don't return yet -- we still want to
1294 // capture partial output and write logs
1297 checkErr(runner.CaptureOutput())
1298 checkErr(runner.CommitLogs())
1299 checkErr(runner.UpdateContainerFinal())
1301 // The real log is already closed, but then we opened
1302 // a new one in case we needed to log anything while
1304 runner.CrunchLog.Close()
1307 err = runner.ArvClient.Get("containers", runner.Container.UUID, nil, &runner.Container)
1309 err = fmt.Errorf("While getting container record: %v", err)
1313 // setup signal handling
1314 runner.SetupSignals()
1316 // check for and/or load image
1317 err = runner.LoadImage()
1319 runner.finalState = "Cancelled"
1320 err = fmt.Errorf("While loading container image: %v", err)
1324 // set up FUSE mount and binds
1325 err = runner.SetupMounts()
1327 runner.finalState = "Cancelled"
1328 err = fmt.Errorf("While setting up mounts: %v", err)
1332 err = runner.CreateContainer()
1337 // Gather and record node information
1338 err = runner.LogNodeInfo()
1342 // Save container.json record on log collection
1343 err = runner.LogContainerRecord()
1348 runner.StartCrunchstat()
1350 if runner.IsCancelled() {
1354 err = runner.UpdateContainerRunning()
1358 runner.finalState = "Cancelled"
1360 err = runner.StartContainer()
1365 err = runner.WaitFinish()
1367 runner.finalState = "Complete"
1372 // NewContainerRunner creates a new container runner.
1373 func NewContainerRunner(api IArvadosClient,
1375 docker ThinDockerClient,
1376 containerUUID string) *ContainerRunner {
1378 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1379 cr.NewLogWriter = cr.NewArvLogWriter
1380 cr.RunArvMount = cr.ArvMountCmd
1381 cr.MkTempDir = ioutil.TempDir
1382 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1383 cr.Container.UUID = containerUUID
1384 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1385 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1387 loadLogThrottleParams(api)
1393 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1394 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1395 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1396 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1397 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1398 enableNetwork := flag.String("container-enable-networking", "default",
1399 `Specify if networking should be enabled for container. One of 'default', 'always':
1400 default: only enable networking if container requests it.
1401 always: containers always have networking enabled
1403 networkMode := flag.String("container-network-mode", "default",
1404 `Set networking mode for container. Corresponds to Docker network mode (--net).
1408 containerId := flag.Arg(0)
1410 if *caCertsPath != "" {
1411 arvadosclient.CertFiles = []string{*caCertsPath}
1414 api, err := arvadosclient.MakeArvadosClient()
1416 log.Fatalf("%s: %v", containerId, err)
1420 var kc *keepclient.KeepClient
1421 kc, err = keepclient.MakeKeepClient(api)
1423 log.Fatalf("%s: %v", containerId, err)
1427 var docker *dockerclient.Client
1428 // API version 1.21 corresponds to Docker 1.9, which is currently the
1429 // minimum version we want to support.
1430 docker, err = dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1432 log.Fatalf("%s: %v", containerId, err)
1435 dockerClientProxy := ThinDockerClientProxy{Docker: docker}
1437 cr := NewContainerRunner(api, kc, dockerClientProxy, containerId)
1438 cr.statInterval = *statInterval
1439 cr.cgroupRoot = *cgroupRoot
1440 cr.expectCgroupParent = *cgroupParent
1441 cr.enableNetwork = *enableNetwork
1442 cr.networkMode = *networkMode
1443 if *cgroupParentSubsystem != "" {
1444 p := findCgroup(*cgroupParentSubsystem)
1445 cr.setCgroupParent = p
1446 cr.expectCgroupParent = p
1451 log.Fatalf("%s: %v", containerId, err)