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":
435 tmpdir, err = runner.MkTempDir("", "")
437 return fmt.Errorf("While creating mount temp dir: %v", err)
439 st, staterr := os.Stat(tmpdir)
441 return fmt.Errorf("While Stat on temp dir: %v", staterr)
443 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
445 return fmt.Errorf("While Chmod temp dir: %v", err)
447 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
448 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", tmpdir, bind))
449 if bind == runner.Container.OutputPath {
450 runner.HostOutputDir = tmpdir
453 case mnt.Kind == "json":
454 jsondata, err := json.Marshal(mnt.Content)
456 return fmt.Errorf("encoding json data: %v", err)
458 // Create a tempdir with a single file
459 // (instead of just a tempfile): this way we
460 // can ensure the file is world-readable
461 // inside the container, without having to
462 // make it world-readable on the docker host.
463 tmpdir, err := runner.MkTempDir("", "")
465 return fmt.Errorf("creating temp dir: %v", err)
467 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
468 tmpfn := filepath.Join(tmpdir, "mountdata.json")
469 err = ioutil.WriteFile(tmpfn, jsondata, 0644)
471 return fmt.Errorf("writing temp file: %v", err)
473 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
477 if runner.HostOutputDir == "" {
478 return fmt.Errorf("Output path does not correspond to a writable mount point")
481 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
482 for _, certfile := range arvadosclient.CertFiles {
483 _, err := os.Stat(certfile)
485 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
492 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
494 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
496 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
498 token, err := runner.ContainerToken()
500 return fmt.Errorf("could not get container token: %s", err)
503 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
505 return fmt.Errorf("While trying to start arv-mount: %v", err)
508 for _, p := range collectionPaths {
511 return fmt.Errorf("While checking that input files exist: %v", err)
518 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
519 // Handle docker log protocol
520 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
522 header := make([]byte, 8)
524 _, readerr := io.ReadAtLeast(containerReader, header, 8)
527 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
530 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
533 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
538 if readerr != io.EOF {
539 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
542 closeerr := runner.Stdout.Close()
544 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
547 closeerr = runner.Stderr.Close()
549 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
552 if runner.statReporter != nil {
553 runner.statReporter.Stop()
554 closeerr = runner.statLogger.Close()
556 runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
560 runner.loggingDone <- true
561 close(runner.loggingDone)
567 func (runner *ContainerRunner) StartCrunchstat() {
568 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
569 runner.statReporter = &crunchstat.Reporter{
570 CID: runner.ContainerID,
571 Logger: log.New(runner.statLogger, "", 0),
572 CgroupParent: runner.expectCgroupParent,
573 CgroupRoot: runner.cgroupRoot,
574 PollPeriod: runner.statInterval,
576 runner.statReporter.Start()
579 type infoCommand struct {
584 // Gather node information and store it on the log for debugging
586 func (runner *ContainerRunner) LogNodeInfo() (err error) {
587 w := runner.NewLogWriter("node-info")
588 logger := log.New(w, "node-info", 0)
590 commands := []infoCommand{
592 label: "Host Information",
593 cmd: []string{"uname", "-a"},
596 label: "CPU Information",
597 cmd: []string{"cat", "/proc/cpuinfo"},
600 label: "Memory Information",
601 cmd: []string{"cat", "/proc/meminfo"},
605 cmd: []string{"df", "-m", "/", os.TempDir()},
608 label: "Disk INodes",
609 cmd: []string{"df", "-i", "/", os.TempDir()},
613 // Run commands with informational output to be logged.
615 for _, command := range commands {
616 out, err = exec.Command(command.cmd[0], command.cmd[1:]...).CombinedOutput()
618 return fmt.Errorf("While running command %q: %v",
621 logger.Println(command.label)
622 for _, line := range strings.Split(string(out), "\n") {
623 logger.Println(" ", line)
629 return fmt.Errorf("While closing node-info logs: %v", err)
634 // Get and save the raw JSON container record from the API server
635 func (runner *ContainerRunner) LogContainerRecord() (err error) {
637 ArvClient: runner.ArvClient,
638 UUID: runner.Container.UUID,
639 loggingStream: "container",
640 writeCloser: runner.LogCollection.Open("container.json"),
643 // Get Container record JSON from the API Server
644 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
646 return fmt.Errorf("While retrieving container record from the API server: %v", err)
649 // Read the API server response as []byte
650 json_bytes, err := ioutil.ReadAll(reader)
652 return fmt.Errorf("While reading container record API server response: %v", err)
654 // Decode the JSON []byte
655 var cr map[string]interface{}
656 if err = json.Unmarshal(json_bytes, &cr); err != nil {
657 return fmt.Errorf("While decoding the container record JSON response: %v", err)
659 // Re-encode it using indentation to improve readability
660 enc := json.NewEncoder(w)
661 enc.SetIndent("", " ")
662 if err = enc.Encode(cr); err != nil {
663 return fmt.Errorf("While logging the JSON container record: %v", err)
667 return fmt.Errorf("While closing container.json log: %v", err)
672 // AttachStreams connects the docker container stdin, stdout and stderr logs
673 // to the Arvados logger which logs to Keep and the API server logs table.
674 func (runner *ContainerRunner) AttachStreams() (err error) {
676 runner.CrunchLog.Print("Attaching container streams")
678 // If stdin mount is provided, attach it to the docker container
679 var stdinRdr keepclient.Reader
681 if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
682 if stdinMnt.Kind == "collection" {
683 var stdinColl arvados.Collection
684 collId := stdinMnt.UUID
686 collId = stdinMnt.PortableDataHash
688 err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
690 return fmt.Errorf("While getting stding collection: %v", err)
693 stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
694 if os.IsNotExist(err) {
695 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
696 } else if err != nil {
697 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
699 } else if stdinMnt.Kind == "json" {
700 stdinJson, err = json.Marshal(stdinMnt.Content)
702 return fmt.Errorf("While encoding stdin json data: %v", err)
707 stdinUsed := stdinRdr != nil || len(stdinJson) != 0
708 response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
709 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
711 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
714 runner.loggingDone = make(chan bool)
716 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
717 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
721 runner.Stdout = stdoutFile
723 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
726 if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
727 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
731 runner.Stderr = stderrFile
733 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
738 _, err := io.Copy(response.Conn, stdinRdr)
740 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
744 response.CloseWrite()
746 } else if len(stdinJson) != 0 {
748 _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
750 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
753 response.CloseWrite()
757 go runner.ProcessDockerAttach(response.Reader)
762 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
763 stdoutPath := mntPath[len(runner.Container.OutputPath):]
764 index := strings.LastIndex(stdoutPath, "/")
766 subdirs := stdoutPath[:index]
768 st, err := os.Stat(runner.HostOutputDir)
770 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
772 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
773 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
775 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
779 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
781 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
784 return stdoutFile, nil
787 // CreateContainer creates the docker container.
788 func (runner *ContainerRunner) CreateContainer() error {
789 runner.CrunchLog.Print("Creating Docker container")
791 runner.ContainerConfig.Cmd = runner.Container.Command
792 if runner.Container.Cwd != "." {
793 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
796 for k, v := range runner.Container.Environment {
797 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
800 runner.ContainerConfig.Volumes = runner.Volumes
802 runner.HostConfig = dockercontainer.HostConfig{
804 Cgroup: dockercontainer.CgroupSpec(runner.setCgroupParent),
805 LogConfig: dockercontainer.LogConfig{
810 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
811 tok, err := runner.ContainerToken()
815 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
816 "ARVADOS_API_TOKEN="+tok,
817 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
818 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
820 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
822 if runner.enableNetwork == "always" {
823 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
825 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
829 _, stdinUsed := runner.Container.Mounts["stdin"]
830 runner.ContainerConfig.OpenStdin = stdinUsed
831 runner.ContainerConfig.StdinOnce = stdinUsed
832 runner.ContainerConfig.AttachStdin = stdinUsed
833 runner.ContainerConfig.AttachStdout = true
834 runner.ContainerConfig.AttachStderr = true
836 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
838 return fmt.Errorf("While creating container: %v", err)
841 runner.ContainerID = createdBody.ID
843 return runner.AttachStreams()
846 // StartContainer starts the docker container created by CreateContainer.
847 func (runner *ContainerRunner) StartContainer() error {
848 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
849 runner.cStateLock.Lock()
850 defer runner.cStateLock.Unlock()
851 if runner.cCancelled {
854 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
855 dockertypes.ContainerStartOptions{})
857 return fmt.Errorf("could not start container: %v", err)
859 runner.cStarted = true
863 // WaitFinish waits for the container to terminate, capture the exit code, and
864 // close the stdout/stderr logging.
865 func (runner *ContainerRunner) WaitFinish() error {
866 runner.CrunchLog.Print("Waiting for container to finish")
868 waitDocker, err := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID)
870 return fmt.Errorf("container wait: %v", err)
873 runner.CrunchLog.Printf("Container exited with code: %v", waitDocker)
874 code := int(waitDocker)
875 runner.ExitCode = &code
877 waitMount := runner.ArvMountExit
879 case err := <-waitMount:
880 runner.CrunchLog.Printf("arv-mount exited before container finished: %v", err)
886 // wait for stdout/stderr to complete
892 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
893 func (runner *ContainerRunner) CaptureOutput() error {
894 if runner.finalState != "Complete" {
898 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
899 // Output may have been set directly by the container, so
900 // refresh the container record to check.
901 err := runner.ArvClient.Get("containers", runner.Container.UUID,
902 nil, &runner.Container)
906 if runner.Container.Output != "" {
907 // Container output is already set.
908 runner.OutputPDH = &runner.Container.Output
913 if runner.HostOutputDir == "" {
917 _, err := os.Stat(runner.HostOutputDir)
919 return fmt.Errorf("While checking host output path: %v", err)
922 // Pre-populate output from the configured mount points
924 for bind, _ := range runner.Container.Mounts {
925 binds = append(binds, bind)
929 var manifestText string
931 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
932 _, err = os.Stat(collectionMetafile)
936 // Find symlinks to arv-mounted files & dirs.
937 err = filepath.Walk(runner.HostOutputDir, func(path string, info os.FileInfo, err error) error {
941 if info.Mode()&os.ModeSymlink == 0 {
944 // read link to get container internal path
946 tgt, err = os.Readlink(path)
950 if !strings.HasPrefix(tgt, "/") {
951 // Link is relative, don't handle it
954 // go through mounts and reverse map to collection reference
955 for _, bind := range binds {
956 mnt := runner.Container.Mounts[bind]
957 if tgt == bind || strings.HasPrefix(tgt, bind+"/") && mnt.Kind == "collection" {
958 // get path relative to bind
959 sourceSuffix := tgt[len(bind):]
960 // get path relative to output dir
961 bindSuffix := path[len(runner.HostOutputDir):]
963 // Copy mount and adjust the path to add path relative to the bind
965 adjustedMount.Path = filepath.Join(adjustedMount.Path, sourceSuffix)
969 m, err = runner.getCollectionManifestForPath(adjustedMount, bindSuffix)
973 manifestText = manifestText + m
974 // delete symlink so WriteTree won't try to to dereference it.
982 return fmt.Errorf("While checking output symlinks: %v", err)
985 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
987 m, err = cw.WriteTree(runner.HostOutputDir, runner.CrunchLog.Logger)
988 manifestText = manifestText + m
990 return fmt.Errorf("While uploading output files: %v", err)
993 // FUSE mount directory
994 file, openerr := os.Open(collectionMetafile)
996 return fmt.Errorf("While opening FUSE metafile: %v", err)
1000 var rec arvados.Collection
1001 err = json.NewDecoder(file).Decode(&rec)
1003 return fmt.Errorf("While reading FUSE metafile: %v", err)
1005 manifestText = rec.ManifestText
1008 for _, bind := range binds {
1009 mnt := runner.Container.Mounts[bind]
1011 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
1013 if bindSuffix == bind || len(bindSuffix) <= 0 {
1014 // either does not start with OutputPath or is OutputPath itself
1018 if mnt.ExcludeFromOutput == true {
1022 // append to manifest_text
1023 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
1028 manifestText = manifestText + m
1032 var response arvados.Collection
1033 manifest := manifest.Manifest{Text: manifestText}
1034 manifestText = manifest.Extract(".", ".").Text
1035 err = runner.ArvClient.Create("collections",
1037 "ensure_unique_name": true,
1038 "collection": arvadosclient.Dict{
1040 "name": "output for " + runner.Container.UUID,
1041 "manifest_text": manifestText}},
1044 return fmt.Errorf("While creating output collection: %v", err)
1046 runner.OutputPDH = &response.PortableDataHash
1050 var outputCollections = make(map[string]arvados.Collection)
1052 // Fetch the collection for the mnt.PortableDataHash
1053 // Return the manifest_text fragment corresponding to the specified mnt.Path
1054 // after making any required updates.
1056 // If mnt.Path is not specified,
1057 // return the entire manifest_text after replacing any "." with bindSuffix
1058 // If mnt.Path corresponds to one stream,
1059 // return the manifest_text for that stream after replacing that stream name with bindSuffix
1060 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1061 // for that stream after replacing stream name with bindSuffix minus the last word
1062 // and the file name with last word of the bindSuffix
1063 // Allowed path examples:
1065 // "path":"/subdir1"
1066 // "path":"/subdir1/subdir2"
1067 // "path":"/subdir/filename" etc
1068 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1069 collection := outputCollections[mnt.PortableDataHash]
1070 if collection.PortableDataHash == "" {
1071 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1073 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1075 outputCollections[mnt.PortableDataHash] = collection
1078 if collection.ManifestText == "" {
1079 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1083 mft := manifest.Manifest{Text: collection.ManifestText}
1084 extracted := mft.Extract(mnt.Path, bindSuffix)
1085 if extracted.Err != nil {
1086 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1088 return extracted.Text, nil
1091 func (runner *ContainerRunner) CleanupDirs() {
1092 if runner.ArvMount != nil {
1093 umount := exec.Command("fusermount", "-z", "-u", runner.ArvMountPoint)
1094 umnterr := umount.Run()
1096 runner.CrunchLog.Printf("While running fusermount: %v", umnterr)
1099 mnterr := <-runner.ArvMountExit
1101 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
1105 for _, tmpdir := range runner.CleanupTempDir {
1106 rmerr := os.RemoveAll(tmpdir)
1108 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1113 // CommitLogs posts the collection containing the final container logs.
1114 func (runner *ContainerRunner) CommitLogs() error {
1115 runner.CrunchLog.Print(runner.finalState)
1116 runner.CrunchLog.Close()
1118 // Closing CrunchLog above allows it to be committed to Keep at this
1119 // point, but re-open crunch log with ArvClient in case there are any
1120 // other further (such as failing to write the log to Keep!) while
1122 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1123 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1125 if runner.LogsPDH != nil {
1126 // If we have already assigned something to LogsPDH,
1127 // we must be closing the re-opened log, which won't
1128 // end up getting attached to the container record and
1129 // therefore doesn't need to be saved as a collection
1130 // -- it exists only to send logs to other channels.
1134 mt, err := runner.LogCollection.ManifestText()
1136 return fmt.Errorf("While creating log manifest: %v", err)
1139 var response arvados.Collection
1140 err = runner.ArvClient.Create("collections",
1142 "ensure_unique_name": true,
1143 "collection": arvadosclient.Dict{
1145 "name": "logs for " + runner.Container.UUID,
1146 "manifest_text": mt}},
1149 return fmt.Errorf("While creating log collection: %v", err)
1151 runner.LogsPDH = &response.PortableDataHash
1155 // UpdateContainerRunning updates the container state to "Running"
1156 func (runner *ContainerRunner) UpdateContainerRunning() error {
1157 runner.cStateLock.Lock()
1158 defer runner.cStateLock.Unlock()
1159 if runner.cCancelled {
1162 return runner.ArvClient.Update("containers", runner.Container.UUID,
1163 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1166 // ContainerToken returns the api_token the container (and any
1167 // arv-mount processes) are allowed to use.
1168 func (runner *ContainerRunner) ContainerToken() (string, error) {
1169 if runner.token != "" {
1170 return runner.token, nil
1173 var auth arvados.APIClientAuthorization
1174 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1178 runner.token = auth.APIToken
1179 return runner.token, nil
1182 // UpdateContainerComplete updates the container record state on API
1183 // server to "Complete" or "Cancelled"
1184 func (runner *ContainerRunner) UpdateContainerFinal() error {
1185 update := arvadosclient.Dict{}
1186 update["state"] = runner.finalState
1187 if runner.LogsPDH != nil {
1188 update["log"] = *runner.LogsPDH
1190 if runner.finalState == "Complete" {
1191 if runner.ExitCode != nil {
1192 update["exit_code"] = *runner.ExitCode
1194 if runner.OutputPDH != nil {
1195 update["output"] = *runner.OutputPDH
1198 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1201 // IsCancelled returns the value of Cancelled, with goroutine safety.
1202 func (runner *ContainerRunner) IsCancelled() bool {
1203 runner.cStateLock.Lock()
1204 defer runner.cStateLock.Unlock()
1205 return runner.cCancelled
1208 // NewArvLogWriter creates an ArvLogWriter
1209 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1210 return &ArvLogWriter{ArvClient: runner.ArvClient, UUID: runner.Container.UUID, loggingStream: name,
1211 writeCloser: runner.LogCollection.Open(name + ".txt")}
1214 // Run the full container lifecycle.
1215 func (runner *ContainerRunner) Run() (err error) {
1216 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1218 hostname, hosterr := os.Hostname()
1220 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1222 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1225 // Clean up temporary directories _after_ finalizing
1226 // everything (if we've made any by then)
1227 defer runner.CleanupDirs()
1229 runner.finalState = "Queued"
1232 // checkErr prints e (unless it's nil) and sets err to
1233 // e (unless err is already non-nil). Thus, if err
1234 // hasn't already been assigned when Run() returns,
1235 // this cleanup func will cause Run() to return the
1236 // first non-nil error that is passed to checkErr().
1237 checkErr := func(e error) {
1241 runner.CrunchLog.Print(e)
1245 if runner.finalState == "Complete" {
1246 // There was an error in the finalization.
1247 runner.finalState = "Cancelled"
1251 // Log the error encountered in Run(), if any
1254 if runner.finalState == "Queued" {
1255 runner.CrunchLog.Close()
1256 runner.UpdateContainerFinal()
1260 if runner.IsCancelled() {
1261 runner.finalState = "Cancelled"
1262 // but don't return yet -- we still want to
1263 // capture partial output and write logs
1266 checkErr(runner.CaptureOutput())
1267 checkErr(runner.CommitLogs())
1268 checkErr(runner.UpdateContainerFinal())
1270 // The real log is already closed, but then we opened
1271 // a new one in case we needed to log anything while
1273 runner.CrunchLog.Close()
1276 err = runner.ArvClient.Get("containers", runner.Container.UUID, nil, &runner.Container)
1278 err = fmt.Errorf("While getting container record: %v", err)
1282 // setup signal handling
1283 runner.SetupSignals()
1285 // check for and/or load image
1286 err = runner.LoadImage()
1288 runner.finalState = "Cancelled"
1289 err = fmt.Errorf("While loading container image: %v", err)
1293 // set up FUSE mount and binds
1294 err = runner.SetupMounts()
1296 runner.finalState = "Cancelled"
1297 err = fmt.Errorf("While setting up mounts: %v", err)
1301 err = runner.CreateContainer()
1306 // Gather and record node information
1307 err = runner.LogNodeInfo()
1311 // Save container.json record on log collection
1312 err = runner.LogContainerRecord()
1317 runner.StartCrunchstat()
1319 if runner.IsCancelled() {
1323 err = runner.UpdateContainerRunning()
1327 runner.finalState = "Cancelled"
1329 err = runner.StartContainer()
1334 err = runner.WaitFinish()
1336 runner.finalState = "Complete"
1341 // NewContainerRunner creates a new container runner.
1342 func NewContainerRunner(api IArvadosClient,
1344 docker ThinDockerClient,
1345 containerUUID string) *ContainerRunner {
1347 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1348 cr.NewLogWriter = cr.NewArvLogWriter
1349 cr.RunArvMount = cr.ArvMountCmd
1350 cr.MkTempDir = ioutil.TempDir
1351 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1352 cr.Container.UUID = containerUUID
1353 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1354 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1356 loadLogThrottleParams(api)
1362 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1363 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1364 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1365 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1366 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1367 enableNetwork := flag.String("container-enable-networking", "default",
1368 `Specify if networking should be enabled for container. One of 'default', 'always':
1369 default: only enable networking if container requests it.
1370 always: containers always have networking enabled
1372 networkMode := flag.String("container-network-mode", "default",
1373 `Set networking mode for container. Corresponds to Docker network mode (--net).
1377 containerId := flag.Arg(0)
1379 if *caCertsPath != "" {
1380 arvadosclient.CertFiles = []string{*caCertsPath}
1383 api, err := arvadosclient.MakeArvadosClient()
1385 log.Fatalf("%s: %v", containerId, err)
1389 var kc *keepclient.KeepClient
1390 kc, err = keepclient.MakeKeepClient(api)
1392 log.Fatalf("%s: %v", containerId, err)
1396 var docker *dockerclient.Client
1397 // API version 1.21 corresponds to Docker 1.9, which is currently the
1398 // minimum version we want to support.
1399 docker, err = dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1401 log.Fatalf("%s: %v", containerId, err)
1404 dockerClientProxy := ThinDockerClientProxy{Docker: docker}
1406 cr := NewContainerRunner(api, kc, dockerClientProxy, containerId)
1407 cr.statInterval = *statInterval
1408 cr.cgroupRoot = *cgroupRoot
1409 cr.expectCgroupParent = *cgroupParent
1410 cr.enableNetwork = *enableNetwork
1411 cr.networkMode = *networkMode
1412 if *cgroupParentSubsystem != "" {
1413 p := findCgroup(*cgroupParentSubsystem)
1414 cr.setCgroupParent = p
1415 cr.expectCgroupParent = p
1420 log.Fatalf("%s: %v", containerId, err)