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)
53 CollectionFileReader(collection map[string]interface{}, filename string) (keepclient.Reader, error)
56 // NewLogWriter is a factory function to create a new log writer.
57 type NewLogWriter func(name string) io.WriteCloser
59 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
61 type MkTempDir func(string, string) (string, error)
63 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
64 type ThinDockerClient interface {
65 ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error)
66 ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
67 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error)
68 ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error
69 ContainerStop(ctx context.Context, container string, timeout *time.Duration) error
70 ContainerWait(ctx context.Context, container string) (int64, error)
71 ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error)
72 ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error)
73 ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error)
76 // ThinDockerClientProxy is a proxy implementation of ThinDockerClient
77 // that executes the docker requests on dockerclient.Client
78 type ThinDockerClientProxy struct {
79 Docker *dockerclient.Client
82 // ContainerAttach invokes dockerclient.Client.ContainerAttach
83 func (proxy ThinDockerClientProxy) ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error) {
84 return proxy.Docker.ContainerAttach(ctx, container, options)
87 // ContainerCreate invokes dockerclient.Client.ContainerCreate
88 func (proxy ThinDockerClientProxy) ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
89 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error) {
90 return proxy.Docker.ContainerCreate(ctx, config, hostConfig, networkingConfig, containerName)
93 // ContainerStart invokes dockerclient.Client.ContainerStart
94 func (proxy ThinDockerClientProxy) ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error {
95 return proxy.Docker.ContainerStart(ctx, container, options)
98 // ContainerStop invokes dockerclient.Client.ContainerStop
99 func (proxy ThinDockerClientProxy) ContainerStop(ctx context.Context, container string, timeout *time.Duration) error {
100 return proxy.Docker.ContainerStop(ctx, container, timeout)
103 // ContainerWait invokes dockerclient.Client.ContainerWait
104 func (proxy ThinDockerClientProxy) ContainerWait(ctx context.Context, container string) (int64, error) {
105 return proxy.Docker.ContainerWait(ctx, container)
108 // ImageInspectWithRaw invokes dockerclient.Client.ImageInspectWithRaw
109 func (proxy ThinDockerClientProxy) ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error) {
110 return proxy.Docker.ImageInspectWithRaw(ctx, image)
113 // ImageLoad invokes dockerclient.Client.ImageLoad
114 func (proxy ThinDockerClientProxy) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error) {
115 return proxy.Docker.ImageLoad(ctx, input, quiet)
118 // ImageRemove invokes dockerclient.Client.ImageRemove
119 func (proxy ThinDockerClientProxy) ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {
120 return proxy.Docker.ImageRemove(ctx, image, options)
123 // ContainerRunner is the main stateful struct used for a single execution of a
125 type ContainerRunner struct {
126 Docker ThinDockerClient
127 ArvClient IArvadosClient
130 ContainerConfig dockercontainer.Config
131 dockercontainer.HostConfig
136 loggingDone chan bool
137 CrunchLog *ThrottledLogger
138 Stdout io.WriteCloser
139 Stderr *ThrottledLogger
140 LogCollection *CollectionWriter
147 CleanupTempDir []string
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 needCertMount := true
343 for bind, _ := range runner.Container.Mounts {
344 binds = append(binds, bind)
348 for _, bind := range binds {
349 mnt := runner.Container.Mounts[bind]
350 if bind == "stdout" {
351 // Is it a "file" mount kind?
352 if mnt.Kind != "file" {
353 return fmt.Errorf("Unsupported mount kind '%s' for stdout. Only 'file' is supported.", mnt.Kind)
356 // Does path start with OutputPath?
357 prefix := runner.Container.OutputPath
358 if !strings.HasSuffix(prefix, "/") {
361 if !strings.HasPrefix(mnt.Path, prefix) {
362 return fmt.Errorf("Stdout path does not start with OutputPath: %s, %s", mnt.Path, prefix)
367 // Is it a "collection" mount kind?
368 if mnt.Kind != "collection" && mnt.Kind != "json" {
369 return fmt.Errorf("Unsupported mount kind '%s' for stdin. Only 'collection' or 'json' are supported.", mnt.Kind)
373 if bind == "/etc/arvados/ca-certificates.crt" {
374 needCertMount = false
377 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
378 if mnt.Kind != "collection" {
379 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
384 case mnt.Kind == "collection":
386 if mnt.UUID != "" && mnt.PortableDataHash != "" {
387 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
391 return fmt.Errorf("Writing to existing collections currently not permitted.")
394 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
395 } else if mnt.PortableDataHash != "" {
397 return fmt.Errorf("Can never write to a collection specified by portable data hash")
399 idx := strings.Index(mnt.PortableDataHash, "/")
401 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
402 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
403 runner.Container.Mounts[bind] = mnt
405 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
406 if mnt.Path != "" && mnt.Path != "." {
407 if strings.HasPrefix(mnt.Path, "./") {
408 mnt.Path = mnt.Path[2:]
409 } else if strings.HasPrefix(mnt.Path, "/") {
410 mnt.Path = mnt.Path[1:]
412 src += "/" + mnt.Path
415 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
416 arvMountCmd = append(arvMountCmd, "--mount-tmp")
417 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
421 if bind == runner.Container.OutputPath {
422 runner.HostOutputDir = src
423 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
424 return fmt.Errorf("Writable mount points are not permitted underneath the output_path: %v", bind)
426 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
428 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
430 collectionPaths = append(collectionPaths, src)
432 case mnt.Kind == "tmp" && bind == runner.Container.OutputPath:
433 runner.HostOutputDir, err = runner.MkTempDir("", "")
435 return fmt.Errorf("While creating mount temp dir: %v", err)
437 st, staterr := os.Stat(runner.HostOutputDir)
439 return fmt.Errorf("While Stat on temp dir: %v", staterr)
441 err = os.Chmod(runner.HostOutputDir, st.Mode()|os.ModeSetgid|0777)
443 return fmt.Errorf("While Chmod temp dir: %v", err)
445 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.HostOutputDir)
446 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", runner.HostOutputDir, bind))
448 case mnt.Kind == "tmp":
449 runner.Binds = append(runner.Binds, bind)
451 case mnt.Kind == "json":
452 jsondata, err := json.Marshal(mnt.Content)
454 return fmt.Errorf("encoding json data: %v", err)
456 // Create a tempdir with a single file
457 // (instead of just a tempfile): this way we
458 // can ensure the file is world-readable
459 // inside the container, without having to
460 // make it world-readable on the docker host.
461 tmpdir, err := runner.MkTempDir("", "")
463 return fmt.Errorf("creating temp dir: %v", err)
465 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
466 tmpfn := filepath.Join(tmpdir, "mountdata.json")
467 err = ioutil.WriteFile(tmpfn, jsondata, 0644)
469 return fmt.Errorf("writing temp file: %v", err)
471 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
475 if runner.HostOutputDir == "" {
476 return fmt.Errorf("Output path does not correspond to a writable mount point")
479 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
480 for _, certfile := range arvadosclient.CertFiles {
481 _, err := os.Stat(certfile)
483 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
490 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
492 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
494 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
496 token, err := runner.ContainerToken()
498 return fmt.Errorf("could not get container token: %s", err)
501 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
503 return fmt.Errorf("While trying to start arv-mount: %v", err)
506 for _, p := range collectionPaths {
509 return fmt.Errorf("While checking that input files exist: %v", err)
516 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
517 // Handle docker log protocol
518 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
520 header := make([]byte, 8)
522 _, readerr := io.ReadAtLeast(containerReader, header, 8)
525 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
528 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
531 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
536 if readerr != io.EOF {
537 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
540 closeerr := runner.Stdout.Close()
542 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
545 closeerr = runner.Stderr.Close()
547 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
550 if runner.statReporter != nil {
551 runner.statReporter.Stop()
552 closeerr = runner.statLogger.Close()
554 runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
558 runner.loggingDone <- true
559 close(runner.loggingDone)
565 func (runner *ContainerRunner) StartCrunchstat() {
566 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
567 runner.statReporter = &crunchstat.Reporter{
568 CID: runner.ContainerID,
569 Logger: log.New(runner.statLogger, "", 0),
570 CgroupParent: runner.expectCgroupParent,
571 CgroupRoot: runner.cgroupRoot,
572 PollPeriod: runner.statInterval,
574 runner.statReporter.Start()
577 type infoCommand struct {
582 // Gather node information and store it on the log for debugging
584 func (runner *ContainerRunner) LogNodeInfo() (err error) {
585 w := runner.NewLogWriter("node-info")
586 logger := log.New(w, "node-info", 0)
588 commands := []infoCommand{
590 label: "Host Information",
591 cmd: []string{"uname", "-a"},
594 label: "CPU Information",
595 cmd: []string{"cat", "/proc/cpuinfo"},
598 label: "Memory Information",
599 cmd: []string{"cat", "/proc/meminfo"},
603 cmd: []string{"df", "-m", "/", os.TempDir()},
606 label: "Disk INodes",
607 cmd: []string{"df", "-i", "/", os.TempDir()},
611 // Run commands with informational output to be logged.
613 for _, command := range commands {
614 out, err = exec.Command(command.cmd[0], command.cmd[1:]...).CombinedOutput()
616 return fmt.Errorf("While running command %q: %v",
619 logger.Println(command.label)
620 for _, line := range strings.Split(string(out), "\n") {
621 logger.Println(" ", line)
627 return fmt.Errorf("While closing node-info logs: %v", err)
632 // Get and save the raw JSON container record from the API server
633 func (runner *ContainerRunner) LogContainerRecord() (err error) {
636 runner.Container.UUID,
638 runner.LogCollection.Open("container.json"),
640 // Get Container record JSON from the API Server
641 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
643 return fmt.Errorf("While retrieving container record from the API server: %v", err)
646 // Read the API server response as []byte
647 json_bytes, err := ioutil.ReadAll(reader)
649 return fmt.Errorf("While reading container record API server response: %v", err)
651 // Decode the JSON []byte
652 var cr map[string]interface{}
653 if err = json.Unmarshal(json_bytes, &cr); err != nil {
654 return fmt.Errorf("While decoding the container record JSON response: %v", err)
656 // Re-encode it using indentation to improve readability
657 enc := json.NewEncoder(w)
658 enc.SetIndent("", " ")
659 if err = enc.Encode(cr); err != nil {
660 return fmt.Errorf("While logging the JSON container record: %v", err)
664 return fmt.Errorf("While closing container.json log: %v", err)
669 // AttachLogs connects the docker container stdout and stderr logs to the
670 // Arvados logger which logs to Keep and the API server logs table.
671 func (runner *ContainerRunner) AttachStreams() (err error) {
673 runner.CrunchLog.Print("Attaching container streams")
675 // If stdin mount is provided, attach it to the docker container
676 var stdinRdr keepclient.Reader
678 if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
679 if stdinMnt.Kind == "collection" {
680 var stdinColl arvados.Collection
681 collId := stdinMnt.UUID
683 collId = stdinMnt.PortableDataHash
685 err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
687 return fmt.Errorf("While getting stding collection: %v", err)
690 stdinRdr, err = runner.Kc.CollectionFileReader(map[string]interface{}{"manifest_text": stdinColl.ManifestText}, stdinMnt.Path)
691 if os.IsNotExist(err) {
692 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
693 } else if err != nil {
694 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
697 defer stdinRdr.Close()
698 } else if stdinMnt.Kind == "json" {
699 stdinJson, err = json.Marshal(stdinMnt.Content)
701 return fmt.Errorf("While encoding stdin json data: %v", err)
706 stdinUsed := stdinRdr != nil || len(stdinJson) != 0
707 response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
708 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
710 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
713 runner.loggingDone = make(chan bool)
715 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
716 stdoutPath := stdoutMnt.Path[len(runner.Container.OutputPath):]
717 index := strings.LastIndex(stdoutPath, "/")
719 subdirs := stdoutPath[:index]
721 st, err := os.Stat(runner.HostOutputDir)
723 return fmt.Errorf("While Stat on temp dir: %v", err)
725 stdoutPath := path.Join(runner.HostOutputDir, subdirs)
726 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
728 return fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
732 stdoutFile, err := os.Create(path.Join(runner.HostOutputDir, stdoutPath))
734 return fmt.Errorf("While creating stdout file: %v", err)
736 runner.Stdout = stdoutFile
738 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
740 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
743 copyErrC := make(chan error)
745 _, err := io.Copy(response.Conn, stdinRdr)
750 copyErr := <-copyErrC
752 return fmt.Errorf("While writing stdin collection to docker container %q", copyErr)
754 } else if len(stdinJson) != 0 {
755 copyErrC := make(chan error)
757 jsonRdr := bytes.NewReader(stdinJson)
758 _, err := io.Copy(response.Conn, jsonRdr)
763 copyErr := <-copyErrC
765 return fmt.Errorf("While writing stdin json to docker container %q", copyErr)
769 go runner.ProcessDockerAttach(response.Reader)
774 // CreateContainer creates the docker container.
775 func (runner *ContainerRunner) CreateContainer() error {
776 runner.CrunchLog.Print("Creating Docker container")
778 runner.ContainerConfig.Cmd = runner.Container.Command
779 if runner.Container.Cwd != "." {
780 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
783 for k, v := range runner.Container.Environment {
784 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
787 runner.HostConfig = dockercontainer.HostConfig{
789 Cgroup: dockercontainer.CgroupSpec(runner.setCgroupParent),
790 LogConfig: dockercontainer.LogConfig{
795 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
796 tok, err := runner.ContainerToken()
800 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
801 "ARVADOS_API_TOKEN="+tok,
802 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
803 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
805 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
807 if runner.enableNetwork == "always" {
808 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
810 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
814 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
816 return fmt.Errorf("While creating container: %v", err)
819 runner.ContainerID = createdBody.ID
821 return runner.AttachStreams()
824 // StartContainer starts the docker container created by CreateContainer.
825 func (runner *ContainerRunner) StartContainer() error {
826 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
827 runner.cStateLock.Lock()
828 defer runner.cStateLock.Unlock()
829 if runner.cCancelled {
832 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
833 dockertypes.ContainerStartOptions{})
835 return fmt.Errorf("could not start container: %v", err)
837 runner.cStarted = true
841 // WaitFinish waits for the container to terminate, capture the exit code, and
842 // close the stdout/stderr logging.
843 func (runner *ContainerRunner) WaitFinish() error {
844 runner.CrunchLog.Print("Waiting for container to finish")
846 waitDocker, err := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID)
848 return fmt.Errorf("container wait: %v", err)
851 runner.CrunchLog.Printf("Container exited with code: %v", waitDocker)
852 code := int(waitDocker)
853 runner.ExitCode = &code
855 waitMount := runner.ArvMountExit
857 case err := <-waitMount:
858 runner.CrunchLog.Printf("arv-mount exited before container finished: %v", err)
864 // wait for stdout/stderr to complete
870 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
871 func (runner *ContainerRunner) CaptureOutput() error {
872 if runner.finalState != "Complete" {
876 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
877 // Output may have been set directly by the container, so
878 // refresh the container record to check.
879 err := runner.ArvClient.Get("containers", runner.Container.UUID,
880 nil, &runner.Container)
884 if runner.Container.Output != "" {
885 // Container output is already set.
886 runner.OutputPDH = &runner.Container.Output
891 if runner.HostOutputDir == "" {
895 _, err := os.Stat(runner.HostOutputDir)
897 return fmt.Errorf("While checking host output path: %v", err)
900 var manifestText string
902 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
903 _, err = os.Stat(collectionMetafile)
906 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
907 manifestText, err = cw.WriteTree(runner.HostOutputDir, runner.CrunchLog.Logger)
909 return fmt.Errorf("While uploading output files: %v", err)
912 // FUSE mount directory
913 file, openerr := os.Open(collectionMetafile)
915 return fmt.Errorf("While opening FUSE metafile: %v", err)
919 var rec arvados.Collection
920 err = json.NewDecoder(file).Decode(&rec)
922 return fmt.Errorf("While reading FUSE metafile: %v", err)
924 manifestText = rec.ManifestText
927 // Pre-populate output from the configured mount points
929 for bind, _ := range runner.Container.Mounts {
930 binds = append(binds, bind)
934 for _, bind := range binds {
935 mnt := runner.Container.Mounts[bind]
937 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
939 if bindSuffix == bind || len(bindSuffix) <= 0 {
940 // either does not start with OutputPath or is OutputPath itself
944 if mnt.ExcludeFromOutput == true {
948 // append to manifest_text
949 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
954 manifestText = manifestText + m
958 var response arvados.Collection
959 manifest := manifest.Manifest{Text: manifestText}
960 manifestText = manifest.Extract(".", ".").Text
961 err = runner.ArvClient.Create("collections",
963 "ensure_unique_name": true,
964 "collection": arvadosclient.Dict{
966 "name": "output for " + runner.Container.UUID,
967 "manifest_text": manifestText}},
970 return fmt.Errorf("While creating output collection: %v", err)
972 runner.OutputPDH = &response.PortableDataHash
976 var outputCollections = make(map[string]arvados.Collection)
978 // Fetch the collection for the mnt.PortableDataHash
979 // Return the manifest_text fragment corresponding to the specified mnt.Path
980 // after making any required updates.
982 // If mnt.Path is not specified,
983 // return the entire manifest_text after replacing any "." with bindSuffix
984 // If mnt.Path corresponds to one stream,
985 // return the manifest_text for that stream after replacing that stream name with bindSuffix
986 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
987 // for that stream after replacing stream name with bindSuffix minus the last word
988 // and the file name with last word of the bindSuffix
989 // Allowed path examples:
992 // "path":"/subdir1/subdir2"
993 // "path":"/subdir/filename" etc
994 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
995 collection := outputCollections[mnt.PortableDataHash]
996 if collection.PortableDataHash == "" {
997 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
999 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1001 outputCollections[mnt.PortableDataHash] = collection
1004 if collection.ManifestText == "" {
1005 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1009 mft := manifest.Manifest{Text: collection.ManifestText}
1010 extracted := mft.Extract(mnt.Path, bindSuffix)
1011 if extracted.Err != nil {
1012 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1014 return extracted.Text, nil
1017 func (runner *ContainerRunner) CleanupDirs() {
1018 if runner.ArvMount != nil {
1019 umount := exec.Command("fusermount", "-z", "-u", runner.ArvMountPoint)
1020 umnterr := umount.Run()
1022 runner.CrunchLog.Printf("While running fusermount: %v", umnterr)
1025 mnterr := <-runner.ArvMountExit
1027 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
1031 for _, tmpdir := range runner.CleanupTempDir {
1032 rmerr := os.RemoveAll(tmpdir)
1034 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1039 // CommitLogs posts the collection containing the final container logs.
1040 func (runner *ContainerRunner) CommitLogs() error {
1041 runner.CrunchLog.Print(runner.finalState)
1042 runner.CrunchLog.Close()
1044 // Closing CrunchLog above allows it to be committed to Keep at this
1045 // point, but re-open crunch log with ArvClient in case there are any
1046 // other further (such as failing to write the log to Keep!) while
1048 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{runner.ArvClient, runner.Container.UUID,
1051 if runner.LogsPDH != nil {
1052 // If we have already assigned something to LogsPDH,
1053 // we must be closing the re-opened log, which won't
1054 // end up getting attached to the container record and
1055 // therefore doesn't need to be saved as a collection
1056 // -- it exists only to send logs to other channels.
1060 mt, err := runner.LogCollection.ManifestText()
1062 return fmt.Errorf("While creating log manifest: %v", err)
1065 var response arvados.Collection
1066 err = runner.ArvClient.Create("collections",
1068 "ensure_unique_name": true,
1069 "collection": arvadosclient.Dict{
1071 "name": "logs for " + runner.Container.UUID,
1072 "manifest_text": mt}},
1075 return fmt.Errorf("While creating log collection: %v", err)
1077 runner.LogsPDH = &response.PortableDataHash
1081 // UpdateContainerRunning updates the container state to "Running"
1082 func (runner *ContainerRunner) UpdateContainerRunning() error {
1083 runner.cStateLock.Lock()
1084 defer runner.cStateLock.Unlock()
1085 if runner.cCancelled {
1088 return runner.ArvClient.Update("containers", runner.Container.UUID,
1089 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1092 // ContainerToken returns the api_token the container (and any
1093 // arv-mount processes) are allowed to use.
1094 func (runner *ContainerRunner) ContainerToken() (string, error) {
1095 if runner.token != "" {
1096 return runner.token, nil
1099 var auth arvados.APIClientAuthorization
1100 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1104 runner.token = auth.APIToken
1105 return runner.token, nil
1108 // UpdateContainerComplete updates the container record state on API
1109 // server to "Complete" or "Cancelled"
1110 func (runner *ContainerRunner) UpdateContainerFinal() error {
1111 update := arvadosclient.Dict{}
1112 update["state"] = runner.finalState
1113 if runner.LogsPDH != nil {
1114 update["log"] = *runner.LogsPDH
1116 if runner.finalState == "Complete" {
1117 if runner.ExitCode != nil {
1118 update["exit_code"] = *runner.ExitCode
1120 if runner.OutputPDH != nil {
1121 update["output"] = *runner.OutputPDH
1124 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1127 // IsCancelled returns the value of Cancelled, with goroutine safety.
1128 func (runner *ContainerRunner) IsCancelled() bool {
1129 runner.cStateLock.Lock()
1130 defer runner.cStateLock.Unlock()
1131 return runner.cCancelled
1134 // NewArvLogWriter creates an ArvLogWriter
1135 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1136 return &ArvLogWriter{runner.ArvClient, runner.Container.UUID, name, runner.LogCollection.Open(name + ".txt")}
1139 // Run the full container lifecycle.
1140 func (runner *ContainerRunner) Run() (err error) {
1141 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1143 hostname, hosterr := os.Hostname()
1145 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1147 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1150 // Clean up temporary directories _after_ finalizing
1151 // everything (if we've made any by then)
1152 defer runner.CleanupDirs()
1154 runner.finalState = "Queued"
1157 // checkErr prints e (unless it's nil) and sets err to
1158 // e (unless err is already non-nil). Thus, if err
1159 // hasn't already been assigned when Run() returns,
1160 // this cleanup func will cause Run() to return the
1161 // first non-nil error that is passed to checkErr().
1162 checkErr := func(e error) {
1166 runner.CrunchLog.Print(e)
1172 // Log the error encountered in Run(), if any
1175 if runner.finalState == "Queued" {
1176 runner.CrunchLog.Close()
1177 runner.UpdateContainerFinal()
1181 if runner.IsCancelled() {
1182 runner.finalState = "Cancelled"
1183 // but don't return yet -- we still want to
1184 // capture partial output and write logs
1187 checkErr(runner.CaptureOutput())
1188 checkErr(runner.CommitLogs())
1189 checkErr(runner.UpdateContainerFinal())
1191 // The real log is already closed, but then we opened
1192 // a new one in case we needed to log anything while
1194 runner.CrunchLog.Close()
1197 err = runner.ArvClient.Get("containers", runner.Container.UUID, nil, &runner.Container)
1199 err = fmt.Errorf("While getting container record: %v", err)
1203 // setup signal handling
1204 runner.SetupSignals()
1206 // check for and/or load image
1207 err = runner.LoadImage()
1209 runner.finalState = "Cancelled"
1210 err = fmt.Errorf("While loading container image: %v", err)
1214 // set up FUSE mount and binds
1215 err = runner.SetupMounts()
1217 runner.finalState = "Cancelled"
1218 err = fmt.Errorf("While setting up mounts: %v", err)
1222 err = runner.CreateContainer()
1227 // Gather and record node information
1228 err = runner.LogNodeInfo()
1232 // Save container.json record on log collection
1233 err = runner.LogContainerRecord()
1238 runner.StartCrunchstat()
1240 if runner.IsCancelled() {
1244 err = runner.UpdateContainerRunning()
1248 runner.finalState = "Cancelled"
1250 err = runner.StartContainer()
1255 err = runner.WaitFinish()
1257 runner.finalState = "Complete"
1262 // NewContainerRunner creates a new container runner.
1263 func NewContainerRunner(api IArvadosClient,
1265 docker ThinDockerClient,
1266 containerUUID string) *ContainerRunner {
1268 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1269 cr.NewLogWriter = cr.NewArvLogWriter
1270 cr.RunArvMount = cr.ArvMountCmd
1271 cr.MkTempDir = ioutil.TempDir
1272 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1273 cr.Container.UUID = containerUUID
1274 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1275 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1280 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1281 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1282 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1283 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1284 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1285 enableNetwork := flag.String("container-enable-networking", "default",
1286 `Specify if networking should be enabled for container. One of 'default', 'always':
1287 default: only enable networking if container requests it.
1288 always: containers always have networking enabled
1290 networkMode := flag.String("container-network-mode", "default",
1291 `Set networking mode for container. Corresponds to Docker network mode (--net).
1295 containerId := flag.Arg(0)
1297 if *caCertsPath != "" {
1298 arvadosclient.CertFiles = []string{*caCertsPath}
1301 api, err := arvadosclient.MakeArvadosClient()
1303 log.Fatalf("%s: %v", containerId, err)
1307 var kc *keepclient.KeepClient
1308 kc, err = keepclient.MakeKeepClient(api)
1310 log.Fatalf("%s: %v", containerId, err)
1314 var docker *dockerclient.Client
1315 // API version 1.21 corresponds to Docker 1.9, which is currently the
1316 // minimum version we want to support.
1317 docker, err = dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1319 log.Fatalf("%s: %v", containerId, err)
1322 dockerClientProxy := ThinDockerClientProxy{Docker: docker}
1324 cr := NewContainerRunner(api, kc, dockerClientProxy, containerId)
1325 cr.statInterval = *statInterval
1326 cr.cgroupRoot = *cgroupRoot
1327 cr.expectCgroupParent = *cgroupParent
1328 cr.enableNetwork = *enableNetwork
1329 cr.networkMode = *networkMode
1330 if *cgroupParentSubsystem != "" {
1331 p := findCgroup(*cgroupParentSubsystem)
1332 cr.setCgroupParent = p
1333 cr.expectCgroupParent = p
1338 log.Fatalf("%s: %v", containerId, err)