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) {
198 // stop the underlying Docker container.
199 func (runner *ContainerRunner) stop() {
200 runner.cStateLock.Lock()
201 defer runner.cStateLock.Unlock()
202 if runner.cCancelled {
205 runner.cCancelled = true
207 timeout := time.Duration(10)
208 err := runner.Docker.ContainerStop(context.TODO(), runner.ContainerID, &(timeout))
210 log.Printf("StopContainer failed: %s", err)
215 func (runner *ContainerRunner) teardown() {
216 if runner.SigChan != nil {
217 signal.Stop(runner.SigChan)
218 close(runner.SigChan)
222 // LoadImage determines the docker image id from the container record and
223 // checks if it is available in the local Docker image store. If not, it loads
224 // the image from Keep.
225 func (runner *ContainerRunner) LoadImage() (err error) {
227 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
229 var collection arvados.Collection
230 err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
232 return fmt.Errorf("While getting container image collection: %v", err)
234 manifest := manifest.Manifest{Text: collection.ManifestText}
235 var img, imageID string
236 for ms := range manifest.StreamIter() {
237 img = ms.FileStreamSegments[0].Name
238 if !strings.HasSuffix(img, ".tar") {
239 return fmt.Errorf("First file in the container image collection does not end in .tar")
241 imageID = img[:len(img)-4]
244 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
246 _, _, err = runner.Docker.ImageInspectWithRaw(context.TODO(), imageID)
248 runner.CrunchLog.Print("Loading Docker image from keep")
250 var readCloser io.ReadCloser
251 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
253 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
256 response, err := runner.Docker.ImageLoad(context.TODO(), readCloser, false)
258 return fmt.Errorf("While loading container image into Docker: %v", err)
260 response.Body.Close()
262 runner.CrunchLog.Print("Docker image is available")
265 runner.ContainerConfig.Image = imageID
270 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
271 c = exec.Command("arv-mount", arvMountCmd...)
273 // Copy our environment, but override ARVADOS_API_TOKEN with
274 // the container auth token.
276 for _, s := range os.Environ() {
277 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
278 c.Env = append(c.Env, s)
281 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
283 nt := NewThrottledLogger(runner.NewLogWriter("arv-mount"))
292 statReadme := make(chan bool)
293 runner.ArvMountExit = make(chan error)
298 time.Sleep(100 * time.Millisecond)
299 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
309 runner.ArvMountExit <- c.Wait()
310 close(runner.ArvMountExit)
316 case err := <-runner.ArvMountExit:
317 runner.ArvMount = nil
325 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
326 if runner.ArvMountPoint == "" {
327 runner.ArvMountPoint, err = runner.MkTempDir("", prefix)
332 func (runner *ContainerRunner) SetupMounts() (err error) {
333 err = runner.SetupArvMountPoint("keep")
335 return fmt.Errorf("While creating keep mount temp dir: %v", err)
338 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.ArvMountPoint)
342 arvMountCmd := []string{"--foreground", "--allow-other", "--read-write"}
344 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
345 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
348 collectionPaths := []string{}
350 runner.Volumes = make(map[string]struct{})
351 needCertMount := true
354 for bind := range runner.Container.Mounts {
355 binds = append(binds, bind)
359 for _, bind := range binds {
360 mnt := runner.Container.Mounts[bind]
361 if bind == "stdout" || bind == "stderr" {
362 // Is it a "file" mount kind?
363 if mnt.Kind != "file" {
364 return fmt.Errorf("Unsupported mount kind '%s' for %s. Only 'file' is supported.", mnt.Kind, bind)
367 // Does path start with OutputPath?
368 prefix := runner.Container.OutputPath
369 if !strings.HasSuffix(prefix, "/") {
372 if !strings.HasPrefix(mnt.Path, prefix) {
373 return fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
378 // Is it a "collection" mount kind?
379 if mnt.Kind != "collection" && mnt.Kind != "json" {
380 return fmt.Errorf("Unsupported mount kind '%s' for stdin. Only 'collection' or 'json' are supported.", mnt.Kind)
384 if bind == "/etc/arvados/ca-certificates.crt" {
385 needCertMount = false
388 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
389 if mnt.Kind != "collection" {
390 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
395 case mnt.Kind == "collection" && bind != "stdin":
397 if mnt.UUID != "" && mnt.PortableDataHash != "" {
398 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
402 return fmt.Errorf("Writing to existing collections currently not permitted.")
405 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
406 } else if mnt.PortableDataHash != "" {
408 return fmt.Errorf("Can never write to a collection specified by portable data hash")
410 idx := strings.Index(mnt.PortableDataHash, "/")
412 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
413 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
414 runner.Container.Mounts[bind] = mnt
416 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
417 if mnt.Path != "" && mnt.Path != "." {
418 if strings.HasPrefix(mnt.Path, "./") {
419 mnt.Path = mnt.Path[2:]
420 } else if strings.HasPrefix(mnt.Path, "/") {
421 mnt.Path = mnt.Path[1:]
423 src += "/" + mnt.Path
426 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
427 arvMountCmd = append(arvMountCmd, "--mount-tmp")
428 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
432 if bind == runner.Container.OutputPath {
433 runner.HostOutputDir = src
434 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
435 return fmt.Errorf("Writable mount points are not permitted underneath the output_path: %v", bind)
437 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
439 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
441 collectionPaths = append(collectionPaths, src)
443 case mnt.Kind == "tmp":
445 tmpdir, err = runner.MkTempDir("", "")
447 return fmt.Errorf("While creating mount temp dir: %v", err)
449 st, staterr := os.Stat(tmpdir)
451 return fmt.Errorf("While Stat on temp dir: %v", staterr)
453 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
455 return fmt.Errorf("While Chmod temp dir: %v", err)
457 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
458 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", tmpdir, bind))
459 if bind == runner.Container.OutputPath {
460 runner.HostOutputDir = tmpdir
463 case mnt.Kind == "json":
464 jsondata, err := json.Marshal(mnt.Content)
466 return fmt.Errorf("encoding json data: %v", err)
468 // Create a tempdir with a single file
469 // (instead of just a tempfile): this way we
470 // can ensure the file is world-readable
471 // inside the container, without having to
472 // make it world-readable on the docker host.
473 tmpdir, err := runner.MkTempDir("", "")
475 return fmt.Errorf("creating temp dir: %v", err)
477 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
478 tmpfn := filepath.Join(tmpdir, "mountdata.json")
479 err = ioutil.WriteFile(tmpfn, jsondata, 0644)
481 return fmt.Errorf("writing temp file: %v", err)
483 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
487 if runner.HostOutputDir == "" {
488 return fmt.Errorf("Output path does not correspond to a writable mount point")
491 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
492 for _, certfile := range arvadosclient.CertFiles {
493 _, err := os.Stat(certfile)
495 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
502 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
504 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
506 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
508 token, err := runner.ContainerToken()
510 return fmt.Errorf("could not get container token: %s", err)
513 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
515 return fmt.Errorf("While trying to start arv-mount: %v", err)
518 for _, p := range collectionPaths {
521 return fmt.Errorf("While checking that input files exist: %v", err)
528 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
529 // Handle docker log protocol
530 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
532 header := make([]byte, 8)
534 _, readerr := io.ReadAtLeast(containerReader, header, 8)
537 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
540 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
543 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
548 if readerr != io.EOF {
549 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
552 closeerr := runner.Stdout.Close()
554 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
557 closeerr = runner.Stderr.Close()
559 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
562 if runner.statReporter != nil {
563 runner.statReporter.Stop()
564 closeerr = runner.statLogger.Close()
566 runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
570 runner.loggingDone <- true
571 close(runner.loggingDone)
577 func (runner *ContainerRunner) StartCrunchstat() {
578 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
579 runner.statReporter = &crunchstat.Reporter{
580 CID: runner.ContainerID,
581 Logger: log.New(runner.statLogger, "", 0),
582 CgroupParent: runner.expectCgroupParent,
583 CgroupRoot: runner.cgroupRoot,
584 PollPeriod: runner.statInterval,
586 runner.statReporter.Start()
589 type infoCommand struct {
594 // Gather node information and store it on the log for debugging
596 func (runner *ContainerRunner) LogNodeInfo() (err error) {
597 w := runner.NewLogWriter("node-info")
598 logger := log.New(w, "node-info", 0)
600 commands := []infoCommand{
602 label: "Host Information",
603 cmd: []string{"uname", "-a"},
606 label: "CPU Information",
607 cmd: []string{"cat", "/proc/cpuinfo"},
610 label: "Memory Information",
611 cmd: []string{"cat", "/proc/meminfo"},
615 cmd: []string{"df", "-m", "/", os.TempDir()},
618 label: "Disk INodes",
619 cmd: []string{"df", "-i", "/", os.TempDir()},
623 // Run commands with informational output to be logged.
625 for _, command := range commands {
626 out, err = exec.Command(command.cmd[0], command.cmd[1:]...).CombinedOutput()
628 return fmt.Errorf("While running command %q: %v",
631 logger.Println(command.label)
632 for _, line := range strings.Split(string(out), "\n") {
633 logger.Println(" ", line)
639 return fmt.Errorf("While closing node-info logs: %v", err)
644 // Get and save the raw JSON container record from the API server
645 func (runner *ContainerRunner) LogContainerRecord() (err error) {
647 ArvClient: runner.ArvClient,
648 UUID: runner.Container.UUID,
649 loggingStream: "container",
650 writeCloser: runner.LogCollection.Open("container.json"),
653 // Get Container record JSON from the API Server
654 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
656 return fmt.Errorf("While retrieving container record from the API server: %v", err)
660 dec := json.NewDecoder(reader)
662 var cr map[string]interface{}
663 if err = dec.Decode(&cr); err != nil {
664 return fmt.Errorf("While decoding the container record JSON response: %v", err)
666 // Re-encode it using indentation to improve readability
667 enc := json.NewEncoder(w)
668 enc.SetIndent("", " ")
669 if err = enc.Encode(cr); err != nil {
670 return fmt.Errorf("While logging the JSON container record: %v", err)
674 return fmt.Errorf("While closing container.json log: %v", err)
679 // AttachStreams connects the docker container stdin, stdout and stderr logs
680 // to the Arvados logger which logs to Keep and the API server logs table.
681 func (runner *ContainerRunner) AttachStreams() (err error) {
683 runner.CrunchLog.Print("Attaching container streams")
685 // If stdin mount is provided, attach it to the docker container
686 var stdinRdr arvados.File
688 if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
689 if stdinMnt.Kind == "collection" {
690 var stdinColl arvados.Collection
691 collId := stdinMnt.UUID
693 collId = stdinMnt.PortableDataHash
695 err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
697 return fmt.Errorf("While getting stding collection: %v", err)
700 stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
701 if os.IsNotExist(err) {
702 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
703 } else if err != nil {
704 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
706 } else if stdinMnt.Kind == "json" {
707 stdinJson, err = json.Marshal(stdinMnt.Content)
709 return fmt.Errorf("While encoding stdin json data: %v", err)
714 stdinUsed := stdinRdr != nil || len(stdinJson) != 0
715 response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
716 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
718 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
721 runner.loggingDone = make(chan bool)
723 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
724 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
728 runner.Stdout = stdoutFile
730 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
733 if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
734 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
738 runner.Stderr = stderrFile
740 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
745 _, err := io.Copy(response.Conn, stdinRdr)
747 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
751 response.CloseWrite()
753 } else if len(stdinJson) != 0 {
755 _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
757 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
760 response.CloseWrite()
764 go runner.ProcessDockerAttach(response.Reader)
769 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
770 stdoutPath := mntPath[len(runner.Container.OutputPath):]
771 index := strings.LastIndex(stdoutPath, "/")
773 subdirs := stdoutPath[:index]
775 st, err := os.Stat(runner.HostOutputDir)
777 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
779 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
780 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
782 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
786 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
788 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
791 return stdoutFile, nil
794 // CreateContainer creates the docker container.
795 func (runner *ContainerRunner) CreateContainer() error {
796 runner.CrunchLog.Print("Creating Docker container")
798 runner.ContainerConfig.Cmd = runner.Container.Command
799 if runner.Container.Cwd != "." {
800 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
803 for k, v := range runner.Container.Environment {
804 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
807 runner.ContainerConfig.Volumes = runner.Volumes
809 runner.HostConfig = dockercontainer.HostConfig{
811 LogConfig: dockercontainer.LogConfig{
814 Resources: dockercontainer.Resources{
815 CgroupParent: runner.setCgroupParent,
819 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
820 tok, err := runner.ContainerToken()
824 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
825 "ARVADOS_API_TOKEN="+tok,
826 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
827 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
829 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
831 if runner.enableNetwork == "always" {
832 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
834 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
838 _, stdinUsed := runner.Container.Mounts["stdin"]
839 runner.ContainerConfig.OpenStdin = stdinUsed
840 runner.ContainerConfig.StdinOnce = stdinUsed
841 runner.ContainerConfig.AttachStdin = stdinUsed
842 runner.ContainerConfig.AttachStdout = true
843 runner.ContainerConfig.AttachStderr = true
845 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
847 return fmt.Errorf("While creating container: %v", err)
850 runner.ContainerID = createdBody.ID
852 return runner.AttachStreams()
855 // StartContainer starts the docker container created by CreateContainer.
856 func (runner *ContainerRunner) StartContainer() error {
857 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
858 runner.cStateLock.Lock()
859 defer runner.cStateLock.Unlock()
860 if runner.cCancelled {
863 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
864 dockertypes.ContainerStartOptions{})
867 if strings.Contains(err.Error(), "no such file or directory") {
868 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])
870 return fmt.Errorf("could not start container: %v%s", err, advice)
872 runner.cStarted = true
876 // WaitFinish waits for the container to terminate, capture the exit code, and
877 // close the stdout/stderr logging.
878 func (runner *ContainerRunner) WaitFinish() (err error) {
879 runner.CrunchLog.Print("Waiting for container to finish")
881 waitOk, waitErr := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID, "not-running")
883 var waitBody dockercontainer.ContainerWaitOKBody
885 case waitBody = <-waitOk:
886 case err = <-waitErr:
890 return fmt.Errorf("container wait: %v", err)
893 runner.CrunchLog.Printf("Container exited with code: %v", waitBody.StatusCode)
894 code := int(waitBody.StatusCode)
895 runner.ExitCode = &code
897 waitMount := runner.ArvMountExit
899 case err = <-waitMount:
900 runner.CrunchLog.Printf("arv-mount exited before container finished: %v", err)
906 // wait for stdout/stderr to complete
912 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
913 func (runner *ContainerRunner) CaptureOutput() error {
914 if runner.finalState != "Complete" {
918 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
919 // Output may have been set directly by the container, so
920 // refresh the container record to check.
921 err := runner.ArvClient.Get("containers", runner.Container.UUID,
922 nil, &runner.Container)
926 if runner.Container.Output != "" {
927 // Container output is already set.
928 runner.OutputPDH = &runner.Container.Output
933 if runner.HostOutputDir == "" {
937 _, err := os.Stat(runner.HostOutputDir)
939 return fmt.Errorf("While checking host output path: %v", err)
942 // Pre-populate output from the configured mount points
944 for bind, mnt := range runner.Container.Mounts {
945 if mnt.Kind == "collection" {
946 binds = append(binds, bind)
951 var manifestText string
953 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
954 _, err = os.Stat(collectionMetafile)
958 // Find symlinks to arv-mounted files & dirs.
959 err = filepath.Walk(runner.HostOutputDir, func(path string, info os.FileInfo, err error) error {
963 if info.Mode()&os.ModeSymlink == 0 {
966 // read link to get container internal path
967 // only support 1 level of symlinking here.
969 tgt, err = os.Readlink(path)
974 // get path relative to output dir
975 outputSuffix := path[len(runner.HostOutputDir):]
977 if strings.HasPrefix(tgt, "/") {
978 // go through mounts and try reverse map to collection reference
979 for _, bind := range binds {
980 mnt := runner.Container.Mounts[bind]
981 if tgt == bind || strings.HasPrefix(tgt, bind+"/") {
982 // get path relative to bind
983 targetSuffix := tgt[len(bind):]
985 // Copy mount and adjust the path to add path relative to the bind
987 adjustedMount.Path = filepath.Join(adjustedMount.Path, targetSuffix)
991 m, err = runner.getCollectionManifestForPath(adjustedMount, outputSuffix)
995 manifestText = manifestText + m
996 // delete symlink so WriteTree won't try to to dereference it.
1003 // Not a link to a mount. Must be dereferencible and
1004 // point into the output directory.
1005 tgt, err = filepath.EvalSymlinks(path)
1011 // Symlink target must be within the output directory otherwise it's an error.
1012 if !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
1014 return fmt.Errorf("Output directory symlink %q points to invalid location %q, must point to mount or output directory.",
1020 return fmt.Errorf("While checking output symlinks: %v", err)
1023 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
1025 m, err = cw.WriteTree(runner.HostOutputDir, runner.CrunchLog.Logger)
1026 manifestText = manifestText + m
1028 return fmt.Errorf("While uploading output files: %v", err)
1031 // FUSE mount directory
1032 file, openerr := os.Open(collectionMetafile)
1034 return fmt.Errorf("While opening FUSE metafile: %v", err)
1038 var rec arvados.Collection
1039 err = json.NewDecoder(file).Decode(&rec)
1041 return fmt.Errorf("While reading FUSE metafile: %v", err)
1043 manifestText = rec.ManifestText
1046 for _, bind := range binds {
1047 mnt := runner.Container.Mounts[bind]
1049 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
1051 if bindSuffix == bind || len(bindSuffix) <= 0 {
1052 // either does not start with OutputPath or is OutputPath itself
1056 if mnt.ExcludeFromOutput == true {
1060 // append to manifest_text
1061 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
1066 manifestText = manifestText + m
1070 var response arvados.Collection
1071 manifest := manifest.Manifest{Text: manifestText}
1072 manifestText = manifest.Extract(".", ".").Text
1073 err = runner.ArvClient.Create("collections",
1075 "ensure_unique_name": true,
1076 "collection": arvadosclient.Dict{
1078 "name": "output for " + runner.Container.UUID,
1079 "manifest_text": manifestText}},
1082 return fmt.Errorf("While creating output collection: %v", err)
1084 runner.OutputPDH = &response.PortableDataHash
1088 var outputCollections = make(map[string]arvados.Collection)
1090 // Fetch the collection for the mnt.PortableDataHash
1091 // Return the manifest_text fragment corresponding to the specified mnt.Path
1092 // after making any required updates.
1094 // If mnt.Path is not specified,
1095 // return the entire manifest_text after replacing any "." with bindSuffix
1096 // If mnt.Path corresponds to one stream,
1097 // return the manifest_text for that stream after replacing that stream name with bindSuffix
1098 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1099 // for that stream after replacing stream name with bindSuffix minus the last word
1100 // and the file name with last word of the bindSuffix
1101 // Allowed path examples:
1103 // "path":"/subdir1"
1104 // "path":"/subdir1/subdir2"
1105 // "path":"/subdir/filename" etc
1106 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1107 collection := outputCollections[mnt.PortableDataHash]
1108 if collection.PortableDataHash == "" {
1109 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1111 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1113 outputCollections[mnt.PortableDataHash] = collection
1116 if collection.ManifestText == "" {
1117 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1121 mft := manifest.Manifest{Text: collection.ManifestText}
1122 extracted := mft.Extract(mnt.Path, bindSuffix)
1123 if extracted.Err != nil {
1124 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1126 return extracted.Text, nil
1129 func (runner *ContainerRunner) CleanupDirs() {
1130 if runner.ArvMount != nil {
1131 umount := exec.Command("fusermount", "-z", "-u", runner.ArvMountPoint)
1132 umnterr := umount.Run()
1134 runner.CrunchLog.Printf("While running fusermount: %v", umnterr)
1137 mnterr := <-runner.ArvMountExit
1139 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
1143 for _, tmpdir := range runner.CleanupTempDir {
1144 rmerr := os.RemoveAll(tmpdir)
1146 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1151 // CommitLogs posts the collection containing the final container logs.
1152 func (runner *ContainerRunner) CommitLogs() error {
1153 runner.CrunchLog.Print(runner.finalState)
1154 runner.CrunchLog.Close()
1156 // Closing CrunchLog above allows it to be committed to Keep at this
1157 // point, but re-open crunch log with ArvClient in case there are any
1158 // other further (such as failing to write the log to Keep!) while
1160 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1161 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1163 if runner.LogsPDH != nil {
1164 // If we have already assigned something to LogsPDH,
1165 // we must be closing the re-opened log, which won't
1166 // end up getting attached to the container record and
1167 // therefore doesn't need to be saved as a collection
1168 // -- it exists only to send logs to other channels.
1172 mt, err := runner.LogCollection.ManifestText()
1174 return fmt.Errorf("While creating log manifest: %v", err)
1177 var response arvados.Collection
1178 err = runner.ArvClient.Create("collections",
1180 "ensure_unique_name": true,
1181 "collection": arvadosclient.Dict{
1183 "name": "logs for " + runner.Container.UUID,
1184 "manifest_text": mt}},
1187 return fmt.Errorf("While creating log collection: %v", err)
1189 runner.LogsPDH = &response.PortableDataHash
1193 // UpdateContainerRunning updates the container state to "Running"
1194 func (runner *ContainerRunner) UpdateContainerRunning() error {
1195 runner.cStateLock.Lock()
1196 defer runner.cStateLock.Unlock()
1197 if runner.cCancelled {
1200 return runner.ArvClient.Update("containers", runner.Container.UUID,
1201 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1204 // ContainerToken returns the api_token the container (and any
1205 // arv-mount processes) are allowed to use.
1206 func (runner *ContainerRunner) ContainerToken() (string, error) {
1207 if runner.token != "" {
1208 return runner.token, nil
1211 var auth arvados.APIClientAuthorization
1212 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1216 runner.token = auth.APIToken
1217 return runner.token, nil
1220 // UpdateContainerComplete updates the container record state on API
1221 // server to "Complete" or "Cancelled"
1222 func (runner *ContainerRunner) UpdateContainerFinal() error {
1223 update := arvadosclient.Dict{}
1224 update["state"] = runner.finalState
1225 if runner.LogsPDH != nil {
1226 update["log"] = *runner.LogsPDH
1228 if runner.finalState == "Complete" {
1229 if runner.ExitCode != nil {
1230 update["exit_code"] = *runner.ExitCode
1232 if runner.OutputPDH != nil {
1233 update["output"] = *runner.OutputPDH
1236 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1239 // IsCancelled returns the value of Cancelled, with goroutine safety.
1240 func (runner *ContainerRunner) IsCancelled() bool {
1241 runner.cStateLock.Lock()
1242 defer runner.cStateLock.Unlock()
1243 return runner.cCancelled
1246 // NewArvLogWriter creates an ArvLogWriter
1247 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1248 return &ArvLogWriter{ArvClient: runner.ArvClient, UUID: runner.Container.UUID, loggingStream: name,
1249 writeCloser: runner.LogCollection.Open(name + ".txt")}
1252 // Run the full container lifecycle.
1253 func (runner *ContainerRunner) Run() (err error) {
1254 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1256 hostname, hosterr := os.Hostname()
1258 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1260 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1263 // Clean up temporary directories _after_ finalizing
1264 // everything (if we've made any by then)
1265 defer runner.CleanupDirs()
1267 runner.finalState = "Queued"
1270 // checkErr prints e (unless it's nil) and sets err to
1271 // e (unless err is already non-nil). Thus, if err
1272 // hasn't already been assigned when Run() returns,
1273 // this cleanup func will cause Run() to return the
1274 // first non-nil error that is passed to checkErr().
1275 checkErr := func(e error) {
1279 runner.CrunchLog.Print(e)
1283 if runner.finalState == "Complete" {
1284 // There was an error in the finalization.
1285 runner.finalState = "Cancelled"
1289 // Log the error encountered in Run(), if any
1292 if runner.finalState == "Queued" {
1293 runner.CrunchLog.Close()
1294 runner.UpdateContainerFinal()
1298 if runner.IsCancelled() {
1299 runner.finalState = "Cancelled"
1300 // but don't return yet -- we still want to
1301 // capture partial output and write logs
1304 checkErr(runner.CaptureOutput())
1305 checkErr(runner.CommitLogs())
1306 checkErr(runner.UpdateContainerFinal())
1308 // The real log is already closed, but then we opened
1309 // a new one in case we needed to log anything while
1311 runner.CrunchLog.Close()
1316 err = runner.fetchContainerRecord()
1321 // setup signal handling
1322 runner.setupSignals()
1324 // check for and/or load image
1325 err = runner.LoadImage()
1327 runner.finalState = "Cancelled"
1328 err = fmt.Errorf("While loading container image: %v", err)
1332 // set up FUSE mount and binds
1333 err = runner.SetupMounts()
1335 runner.finalState = "Cancelled"
1336 err = fmt.Errorf("While setting up mounts: %v", err)
1340 err = runner.CreateContainer()
1345 // Gather and record node information
1346 err = runner.LogNodeInfo()
1350 // Save container.json record on log collection
1351 err = runner.LogContainerRecord()
1356 runner.StartCrunchstat()
1358 if runner.IsCancelled() {
1362 err = runner.UpdateContainerRunning()
1366 runner.finalState = "Cancelled"
1368 err = runner.StartContainer()
1373 err = runner.WaitFinish()
1375 runner.finalState = "Complete"
1380 // Fetch the current container record (uuid = runner.Container.UUID)
1381 // into runner.Container.
1382 func (runner *ContainerRunner) fetchContainerRecord() error {
1383 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1385 return fmt.Errorf("error fetching container record: %v", err)
1387 defer reader.Close()
1389 dec := json.NewDecoder(reader)
1391 err = dec.Decode(&runner.Container)
1393 return fmt.Errorf("error decoding container record: %v", err)
1398 // NewContainerRunner creates a new container runner.
1399 func NewContainerRunner(api IArvadosClient,
1401 docker ThinDockerClient,
1402 containerUUID string) *ContainerRunner {
1404 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1405 cr.NewLogWriter = cr.NewArvLogWriter
1406 cr.RunArvMount = cr.ArvMountCmd
1407 cr.MkTempDir = ioutil.TempDir
1408 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1409 cr.Container.UUID = containerUUID
1410 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1411 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1413 loadLogThrottleParams(api)
1419 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1420 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1421 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1422 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1423 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1424 enableNetwork := flag.String("container-enable-networking", "default",
1425 `Specify if networking should be enabled for container. One of 'default', 'always':
1426 default: only enable networking if container requests it.
1427 always: containers always have networking enabled
1429 networkMode := flag.String("container-network-mode", "default",
1430 `Set networking mode for container. Corresponds to Docker network mode (--net).
1434 containerId := flag.Arg(0)
1436 if *caCertsPath != "" {
1437 arvadosclient.CertFiles = []string{*caCertsPath}
1440 api, err := arvadosclient.MakeArvadosClient()
1442 log.Fatalf("%s: %v", containerId, err)
1446 var kc *keepclient.KeepClient
1447 kc, err = keepclient.MakeKeepClient(api)
1449 log.Fatalf("%s: %v", containerId, err)
1453 var docker *dockerclient.Client
1454 // API version 1.21 corresponds to Docker 1.9, which is currently the
1455 // minimum version we want to support.
1456 docker, err = dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1458 log.Fatalf("%s: %v", containerId, err)
1461 dockerClientProxy := ThinDockerClientProxy{Docker: docker}
1463 cr := NewContainerRunner(api, kc, dockerClientProxy, containerId)
1464 cr.statInterval = *statInterval
1465 cr.cgroupRoot = *cgroupRoot
1466 cr.expectCgroupParent = *cgroupParent
1467 cr.enableNetwork = *enableNetwork
1468 cr.networkMode = *networkMode
1469 if *cgroupParentSubsystem != "" {
1470 p := findCgroup(*cgroupParentSubsystem)
1471 cr.setCgroupParent = p
1472 cr.expectCgroupParent = p
1477 log.Fatalf("%s: %v", containerId, err)