24 "git.curoverse.com/arvados.git/lib/crunchstat"
25 "git.curoverse.com/arvados.git/sdk/go/arvados"
26 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
27 "git.curoverse.com/arvados.git/sdk/go/keepclient"
28 "git.curoverse.com/arvados.git/sdk/go/manifest"
30 dockertypes "github.com/docker/docker/api/types"
31 dockercontainer "github.com/docker/docker/api/types/container"
32 dockernetwork "github.com/docker/docker/api/types/network"
33 dockerclient "github.com/docker/docker/client"
36 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
37 type IArvadosClient interface {
38 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
39 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
40 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
41 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
42 CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
43 Discovery(key string) (interface{}, error)
46 // ErrCancelled is the error returned when the container is cancelled.
47 var ErrCancelled = errors.New("Cancelled")
49 // IKeepClient is the minimal Keep API methods used by crunch-run.
50 type IKeepClient interface {
51 PutHB(hash string, buf []byte) (string, int, error)
52 ManifestFileReader(m manifest.Manifest, filename string) (keepclient.Reader, error)
55 // NewLogWriter is a factory function to create a new log writer.
56 type NewLogWriter func(name string) io.WriteCloser
58 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
60 type MkTempDir func(string, string) (string, error)
62 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
63 type ThinDockerClient interface {
64 ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error)
65 ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
66 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error)
67 ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error
68 ContainerStop(ctx context.Context, container string, timeout *time.Duration) error
69 ContainerWait(ctx context.Context, container string) (int64, error)
70 ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error)
71 ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error)
72 ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error)
75 // ThinDockerClientProxy is a proxy implementation of ThinDockerClient
76 // that executes the docker requests on dockerclient.Client
77 type ThinDockerClientProxy struct {
78 Docker *dockerclient.Client
81 // ContainerAttach invokes dockerclient.Client.ContainerAttach
82 func (proxy ThinDockerClientProxy) ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error) {
83 return proxy.Docker.ContainerAttach(ctx, container, options)
86 // ContainerCreate invokes dockerclient.Client.ContainerCreate
87 func (proxy ThinDockerClientProxy) ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
88 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error) {
89 return proxy.Docker.ContainerCreate(ctx, config, hostConfig, networkingConfig, containerName)
92 // ContainerStart invokes dockerclient.Client.ContainerStart
93 func (proxy ThinDockerClientProxy) ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error {
94 return proxy.Docker.ContainerStart(ctx, container, options)
97 // ContainerStop invokes dockerclient.Client.ContainerStop
98 func (proxy ThinDockerClientProxy) ContainerStop(ctx context.Context, container string, timeout *time.Duration) error {
99 return proxy.Docker.ContainerStop(ctx, container, timeout)
102 // ContainerWait invokes dockerclient.Client.ContainerWait
103 func (proxy ThinDockerClientProxy) ContainerWait(ctx context.Context, container string) (int64, error) {
104 return proxy.Docker.ContainerWait(ctx, container)
107 // ImageInspectWithRaw invokes dockerclient.Client.ImageInspectWithRaw
108 func (proxy ThinDockerClientProxy) ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error) {
109 return proxy.Docker.ImageInspectWithRaw(ctx, image)
112 // ImageLoad invokes dockerclient.Client.ImageLoad
113 func (proxy ThinDockerClientProxy) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error) {
114 return proxy.Docker.ImageLoad(ctx, input, quiet)
117 // ImageRemove invokes dockerclient.Client.ImageRemove
118 func (proxy ThinDockerClientProxy) ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {
119 return proxy.Docker.ImageRemove(ctx, image, options)
122 // ContainerRunner is the main stateful struct used for a single execution of a
124 type ContainerRunner struct {
125 Docker ThinDockerClient
126 ArvClient IArvadosClient
129 ContainerConfig dockercontainer.Config
130 dockercontainer.HostConfig
135 loggingDone chan bool
136 CrunchLog *ThrottledLogger
137 Stdout io.WriteCloser
138 Stderr io.WriteCloser
139 LogCollection *CollectionWriter
146 CleanupTempDir []string
148 Volumes map[string]struct{}
150 SigChan chan os.Signal
151 ArvMountExit chan error
154 statLogger io.WriteCloser
155 statReporter *crunchstat.Reporter
156 statInterval time.Duration
158 // What we expect the container's cgroup parent to be.
159 expectCgroupParent string
160 // What we tell docker to use as the container's cgroup
161 // parent. Note: Ideally we would use the same field for both
162 // expectCgroupParent and setCgroupParent, and just make it
163 // default to "docker". However, when using docker < 1.10 with
164 // systemd, specifying a non-empty cgroup parent (even the
165 // default value "docker") hits a docker bug
166 // (https://github.com/docker/docker/issues/17126). Using two
167 // separate fields makes it possible to use the "expect cgroup
168 // parent to be X" feature even on sites where the "specify
169 // cgroup parent" feature breaks.
170 setCgroupParent string
172 cStateLock sync.Mutex
173 cStarted bool // StartContainer() succeeded
174 cCancelled bool // StopContainer() invoked
176 enableNetwork string // one of "default" or "always"
177 networkMode string // passed through to HostConfig.NetworkMode
180 // SetupSignals sets up signal handling to gracefully terminate the underlying
181 // Docker container and update state when receiving a TERM, INT or QUIT signal.
182 func (runner *ContainerRunner) SetupSignals() {
183 runner.SigChan = make(chan os.Signal, 1)
184 signal.Notify(runner.SigChan, syscall.SIGTERM)
185 signal.Notify(runner.SigChan, syscall.SIGINT)
186 signal.Notify(runner.SigChan, syscall.SIGQUIT)
188 go func(sig chan os.Signal) {
195 // stop the underlying Docker container.
196 func (runner *ContainerRunner) stop() {
197 runner.cStateLock.Lock()
198 defer runner.cStateLock.Unlock()
199 if runner.cCancelled {
202 runner.cCancelled = true
204 timeout := time.Duration(10)
205 err := runner.Docker.ContainerStop(context.TODO(), runner.ContainerID, &(timeout))
207 log.Printf("StopContainer failed: %s", err)
212 // LoadImage determines the docker image id from the container record and
213 // checks if it is available in the local Docker image store. If not, it loads
214 // the image from Keep.
215 func (runner *ContainerRunner) LoadImage() (err error) {
217 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
219 var collection arvados.Collection
220 err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
222 return fmt.Errorf("While getting container image collection: %v", err)
224 manifest := manifest.Manifest{Text: collection.ManifestText}
225 var img, imageID string
226 for ms := range manifest.StreamIter() {
227 img = ms.FileStreamSegments[0].Name
228 if !strings.HasSuffix(img, ".tar") {
229 return fmt.Errorf("First file in the container image collection does not end in .tar")
231 imageID = img[:len(img)-4]
234 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
236 _, _, err = runner.Docker.ImageInspectWithRaw(context.TODO(), imageID)
238 runner.CrunchLog.Print("Loading Docker image from keep")
240 var readCloser io.ReadCloser
241 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
243 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
246 response, err := runner.Docker.ImageLoad(context.TODO(), readCloser, false)
248 return fmt.Errorf("While loading container image into Docker: %v", err)
250 response.Body.Close()
252 runner.CrunchLog.Print("Docker image is available")
255 runner.ContainerConfig.Image = imageID
260 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
261 c = exec.Command("arv-mount", arvMountCmd...)
263 // Copy our environment, but override ARVADOS_API_TOKEN with
264 // the container auth token.
266 for _, s := range os.Environ() {
267 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
268 c.Env = append(c.Env, s)
271 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
273 nt := NewThrottledLogger(runner.NewLogWriter("arv-mount"))
282 statReadme := make(chan bool)
283 runner.ArvMountExit = make(chan error)
288 time.Sleep(100 * time.Millisecond)
289 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
299 runner.ArvMountExit <- c.Wait()
300 close(runner.ArvMountExit)
306 case err := <-runner.ArvMountExit:
307 runner.ArvMount = nil
315 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
316 if runner.ArvMountPoint == "" {
317 runner.ArvMountPoint, err = runner.MkTempDir("", prefix)
322 func (runner *ContainerRunner) SetupMounts() (err error) {
323 err = runner.SetupArvMountPoint("keep")
325 return fmt.Errorf("While creating keep mount temp dir: %v", err)
328 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.ArvMountPoint)
332 arvMountCmd := []string{"--foreground", "--allow-other", "--read-write"}
334 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
335 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
338 collectionPaths := []string{}
340 runner.Volumes = make(map[string]struct{})
341 needCertMount := true
344 for bind, _ := range runner.Container.Mounts {
345 binds = append(binds, bind)
349 for _, bind := range binds {
350 mnt := runner.Container.Mounts[bind]
351 if bind == "stdout" || bind == "stderr" {
352 // Is it a "file" mount kind?
353 if mnt.Kind != "file" {
354 return fmt.Errorf("Unsupported mount kind '%s' for %s. Only 'file' is supported.", mnt.Kind, bind)
357 // Does path start with OutputPath?
358 prefix := runner.Container.OutputPath
359 if !strings.HasSuffix(prefix, "/") {
362 if !strings.HasPrefix(mnt.Path, prefix) {
363 return fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
368 // Is it a "collection" mount kind?
369 if mnt.Kind != "collection" && mnt.Kind != "json" {
370 return fmt.Errorf("Unsupported mount kind '%s' for stdin. Only 'collection' or 'json' are supported.", mnt.Kind)
374 if bind == "/etc/arvados/ca-certificates.crt" {
375 needCertMount = false
378 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
379 if mnt.Kind != "collection" {
380 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
385 case mnt.Kind == "collection" && bind != "stdin":
387 if mnt.UUID != "" && mnt.PortableDataHash != "" {
388 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
392 return fmt.Errorf("Writing to existing collections currently not permitted.")
395 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
396 } else if mnt.PortableDataHash != "" {
398 return fmt.Errorf("Can never write to a collection specified by portable data hash")
400 idx := strings.Index(mnt.PortableDataHash, "/")
402 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
403 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
404 runner.Container.Mounts[bind] = mnt
406 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
407 if mnt.Path != "" && mnt.Path != "." {
408 if strings.HasPrefix(mnt.Path, "./") {
409 mnt.Path = mnt.Path[2:]
410 } else if strings.HasPrefix(mnt.Path, "/") {
411 mnt.Path = mnt.Path[1:]
413 src += "/" + mnt.Path
416 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
417 arvMountCmd = append(arvMountCmd, "--mount-tmp")
418 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
422 if bind == runner.Container.OutputPath {
423 runner.HostOutputDir = src
424 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
425 return fmt.Errorf("Writable mount points are not permitted underneath the output_path: %v", bind)
427 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
429 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
431 collectionPaths = append(collectionPaths, src)
433 case mnt.Kind == "tmp" && bind == runner.Container.OutputPath:
434 runner.HostOutputDir, err = runner.MkTempDir("", "")
436 return fmt.Errorf("While creating mount temp dir: %v", err)
438 st, staterr := os.Stat(runner.HostOutputDir)
440 return fmt.Errorf("While Stat on temp dir: %v", staterr)
442 err = os.Chmod(runner.HostOutputDir, st.Mode()|os.ModeSetgid|0777)
444 return fmt.Errorf("While Chmod temp dir: %v", err)
446 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.HostOutputDir)
447 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", runner.HostOutputDir, bind))
449 case mnt.Kind == "tmp":
450 runner.Volumes[bind] = struct{}{}
452 case mnt.Kind == "json":
453 jsondata, err := json.Marshal(mnt.Content)
455 return fmt.Errorf("encoding json data: %v", err)
457 // Create a tempdir with a single file
458 // (instead of just a tempfile): this way we
459 // can ensure the file is world-readable
460 // inside the container, without having to
461 // make it world-readable on the docker host.
462 tmpdir, err := runner.MkTempDir("", "")
464 return fmt.Errorf("creating temp dir: %v", err)
466 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
467 tmpfn := filepath.Join(tmpdir, "mountdata.json")
468 err = ioutil.WriteFile(tmpfn, jsondata, 0644)
470 return fmt.Errorf("writing temp file: %v", err)
472 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
476 if runner.HostOutputDir == "" {
477 return fmt.Errorf("Output path does not correspond to a writable mount point")
480 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
481 for _, certfile := range arvadosclient.CertFiles {
482 _, err := os.Stat(certfile)
484 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
491 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
493 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
495 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
497 token, err := runner.ContainerToken()
499 return fmt.Errorf("could not get container token: %s", err)
502 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
504 return fmt.Errorf("While trying to start arv-mount: %v", err)
507 for _, p := range collectionPaths {
510 return fmt.Errorf("While checking that input files exist: %v", err)
517 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
518 // Handle docker log protocol
519 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
521 header := make([]byte, 8)
523 _, readerr := io.ReadAtLeast(containerReader, header, 8)
526 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
529 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
532 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
537 if readerr != io.EOF {
538 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
541 closeerr := runner.Stdout.Close()
543 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
546 closeerr = runner.Stderr.Close()
548 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
551 if runner.statReporter != nil {
552 runner.statReporter.Stop()
553 closeerr = runner.statLogger.Close()
555 runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
559 runner.loggingDone <- true
560 close(runner.loggingDone)
566 func (runner *ContainerRunner) StartCrunchstat() {
567 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
568 runner.statReporter = &crunchstat.Reporter{
569 CID: runner.ContainerID,
570 Logger: log.New(runner.statLogger, "", 0),
571 CgroupParent: runner.expectCgroupParent,
572 CgroupRoot: runner.cgroupRoot,
573 PollPeriod: runner.statInterval,
575 runner.statReporter.Start()
578 type infoCommand struct {
583 // Gather node information and store it on the log for debugging
585 func (runner *ContainerRunner) LogNodeInfo() (err error) {
586 w := runner.NewLogWriter("node-info")
587 logger := log.New(w, "node-info", 0)
589 commands := []infoCommand{
591 label: "Host Information",
592 cmd: []string{"uname", "-a"},
595 label: "CPU Information",
596 cmd: []string{"cat", "/proc/cpuinfo"},
599 label: "Memory Information",
600 cmd: []string{"cat", "/proc/meminfo"},
604 cmd: []string{"df", "-m", "/", os.TempDir()},
607 label: "Disk INodes",
608 cmd: []string{"df", "-i", "/", os.TempDir()},
612 // Run commands with informational output to be logged.
614 for _, command := range commands {
615 out, err = exec.Command(command.cmd[0], command.cmd[1:]...).CombinedOutput()
617 return fmt.Errorf("While running command %q: %v",
620 logger.Println(command.label)
621 for _, line := range strings.Split(string(out), "\n") {
622 logger.Println(" ", line)
628 return fmt.Errorf("While closing node-info logs: %v", err)
633 // Get and save the raw JSON container record from the API server
634 func (runner *ContainerRunner) LogContainerRecord() (err error) {
637 runner.Container.UUID,
639 runner.LogCollection.Open("container.json"),
641 // Get Container record JSON from the API Server
642 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
644 return fmt.Errorf("While retrieving container record from the API server: %v", err)
647 // Read the API server response as []byte
648 json_bytes, err := ioutil.ReadAll(reader)
650 return fmt.Errorf("While reading container record API server response: %v", err)
652 // Decode the JSON []byte
653 var cr map[string]interface{}
654 if err = json.Unmarshal(json_bytes, &cr); err != nil {
655 return fmt.Errorf("While decoding the container record JSON response: %v", err)
657 // Re-encode it using indentation to improve readability
658 enc := json.NewEncoder(w)
659 enc.SetIndent("", " ")
660 if err = enc.Encode(cr); err != nil {
661 return fmt.Errorf("While logging the JSON container record: %v", err)
665 return fmt.Errorf("While closing container.json log: %v", err)
670 // AttachStreams connects the docker container stdin, stdout and stderr logs
671 // to the Arvados logger which logs to Keep and the API server logs table.
672 func (runner *ContainerRunner) AttachStreams() (err error) {
674 runner.CrunchLog.Print("Attaching container streams")
676 // If stdin mount is provided, attach it to the docker container
677 var stdinRdr keepclient.Reader
679 if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
680 if stdinMnt.Kind == "collection" {
681 var stdinColl arvados.Collection
682 collId := stdinMnt.UUID
684 collId = stdinMnt.PortableDataHash
686 err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
688 return fmt.Errorf("While getting stding collection: %v", err)
691 stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
692 if os.IsNotExist(err) {
693 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
694 } else if err != nil {
695 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
697 } else if stdinMnt.Kind == "json" {
698 stdinJson, err = json.Marshal(stdinMnt.Content)
700 return fmt.Errorf("While encoding stdin json data: %v", err)
705 stdinUsed := stdinRdr != nil || len(stdinJson) != 0
706 response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
707 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
709 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
712 runner.loggingDone = make(chan bool)
714 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
715 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
719 runner.Stdout = stdoutFile
721 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
724 if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
725 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
729 runner.Stderr = stderrFile
731 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
736 _, err := io.Copy(response.Conn, stdinRdr)
738 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
742 response.CloseWrite()
744 } else if len(stdinJson) != 0 {
746 _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
748 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
751 response.CloseWrite()
755 go runner.ProcessDockerAttach(response.Reader)
760 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
761 stdoutPath := mntPath[len(runner.Container.OutputPath):]
762 index := strings.LastIndex(stdoutPath, "/")
764 subdirs := stdoutPath[:index]
766 st, err := os.Stat(runner.HostOutputDir)
768 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
770 stdoutPath := path.Join(runner.HostOutputDir, subdirs)
771 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
773 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
777 stdoutFile, err := os.Create(path.Join(runner.HostOutputDir, stdoutPath))
779 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
782 return stdoutFile, nil
785 // CreateContainer creates the docker container.
786 func (runner *ContainerRunner) CreateContainer() error {
787 runner.CrunchLog.Print("Creating Docker container")
789 runner.ContainerConfig.Cmd = runner.Container.Command
790 if runner.Container.Cwd != "." {
791 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
794 for k, v := range runner.Container.Environment {
795 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
798 runner.ContainerConfig.Volumes = runner.Volumes
800 runner.HostConfig = dockercontainer.HostConfig{
802 Cgroup: dockercontainer.CgroupSpec(runner.setCgroupParent),
803 LogConfig: dockercontainer.LogConfig{
808 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
809 tok, err := runner.ContainerToken()
813 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
814 "ARVADOS_API_TOKEN="+tok,
815 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
816 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
818 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
820 if runner.enableNetwork == "always" {
821 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
823 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
827 _, stdinUsed := runner.Container.Mounts["stdin"]
828 runner.ContainerConfig.OpenStdin = stdinUsed
829 runner.ContainerConfig.StdinOnce = stdinUsed
830 runner.ContainerConfig.AttachStdin = stdinUsed
831 runner.ContainerConfig.AttachStdout = true
832 runner.ContainerConfig.AttachStderr = true
834 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
836 return fmt.Errorf("While creating container: %v", err)
839 runner.ContainerID = createdBody.ID
841 return runner.AttachStreams()
844 // StartContainer starts the docker container created by CreateContainer.
845 func (runner *ContainerRunner) StartContainer() error {
846 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
847 runner.cStateLock.Lock()
848 defer runner.cStateLock.Unlock()
849 if runner.cCancelled {
852 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
853 dockertypes.ContainerStartOptions{})
855 return fmt.Errorf("could not start container: %v", err)
857 runner.cStarted = true
861 // WaitFinish waits for the container to terminate, capture the exit code, and
862 // close the stdout/stderr logging.
863 func (runner *ContainerRunner) WaitFinish() error {
864 runner.CrunchLog.Print("Waiting for container to finish")
866 waitDocker, err := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID)
868 return fmt.Errorf("container wait: %v", err)
871 runner.CrunchLog.Printf("Container exited with code: %v", waitDocker)
872 code := int(waitDocker)
873 runner.ExitCode = &code
875 waitMount := runner.ArvMountExit
877 case err := <-waitMount:
878 runner.CrunchLog.Printf("arv-mount exited before container finished: %v", err)
884 // wait for stdout/stderr to complete
890 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
891 func (runner *ContainerRunner) CaptureOutput() error {
892 if runner.finalState != "Complete" {
896 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
897 // Output may have been set directly by the container, so
898 // refresh the container record to check.
899 err := runner.ArvClient.Get("containers", runner.Container.UUID,
900 nil, &runner.Container)
904 if runner.Container.Output != "" {
905 // Container output is already set.
906 runner.OutputPDH = &runner.Container.Output
911 if runner.HostOutputDir == "" {
915 _, err := os.Stat(runner.HostOutputDir)
917 return fmt.Errorf("While checking host output path: %v", err)
920 var manifestText string
922 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
923 _, err = os.Stat(collectionMetafile)
926 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
927 manifestText, err = cw.WriteTree(runner.HostOutputDir, runner.CrunchLog.Logger)
929 return fmt.Errorf("While uploading output files: %v", err)
932 // FUSE mount directory
933 file, openerr := os.Open(collectionMetafile)
935 return fmt.Errorf("While opening FUSE metafile: %v", err)
939 var rec arvados.Collection
940 err = json.NewDecoder(file).Decode(&rec)
942 return fmt.Errorf("While reading FUSE metafile: %v", err)
944 manifestText = rec.ManifestText
947 // Pre-populate output from the configured mount points
949 for bind, _ := range runner.Container.Mounts {
950 binds = append(binds, bind)
954 for _, bind := range binds {
955 mnt := runner.Container.Mounts[bind]
957 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
959 if bindSuffix == bind || len(bindSuffix) <= 0 {
960 // either does not start with OutputPath or is OutputPath itself
964 if mnt.ExcludeFromOutput == true {
968 // append to manifest_text
969 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
974 manifestText = manifestText + m
978 var response arvados.Collection
979 manifest := manifest.Manifest{Text: manifestText}
980 manifestText = manifest.Extract(".", ".").Text
981 err = runner.ArvClient.Create("collections",
983 "ensure_unique_name": true,
984 "collection": arvadosclient.Dict{
986 "name": "output for " + runner.Container.UUID,
987 "manifest_text": manifestText}},
990 return fmt.Errorf("While creating output collection: %v", err)
992 runner.OutputPDH = &response.PortableDataHash
996 var outputCollections = make(map[string]arvados.Collection)
998 // Fetch the collection for the mnt.PortableDataHash
999 // Return the manifest_text fragment corresponding to the specified mnt.Path
1000 // after making any required updates.
1002 // If mnt.Path is not specified,
1003 // return the entire manifest_text after replacing any "." with bindSuffix
1004 // If mnt.Path corresponds to one stream,
1005 // return the manifest_text for that stream after replacing that stream name with bindSuffix
1006 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1007 // for that stream after replacing stream name with bindSuffix minus the last word
1008 // and the file name with last word of the bindSuffix
1009 // Allowed path examples:
1011 // "path":"/subdir1"
1012 // "path":"/subdir1/subdir2"
1013 // "path":"/subdir/filename" etc
1014 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1015 collection := outputCollections[mnt.PortableDataHash]
1016 if collection.PortableDataHash == "" {
1017 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1019 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1021 outputCollections[mnt.PortableDataHash] = collection
1024 if collection.ManifestText == "" {
1025 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1029 mft := manifest.Manifest{Text: collection.ManifestText}
1030 extracted := mft.Extract(mnt.Path, bindSuffix)
1031 if extracted.Err != nil {
1032 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1034 return extracted.Text, nil
1037 func (runner *ContainerRunner) CleanupDirs() {
1038 if runner.ArvMount != nil {
1039 umount := exec.Command("fusermount", "-z", "-u", runner.ArvMountPoint)
1040 umnterr := umount.Run()
1042 runner.CrunchLog.Printf("While running fusermount: %v", umnterr)
1045 mnterr := <-runner.ArvMountExit
1047 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
1051 for _, tmpdir := range runner.CleanupTempDir {
1052 rmerr := os.RemoveAll(tmpdir)
1054 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1059 // CommitLogs posts the collection containing the final container logs.
1060 func (runner *ContainerRunner) CommitLogs() error {
1061 runner.CrunchLog.Print(runner.finalState)
1062 runner.CrunchLog.Close()
1064 // Closing CrunchLog above allows it to be committed to Keep at this
1065 // point, but re-open crunch log with ArvClient in case there are any
1066 // other further (such as failing to write the log to Keep!) while
1068 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{runner.ArvClient, runner.Container.UUID,
1071 if runner.LogsPDH != nil {
1072 // If we have already assigned something to LogsPDH,
1073 // we must be closing the re-opened log, which won't
1074 // end up getting attached to the container record and
1075 // therefore doesn't need to be saved as a collection
1076 // -- it exists only to send logs to other channels.
1080 mt, err := runner.LogCollection.ManifestText()
1082 return fmt.Errorf("While creating log manifest: %v", err)
1085 var response arvados.Collection
1086 err = runner.ArvClient.Create("collections",
1088 "ensure_unique_name": true,
1089 "collection": arvadosclient.Dict{
1091 "name": "logs for " + runner.Container.UUID,
1092 "manifest_text": mt}},
1095 return fmt.Errorf("While creating log collection: %v", err)
1097 runner.LogsPDH = &response.PortableDataHash
1101 // UpdateContainerRunning updates the container state to "Running"
1102 func (runner *ContainerRunner) UpdateContainerRunning() error {
1103 runner.cStateLock.Lock()
1104 defer runner.cStateLock.Unlock()
1105 if runner.cCancelled {
1108 return runner.ArvClient.Update("containers", runner.Container.UUID,
1109 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1112 // ContainerToken returns the api_token the container (and any
1113 // arv-mount processes) are allowed to use.
1114 func (runner *ContainerRunner) ContainerToken() (string, error) {
1115 if runner.token != "" {
1116 return runner.token, nil
1119 var auth arvados.APIClientAuthorization
1120 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1124 runner.token = auth.APIToken
1125 return runner.token, nil
1128 // UpdateContainerComplete updates the container record state on API
1129 // server to "Complete" or "Cancelled"
1130 func (runner *ContainerRunner) UpdateContainerFinal() error {
1131 update := arvadosclient.Dict{}
1132 update["state"] = runner.finalState
1133 if runner.LogsPDH != nil {
1134 update["log"] = *runner.LogsPDH
1136 if runner.finalState == "Complete" {
1137 if runner.ExitCode != nil {
1138 update["exit_code"] = *runner.ExitCode
1140 if runner.OutputPDH != nil {
1141 update["output"] = *runner.OutputPDH
1144 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1147 // IsCancelled returns the value of Cancelled, with goroutine safety.
1148 func (runner *ContainerRunner) IsCancelled() bool {
1149 runner.cStateLock.Lock()
1150 defer runner.cStateLock.Unlock()
1151 return runner.cCancelled
1154 // NewArvLogWriter creates an ArvLogWriter
1155 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1156 return &ArvLogWriter{runner.ArvClient, runner.Container.UUID, name, runner.LogCollection.Open(name + ".txt")}
1159 // Run the full container lifecycle.
1160 func (runner *ContainerRunner) Run() (err error) {
1161 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1163 hostname, hosterr := os.Hostname()
1165 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1167 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1170 // Clean up temporary directories _after_ finalizing
1171 // everything (if we've made any by then)
1172 defer runner.CleanupDirs()
1174 runner.finalState = "Queued"
1177 // checkErr prints e (unless it's nil) and sets err to
1178 // e (unless err is already non-nil). Thus, if err
1179 // hasn't already been assigned when Run() returns,
1180 // this cleanup func will cause Run() to return the
1181 // first non-nil error that is passed to checkErr().
1182 checkErr := func(e error) {
1186 runner.CrunchLog.Print(e)
1192 // Log the error encountered in Run(), if any
1195 if runner.finalState == "Queued" {
1196 runner.CrunchLog.Close()
1197 runner.UpdateContainerFinal()
1201 if runner.IsCancelled() {
1202 runner.finalState = "Cancelled"
1203 // but don't return yet -- we still want to
1204 // capture partial output and write logs
1207 checkErr(runner.CaptureOutput())
1208 checkErr(runner.CommitLogs())
1209 checkErr(runner.UpdateContainerFinal())
1211 // The real log is already closed, but then we opened
1212 // a new one in case we needed to log anything while
1214 runner.CrunchLog.Close()
1217 err = runner.ArvClient.Get("containers", runner.Container.UUID, nil, &runner.Container)
1219 err = fmt.Errorf("While getting container record: %v", err)
1223 // setup signal handling
1224 runner.SetupSignals()
1226 // check for and/or load image
1227 err = runner.LoadImage()
1229 runner.finalState = "Cancelled"
1230 err = fmt.Errorf("While loading container image: %v", err)
1234 // set up FUSE mount and binds
1235 err = runner.SetupMounts()
1237 runner.finalState = "Cancelled"
1238 err = fmt.Errorf("While setting up mounts: %v", err)
1242 err = runner.CreateContainer()
1247 // Gather and record node information
1248 err = runner.LogNodeInfo()
1252 // Save container.json record on log collection
1253 err = runner.LogContainerRecord()
1258 runner.StartCrunchstat()
1260 if runner.IsCancelled() {
1264 err = runner.UpdateContainerRunning()
1268 runner.finalState = "Cancelled"
1270 err = runner.StartContainer()
1275 err = runner.WaitFinish()
1277 runner.finalState = "Complete"
1282 // NewContainerRunner creates a new container runner.
1283 func NewContainerRunner(api IArvadosClient,
1285 docker ThinDockerClient,
1286 containerUUID string) *ContainerRunner {
1288 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1289 cr.NewLogWriter = cr.NewArvLogWriter
1290 cr.RunArvMount = cr.ArvMountCmd
1291 cr.MkTempDir = ioutil.TempDir
1292 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1293 cr.Container.UUID = containerUUID
1294 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1295 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1300 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1301 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1302 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1303 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1304 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1305 enableNetwork := flag.String("container-enable-networking", "default",
1306 `Specify if networking should be enabled for container. One of 'default', 'always':
1307 default: only enable networking if container requests it.
1308 always: containers always have networking enabled
1310 networkMode := flag.String("container-network-mode", "default",
1311 `Set networking mode for container. Corresponds to Docker network mode (--net).
1315 containerId := flag.Arg(0)
1317 if *caCertsPath != "" {
1318 arvadosclient.CertFiles = []string{*caCertsPath}
1321 api, err := arvadosclient.MakeArvadosClient()
1323 log.Fatalf("%s: %v", containerId, err)
1327 var kc *keepclient.KeepClient
1328 kc, err = keepclient.MakeKeepClient(api)
1330 log.Fatalf("%s: %v", containerId, err)
1334 var docker *dockerclient.Client
1335 // API version 1.21 corresponds to Docker 1.9, which is currently the
1336 // minimum version we want to support.
1337 docker, err = dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1339 log.Fatalf("%s: %v", containerId, err)
1342 dockerClientProxy := ThinDockerClientProxy{Docker: docker}
1344 cr := NewContainerRunner(api, kc, dockerClientProxy, containerId)
1345 cr.statInterval = *statInterval
1346 cr.cgroupRoot = *cgroupRoot
1347 cr.expectCgroupParent = *cgroupParent
1348 cr.enableNetwork = *enableNetwork
1349 cr.networkMode = *networkMode
1350 if *cgroupParentSubsystem != "" {
1351 p := findCgroup(*cgroupParentSubsystem)
1352 cr.setCgroupParent = p
1353 cr.expectCgroupParent = p
1358 log.Fatalf("%s: %v", containerId, err)