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
149 SigChan chan os.Signal
150 ArvMountExit chan error
153 statLogger io.WriteCloser
154 statReporter *crunchstat.Reporter
155 statInterval time.Duration
157 // What we expect the container's cgroup parent to be.
158 expectCgroupParent string
159 // What we tell docker to use as the container's cgroup
160 // parent. Note: Ideally we would use the same field for both
161 // expectCgroupParent and setCgroupParent, and just make it
162 // default to "docker". However, when using docker < 1.10 with
163 // systemd, specifying a non-empty cgroup parent (even the
164 // default value "docker") hits a docker bug
165 // (https://github.com/docker/docker/issues/17126). Using two
166 // separate fields makes it possible to use the "expect cgroup
167 // parent to be X" feature even on sites where the "specify
168 // cgroup parent" feature breaks.
169 setCgroupParent string
171 cStateLock sync.Mutex
172 cStarted bool // StartContainer() succeeded
173 cCancelled bool // StopContainer() invoked
175 enableNetwork string // one of "default" or "always"
176 networkMode string // passed through to HostConfig.NetworkMode
179 // SetupSignals sets up signal handling to gracefully terminate the underlying
180 // Docker container and update state when receiving a TERM, INT or QUIT signal.
181 func (runner *ContainerRunner) SetupSignals() {
182 runner.SigChan = make(chan os.Signal, 1)
183 signal.Notify(runner.SigChan, syscall.SIGTERM)
184 signal.Notify(runner.SigChan, syscall.SIGINT)
185 signal.Notify(runner.SigChan, syscall.SIGQUIT)
187 go func(sig chan os.Signal) {
194 // stop the underlying Docker container.
195 func (runner *ContainerRunner) stop() {
196 runner.cStateLock.Lock()
197 defer runner.cStateLock.Unlock()
198 if runner.cCancelled {
201 runner.cCancelled = true
203 timeout := time.Duration(10)
204 err := runner.Docker.ContainerStop(context.TODO(), runner.ContainerID, &(timeout))
206 log.Printf("StopContainer failed: %s", err)
211 // LoadImage determines the docker image id from the container record and
212 // checks if it is available in the local Docker image store. If not, it loads
213 // the image from Keep.
214 func (runner *ContainerRunner) LoadImage() (err error) {
216 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
218 var collection arvados.Collection
219 err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
221 return fmt.Errorf("While getting container image collection: %v", err)
223 manifest := manifest.Manifest{Text: collection.ManifestText}
224 var img, imageID string
225 for ms := range manifest.StreamIter() {
226 img = ms.FileStreamSegments[0].Name
227 if !strings.HasSuffix(img, ".tar") {
228 return fmt.Errorf("First file in the container image collection does not end in .tar")
230 imageID = img[:len(img)-4]
233 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
235 _, _, err = runner.Docker.ImageInspectWithRaw(context.TODO(), imageID)
237 runner.CrunchLog.Print("Loading Docker image from keep")
239 var readCloser io.ReadCloser
240 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
242 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
245 response, err := runner.Docker.ImageLoad(context.TODO(), readCloser, false)
247 return fmt.Errorf("While loading container image into Docker: %v", err)
249 response.Body.Close()
251 runner.CrunchLog.Print("Docker image is available")
254 runner.ContainerConfig.Image = imageID
259 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
260 c = exec.Command("arv-mount", arvMountCmd...)
262 // Copy our environment, but override ARVADOS_API_TOKEN with
263 // the container auth token.
265 for _, s := range os.Environ() {
266 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
267 c.Env = append(c.Env, s)
270 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
272 nt := NewThrottledLogger(runner.NewLogWriter("arv-mount"))
281 statReadme := make(chan bool)
282 runner.ArvMountExit = make(chan error)
287 time.Sleep(100 * time.Millisecond)
288 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
298 runner.ArvMountExit <- c.Wait()
299 close(runner.ArvMountExit)
305 case err := <-runner.ArvMountExit:
306 runner.ArvMount = nil
314 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
315 if runner.ArvMountPoint == "" {
316 runner.ArvMountPoint, err = runner.MkTempDir("", prefix)
321 func (runner *ContainerRunner) SetupMounts() (err error) {
322 err = runner.SetupArvMountPoint("keep")
324 return fmt.Errorf("While creating keep mount temp dir: %v", err)
327 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.ArvMountPoint)
331 arvMountCmd := []string{"--foreground", "--allow-other", "--read-write"}
333 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
334 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
337 collectionPaths := []string{}
339 needCertMount := true
342 for bind, _ := range runner.Container.Mounts {
343 binds = append(binds, bind)
347 for _, bind := range binds {
348 mnt := runner.Container.Mounts[bind]
349 if bind == "stdout" || bind == "stderr" {
350 // Is it a "file" mount kind?
351 if mnt.Kind != "file" {
352 return fmt.Errorf("Unsupported mount kind '%s' for %s. Only 'file' is supported.", mnt.Kind, bind)
355 // Does path start with OutputPath?
356 prefix := runner.Container.OutputPath
357 if !strings.HasSuffix(prefix, "/") {
360 if !strings.HasPrefix(mnt.Path, prefix) {
361 return fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
366 // Is it a "collection" mount kind?
367 if mnt.Kind != "collection" && mnt.Kind != "json" {
368 return fmt.Errorf("Unsupported mount kind '%s' for stdin. Only 'collection' or 'json' are supported.", mnt.Kind)
372 if bind == "/etc/arvados/ca-certificates.crt" {
373 needCertMount = false
376 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
377 if mnt.Kind != "collection" {
378 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
383 case mnt.Kind == "collection":
385 if mnt.UUID != "" && mnt.PortableDataHash != "" {
386 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
390 return fmt.Errorf("Writing to existing collections currently not permitted.")
393 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
394 } else if mnt.PortableDataHash != "" {
396 return fmt.Errorf("Can never write to a collection specified by portable data hash")
398 idx := strings.Index(mnt.PortableDataHash, "/")
400 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
401 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
402 runner.Container.Mounts[bind] = mnt
404 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
405 if mnt.Path != "" && mnt.Path != "." {
406 if strings.HasPrefix(mnt.Path, "./") {
407 mnt.Path = mnt.Path[2:]
408 } else if strings.HasPrefix(mnt.Path, "/") {
409 mnt.Path = mnt.Path[1:]
411 src += "/" + mnt.Path
414 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
415 arvMountCmd = append(arvMountCmd, "--mount-tmp")
416 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
420 if bind == runner.Container.OutputPath {
421 runner.HostOutputDir = src
422 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
423 return fmt.Errorf("Writable mount points are not permitted underneath the output_path: %v", bind)
425 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
427 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
429 collectionPaths = append(collectionPaths, src)
431 case mnt.Kind == "tmp" && bind == runner.Container.OutputPath:
432 runner.HostOutputDir, err = runner.MkTempDir("", "")
434 return fmt.Errorf("While creating mount temp dir: %v", err)
436 st, staterr := os.Stat(runner.HostOutputDir)
438 return fmt.Errorf("While Stat on temp dir: %v", staterr)
440 err = os.Chmod(runner.HostOutputDir, st.Mode()|os.ModeSetgid|0777)
442 return fmt.Errorf("While Chmod temp dir: %v", err)
444 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.HostOutputDir)
445 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", runner.HostOutputDir, bind))
447 case mnt.Kind == "tmp":
448 runner.Binds = append(runner.Binds, bind)
450 case mnt.Kind == "json":
451 jsondata, err := json.Marshal(mnt.Content)
453 return fmt.Errorf("encoding json data: %v", err)
455 // Create a tempdir with a single file
456 // (instead of just a tempfile): this way we
457 // can ensure the file is world-readable
458 // inside the container, without having to
459 // make it world-readable on the docker host.
460 tmpdir, err := runner.MkTempDir("", "")
462 return fmt.Errorf("creating temp dir: %v", err)
464 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
465 tmpfn := filepath.Join(tmpdir, "mountdata.json")
466 err = ioutil.WriteFile(tmpfn, jsondata, 0644)
468 return fmt.Errorf("writing temp file: %v", err)
470 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
474 if runner.HostOutputDir == "" {
475 return fmt.Errorf("Output path does not correspond to a writable mount point")
478 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
479 for _, certfile := range arvadosclient.CertFiles {
480 _, err := os.Stat(certfile)
482 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
489 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
491 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
493 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
495 token, err := runner.ContainerToken()
497 return fmt.Errorf("could not get container token: %s", err)
500 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
502 return fmt.Errorf("While trying to start arv-mount: %v", err)
505 for _, p := range collectionPaths {
508 return fmt.Errorf("While checking that input files exist: %v", err)
515 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
516 // Handle docker log protocol
517 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
519 header := make([]byte, 8)
521 _, readerr := io.ReadAtLeast(containerReader, header, 8)
524 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
527 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
530 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
535 if readerr != io.EOF {
536 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
539 closeerr := runner.Stdout.Close()
541 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
544 closeerr = runner.Stderr.Close()
546 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
549 if runner.statReporter != nil {
550 runner.statReporter.Stop()
551 closeerr = runner.statLogger.Close()
553 runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
557 runner.loggingDone <- true
558 close(runner.loggingDone)
564 func (runner *ContainerRunner) StartCrunchstat() {
565 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
566 runner.statReporter = &crunchstat.Reporter{
567 CID: runner.ContainerID,
568 Logger: log.New(runner.statLogger, "", 0),
569 CgroupParent: runner.expectCgroupParent,
570 CgroupRoot: runner.cgroupRoot,
571 PollPeriod: runner.statInterval,
573 runner.statReporter.Start()
576 type infoCommand struct {
581 // Gather node information and store it on the log for debugging
583 func (runner *ContainerRunner) LogNodeInfo() (err error) {
584 w := runner.NewLogWriter("node-info")
585 logger := log.New(w, "node-info", 0)
587 commands := []infoCommand{
589 label: "Host Information",
590 cmd: []string{"uname", "-a"},
593 label: "CPU Information",
594 cmd: []string{"cat", "/proc/cpuinfo"},
597 label: "Memory Information",
598 cmd: []string{"cat", "/proc/meminfo"},
602 cmd: []string{"df", "-m", "/", os.TempDir()},
605 label: "Disk INodes",
606 cmd: []string{"df", "-i", "/", os.TempDir()},
610 // Run commands with informational output to be logged.
612 for _, command := range commands {
613 out, err = exec.Command(command.cmd[0], command.cmd[1:]...).CombinedOutput()
615 return fmt.Errorf("While running command %q: %v",
618 logger.Println(command.label)
619 for _, line := range strings.Split(string(out), "\n") {
620 logger.Println(" ", line)
626 return fmt.Errorf("While closing node-info logs: %v", err)
631 // Get and save the raw JSON container record from the API server
632 func (runner *ContainerRunner) LogContainerRecord() (err error) {
635 runner.Container.UUID,
637 runner.LogCollection.Open("container.json"),
639 // Get Container record JSON from the API Server
640 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
642 return fmt.Errorf("While retrieving container record from the API server: %v", err)
645 // Read the API server response as []byte
646 json_bytes, err := ioutil.ReadAll(reader)
648 return fmt.Errorf("While reading container record API server response: %v", err)
650 // Decode the JSON []byte
651 var cr map[string]interface{}
652 if err = json.Unmarshal(json_bytes, &cr); err != nil {
653 return fmt.Errorf("While decoding the container record JSON response: %v", err)
655 // Re-encode it using indentation to improve readability
656 enc := json.NewEncoder(w)
657 enc.SetIndent("", " ")
658 if err = enc.Encode(cr); err != nil {
659 return fmt.Errorf("While logging the JSON container record: %v", err)
663 return fmt.Errorf("While closing container.json log: %v", err)
668 // AttachStreams connects the docker container stdin, stdout and stderr logs
669 // to the Arvados logger which logs to Keep and the API server logs table.
670 func (runner *ContainerRunner) AttachStreams() (err error) {
672 runner.CrunchLog.Print("Attaching container streams")
674 // If stdin mount is provided, attach it to the docker container
675 var stdinRdr keepclient.Reader
677 if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
678 if stdinMnt.Kind == "collection" {
679 var stdinColl arvados.Collection
680 collId := stdinMnt.UUID
682 collId = stdinMnt.PortableDataHash
684 err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
686 return fmt.Errorf("While getting stding collection: %v", err)
689 stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
690 if os.IsNotExist(err) {
691 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
692 } else if err != nil {
693 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
696 defer stdinRdr.Close()
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)
741 response.Conn.Close()
743 } else if len(stdinJson) != 0 {
745 _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
747 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
750 response.Conn.Close()
754 go runner.ProcessDockerAttach(response.Reader)
759 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
760 stdoutPath := mntPath[len(runner.Container.OutputPath):]
761 index := strings.LastIndex(stdoutPath, "/")
763 subdirs := stdoutPath[:index]
765 st, err := os.Stat(runner.HostOutputDir)
767 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
769 stdoutPath := path.Join(runner.HostOutputDir, subdirs)
770 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
772 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
776 stdoutFile, err := os.Create(path.Join(runner.HostOutputDir, stdoutPath))
778 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
781 return stdoutFile, nil
784 // CreateContainer creates the docker container.
785 func (runner *ContainerRunner) CreateContainer() error {
786 runner.CrunchLog.Print("Creating Docker container")
788 runner.ContainerConfig.Cmd = runner.Container.Command
789 if runner.Container.Cwd != "." {
790 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
793 for k, v := range runner.Container.Environment {
794 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
797 runner.HostConfig = dockercontainer.HostConfig{
799 Cgroup: dockercontainer.CgroupSpec(runner.setCgroupParent),
800 LogConfig: dockercontainer.LogConfig{
805 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
806 tok, err := runner.ContainerToken()
810 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
811 "ARVADOS_API_TOKEN="+tok,
812 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
813 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
815 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
817 if runner.enableNetwork == "always" {
818 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
820 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
824 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
826 return fmt.Errorf("While creating container: %v", err)
829 runner.ContainerID = createdBody.ID
831 return runner.AttachStreams()
834 // StartContainer starts the docker container created by CreateContainer.
835 func (runner *ContainerRunner) StartContainer() error {
836 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
837 runner.cStateLock.Lock()
838 defer runner.cStateLock.Unlock()
839 if runner.cCancelled {
842 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
843 dockertypes.ContainerStartOptions{})
845 return fmt.Errorf("could not start container: %v", err)
847 runner.cStarted = true
851 // WaitFinish waits for the container to terminate, capture the exit code, and
852 // close the stdout/stderr logging.
853 func (runner *ContainerRunner) WaitFinish() error {
854 runner.CrunchLog.Print("Waiting for container to finish")
856 waitDocker, err := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID)
858 return fmt.Errorf("container wait: %v", err)
861 runner.CrunchLog.Printf("Container exited with code: %v", waitDocker)
862 code := int(waitDocker)
863 runner.ExitCode = &code
865 waitMount := runner.ArvMountExit
867 case err := <-waitMount:
868 runner.CrunchLog.Printf("arv-mount exited before container finished: %v", err)
874 // wait for stdout/stderr to complete
880 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
881 func (runner *ContainerRunner) CaptureOutput() error {
882 if runner.finalState != "Complete" {
886 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
887 // Output may have been set directly by the container, so
888 // refresh the container record to check.
889 err := runner.ArvClient.Get("containers", runner.Container.UUID,
890 nil, &runner.Container)
894 if runner.Container.Output != "" {
895 // Container output is already set.
896 runner.OutputPDH = &runner.Container.Output
901 if runner.HostOutputDir == "" {
905 _, err := os.Stat(runner.HostOutputDir)
907 return fmt.Errorf("While checking host output path: %v", err)
910 var manifestText string
912 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
913 _, err = os.Stat(collectionMetafile)
916 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
917 manifestText, err = cw.WriteTree(runner.HostOutputDir, runner.CrunchLog.Logger)
919 return fmt.Errorf("While uploading output files: %v", err)
922 // FUSE mount directory
923 file, openerr := os.Open(collectionMetafile)
925 return fmt.Errorf("While opening FUSE metafile: %v", err)
929 var rec arvados.Collection
930 err = json.NewDecoder(file).Decode(&rec)
932 return fmt.Errorf("While reading FUSE metafile: %v", err)
934 manifestText = rec.ManifestText
937 // Pre-populate output from the configured mount points
939 for bind, _ := range runner.Container.Mounts {
940 binds = append(binds, bind)
944 for _, bind := range binds {
945 mnt := runner.Container.Mounts[bind]
947 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
949 if bindSuffix == bind || len(bindSuffix) <= 0 {
950 // either does not start with OutputPath or is OutputPath itself
954 if mnt.ExcludeFromOutput == true {
958 // append to manifest_text
959 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
964 manifestText = manifestText + m
968 var response arvados.Collection
969 manifest := manifest.Manifest{Text: manifestText}
970 manifestText = manifest.Extract(".", ".").Text
971 err = runner.ArvClient.Create("collections",
973 "ensure_unique_name": true,
974 "collection": arvadosclient.Dict{
976 "name": "output for " + runner.Container.UUID,
977 "manifest_text": manifestText}},
980 return fmt.Errorf("While creating output collection: %v", err)
982 runner.OutputPDH = &response.PortableDataHash
986 var outputCollections = make(map[string]arvados.Collection)
988 // Fetch the collection for the mnt.PortableDataHash
989 // Return the manifest_text fragment corresponding to the specified mnt.Path
990 // after making any required updates.
992 // If mnt.Path is not specified,
993 // return the entire manifest_text after replacing any "." with bindSuffix
994 // If mnt.Path corresponds to one stream,
995 // return the manifest_text for that stream after replacing that stream name with bindSuffix
996 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
997 // for that stream after replacing stream name with bindSuffix minus the last word
998 // and the file name with last word of the bindSuffix
999 // Allowed path examples:
1001 // "path":"/subdir1"
1002 // "path":"/subdir1/subdir2"
1003 // "path":"/subdir/filename" etc
1004 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1005 collection := outputCollections[mnt.PortableDataHash]
1006 if collection.PortableDataHash == "" {
1007 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1009 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1011 outputCollections[mnt.PortableDataHash] = collection
1014 if collection.ManifestText == "" {
1015 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1019 mft := manifest.Manifest{Text: collection.ManifestText}
1020 extracted := mft.Extract(mnt.Path, bindSuffix)
1021 if extracted.Err != nil {
1022 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1024 return extracted.Text, nil
1027 func (runner *ContainerRunner) CleanupDirs() {
1028 if runner.ArvMount != nil {
1029 umount := exec.Command("fusermount", "-z", "-u", runner.ArvMountPoint)
1030 umnterr := umount.Run()
1032 runner.CrunchLog.Printf("While running fusermount: %v", umnterr)
1035 mnterr := <-runner.ArvMountExit
1037 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
1041 for _, tmpdir := range runner.CleanupTempDir {
1042 rmerr := os.RemoveAll(tmpdir)
1044 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1049 // CommitLogs posts the collection containing the final container logs.
1050 func (runner *ContainerRunner) CommitLogs() error {
1051 runner.CrunchLog.Print(runner.finalState)
1052 runner.CrunchLog.Close()
1054 // Closing CrunchLog above allows it to be committed to Keep at this
1055 // point, but re-open crunch log with ArvClient in case there are any
1056 // other further (such as failing to write the log to Keep!) while
1058 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{runner.ArvClient, runner.Container.UUID,
1061 if runner.LogsPDH != nil {
1062 // If we have already assigned something to LogsPDH,
1063 // we must be closing the re-opened log, which won't
1064 // end up getting attached to the container record and
1065 // therefore doesn't need to be saved as a collection
1066 // -- it exists only to send logs to other channels.
1070 mt, err := runner.LogCollection.ManifestText()
1072 return fmt.Errorf("While creating log manifest: %v", err)
1075 var response arvados.Collection
1076 err = runner.ArvClient.Create("collections",
1078 "ensure_unique_name": true,
1079 "collection": arvadosclient.Dict{
1081 "name": "logs for " + runner.Container.UUID,
1082 "manifest_text": mt}},
1085 return fmt.Errorf("While creating log collection: %v", err)
1087 runner.LogsPDH = &response.PortableDataHash
1091 // UpdateContainerRunning updates the container state to "Running"
1092 func (runner *ContainerRunner) UpdateContainerRunning() error {
1093 runner.cStateLock.Lock()
1094 defer runner.cStateLock.Unlock()
1095 if runner.cCancelled {
1098 return runner.ArvClient.Update("containers", runner.Container.UUID,
1099 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1102 // ContainerToken returns the api_token the container (and any
1103 // arv-mount processes) are allowed to use.
1104 func (runner *ContainerRunner) ContainerToken() (string, error) {
1105 if runner.token != "" {
1106 return runner.token, nil
1109 var auth arvados.APIClientAuthorization
1110 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1114 runner.token = auth.APIToken
1115 return runner.token, nil
1118 // UpdateContainerComplete updates the container record state on API
1119 // server to "Complete" or "Cancelled"
1120 func (runner *ContainerRunner) UpdateContainerFinal() error {
1121 update := arvadosclient.Dict{}
1122 update["state"] = runner.finalState
1123 if runner.LogsPDH != nil {
1124 update["log"] = *runner.LogsPDH
1126 if runner.finalState == "Complete" {
1127 if runner.ExitCode != nil {
1128 update["exit_code"] = *runner.ExitCode
1130 if runner.OutputPDH != nil {
1131 update["output"] = *runner.OutputPDH
1134 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1137 // IsCancelled returns the value of Cancelled, with goroutine safety.
1138 func (runner *ContainerRunner) IsCancelled() bool {
1139 runner.cStateLock.Lock()
1140 defer runner.cStateLock.Unlock()
1141 return runner.cCancelled
1144 // NewArvLogWriter creates an ArvLogWriter
1145 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1146 return &ArvLogWriter{runner.ArvClient, runner.Container.UUID, name, runner.LogCollection.Open(name + ".txt")}
1149 // Run the full container lifecycle.
1150 func (runner *ContainerRunner) Run() (err error) {
1151 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1153 hostname, hosterr := os.Hostname()
1155 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1157 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1160 // Clean up temporary directories _after_ finalizing
1161 // everything (if we've made any by then)
1162 defer runner.CleanupDirs()
1164 runner.finalState = "Queued"
1167 // checkErr prints e (unless it's nil) and sets err to
1168 // e (unless err is already non-nil). Thus, if err
1169 // hasn't already been assigned when Run() returns,
1170 // this cleanup func will cause Run() to return the
1171 // first non-nil error that is passed to checkErr().
1172 checkErr := func(e error) {
1176 runner.CrunchLog.Print(e)
1182 // Log the error encountered in Run(), if any
1185 if runner.finalState == "Queued" {
1186 runner.CrunchLog.Close()
1187 runner.UpdateContainerFinal()
1191 if runner.IsCancelled() {
1192 runner.finalState = "Cancelled"
1193 // but don't return yet -- we still want to
1194 // capture partial output and write logs
1197 checkErr(runner.CaptureOutput())
1198 checkErr(runner.CommitLogs())
1199 checkErr(runner.UpdateContainerFinal())
1201 // The real log is already closed, but then we opened
1202 // a new one in case we needed to log anything while
1204 runner.CrunchLog.Close()
1207 err = runner.ArvClient.Get("containers", runner.Container.UUID, nil, &runner.Container)
1209 err = fmt.Errorf("While getting container record: %v", err)
1213 // setup signal handling
1214 runner.SetupSignals()
1216 // check for and/or load image
1217 err = runner.LoadImage()
1219 runner.finalState = "Cancelled"
1220 err = fmt.Errorf("While loading container image: %v", err)
1224 // set up FUSE mount and binds
1225 err = runner.SetupMounts()
1227 runner.finalState = "Cancelled"
1228 err = fmt.Errorf("While setting up mounts: %v", err)
1232 err = runner.CreateContainer()
1237 // Gather and record node information
1238 err = runner.LogNodeInfo()
1242 // Save container.json record on log collection
1243 err = runner.LogContainerRecord()
1248 runner.StartCrunchstat()
1250 if runner.IsCancelled() {
1254 err = runner.UpdateContainerRunning()
1258 runner.finalState = "Cancelled"
1260 err = runner.StartContainer()
1265 err = runner.WaitFinish()
1267 runner.finalState = "Complete"
1272 // NewContainerRunner creates a new container runner.
1273 func NewContainerRunner(api IArvadosClient,
1275 docker ThinDockerClient,
1276 containerUUID string) *ContainerRunner {
1278 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1279 cr.NewLogWriter = cr.NewArvLogWriter
1280 cr.RunArvMount = cr.ArvMountCmd
1281 cr.MkTempDir = ioutil.TempDir
1282 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1283 cr.Container.UUID = containerUUID
1284 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1285 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1290 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1291 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1292 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1293 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1294 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1295 enableNetwork := flag.String("container-enable-networking", "default",
1296 `Specify if networking should be enabled for container. One of 'default', 'always':
1297 default: only enable networking if container requests it.
1298 always: containers always have networking enabled
1300 networkMode := flag.String("container-network-mode", "default",
1301 `Set networking mode for container. Corresponds to Docker network mode (--net).
1305 containerId := flag.Arg(0)
1307 if *caCertsPath != "" {
1308 arvadosclient.CertFiles = []string{*caCertsPath}
1311 api, err := arvadosclient.MakeArvadosClient()
1313 log.Fatalf("%s: %v", containerId, err)
1317 var kc *keepclient.KeepClient
1318 kc, err = keepclient.MakeKeepClient(api)
1320 log.Fatalf("%s: %v", containerId, err)
1324 var docker *dockerclient.Client
1325 // API version 1.21 corresponds to Docker 1.9, which is currently the
1326 // minimum version we want to support.
1327 docker, err = dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1329 log.Fatalf("%s: %v", containerId, err)
1332 dockerClientProxy := ThinDockerClientProxy{Docker: docker}
1334 cr := NewContainerRunner(api, kc, dockerClientProxy, containerId)
1335 cr.statInterval = *statInterval
1336 cr.cgroupRoot = *cgroupRoot
1337 cr.expectCgroupParent = *cgroupParent
1338 cr.enableNetwork = *enableNetwork
1339 cr.networkMode = *networkMode
1340 if *cgroupParentSubsystem != "" {
1341 p := findCgroup(*cgroupParentSubsystem)
1342 cr.setCgroupParent = p
1343 cr.expectCgroupParent = p
1348 log.Fatalf("%s: %v", containerId, err)