24 "git.curoverse.com/arvados.git/lib/crunchstat"
25 "git.curoverse.com/arvados.git/sdk/go/arvados"
26 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
27 "git.curoverse.com/arvados.git/sdk/go/keepclient"
28 "git.curoverse.com/arvados.git/sdk/go/manifest"
30 dockertypes "github.com/docker/docker/api/types"
31 dockercontainer "github.com/docker/docker/api/types/container"
32 dockernetwork "github.com/docker/docker/api/types/network"
33 dockerclient "github.com/docker/docker/client"
36 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
37 type IArvadosClient interface {
38 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
39 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
40 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
41 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
42 CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
43 Discovery(key string) (interface{}, error)
46 // ErrCancelled is the error returned when the container is cancelled.
47 var ErrCancelled = errors.New("Cancelled")
49 // IKeepClient is the minimal Keep API methods used by crunch-run.
50 type IKeepClient interface {
51 PutHB(hash string, buf []byte) (string, int, error)
52 ManifestFileReader(m manifest.Manifest, filename string) (keepclient.Reader, error)
55 // NewLogWriter is a factory function to create a new log writer.
56 type NewLogWriter func(name string) io.WriteCloser
58 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
60 type MkTempDir func(string, string) (string, error)
62 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
63 type ThinDockerClient interface {
64 ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error)
65 ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
66 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error)
67 ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error
68 ContainerStop(ctx context.Context, container string, timeout *time.Duration) error
69 ContainerWait(ctx context.Context, container string) (int64, error)
70 ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error)
71 ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error)
72 ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error)
75 // ThinDockerClientProxy is a proxy implementation of ThinDockerClient
76 // that executes the docker requests on dockerclient.Client
77 type ThinDockerClientProxy struct {
78 Docker *dockerclient.Client
81 // ContainerAttach invokes dockerclient.Client.ContainerAttach
82 func (proxy ThinDockerClientProxy) ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error) {
83 return proxy.Docker.ContainerAttach(ctx, container, options)
86 // ContainerCreate invokes dockerclient.Client.ContainerCreate
87 func (proxy ThinDockerClientProxy) ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
88 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error) {
89 return proxy.Docker.ContainerCreate(ctx, config, hostConfig, networkingConfig, containerName)
92 // ContainerStart invokes dockerclient.Client.ContainerStart
93 func (proxy ThinDockerClientProxy) ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error {
94 return proxy.Docker.ContainerStart(ctx, container, options)
97 // ContainerStop invokes dockerclient.Client.ContainerStop
98 func (proxy ThinDockerClientProxy) ContainerStop(ctx context.Context, container string, timeout *time.Duration) error {
99 return proxy.Docker.ContainerStop(ctx, container, timeout)
102 // ContainerWait invokes dockerclient.Client.ContainerWait
103 func (proxy ThinDockerClientProxy) ContainerWait(ctx context.Context, container string) (int64, error) {
104 return proxy.Docker.ContainerWait(ctx, container)
107 // ImageInspectWithRaw invokes dockerclient.Client.ImageInspectWithRaw
108 func (proxy ThinDockerClientProxy) ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error) {
109 return proxy.Docker.ImageInspectWithRaw(ctx, image)
112 // ImageLoad invokes dockerclient.Client.ImageLoad
113 func (proxy ThinDockerClientProxy) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error) {
114 return proxy.Docker.ImageLoad(ctx, input, quiet)
117 // ImageRemove invokes dockerclient.Client.ImageRemove
118 func (proxy ThinDockerClientProxy) ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {
119 return proxy.Docker.ImageRemove(ctx, image, options)
122 // ContainerRunner is the main stateful struct used for a single execution of a
124 type ContainerRunner struct {
125 Docker ThinDockerClient
126 ArvClient IArvadosClient
129 ContainerConfig dockercontainer.Config
130 dockercontainer.HostConfig
135 loggingDone chan bool
136 CrunchLog *ThrottledLogger
137 Stdout io.WriteCloser
138 Stderr io.WriteCloser
139 LogCollection *CollectionWriter
146 CleanupTempDir []string
148 Volumes map[string]struct{}
150 SigChan chan os.Signal
151 ArvMountExit chan error
154 statLogger io.WriteCloser
155 statReporter *crunchstat.Reporter
156 statInterval time.Duration
158 // What we expect the container's cgroup parent to be.
159 expectCgroupParent string
160 // What we tell docker to use as the container's cgroup
161 // parent. Note: Ideally we would use the same field for both
162 // expectCgroupParent and setCgroupParent, and just make it
163 // default to "docker". However, when using docker < 1.10 with
164 // systemd, specifying a non-empty cgroup parent (even the
165 // default value "docker") hits a docker bug
166 // (https://github.com/docker/docker/issues/17126). Using two
167 // separate fields makes it possible to use the "expect cgroup
168 // parent to be X" feature even on sites where the "specify
169 // cgroup parent" feature breaks.
170 setCgroupParent string
172 cStateLock sync.Mutex
173 cStarted bool // StartContainer() succeeded
174 cCancelled bool // StopContainer() invoked
176 enableNetwork string // one of "default" or "always"
177 networkMode string // passed through to HostConfig.NetworkMode
180 // SetupSignals sets up signal handling to gracefully terminate the underlying
181 // Docker container and update state when receiving a TERM, INT or QUIT signal.
182 func (runner *ContainerRunner) SetupSignals() {
183 runner.SigChan = make(chan os.Signal, 1)
184 signal.Notify(runner.SigChan, syscall.SIGTERM)
185 signal.Notify(runner.SigChan, syscall.SIGINT)
186 signal.Notify(runner.SigChan, syscall.SIGQUIT)
188 go func(sig chan os.Signal) {
195 // stop the underlying Docker container.
196 func (runner *ContainerRunner) stop() {
197 runner.cStateLock.Lock()
198 defer runner.cStateLock.Unlock()
199 if runner.cCancelled {
202 runner.cCancelled = true
204 timeout := time.Duration(10)
205 err := runner.Docker.ContainerStop(context.TODO(), runner.ContainerID, &(timeout))
207 log.Printf("StopContainer failed: %s", err)
212 // LoadImage determines the docker image id from the container record and
213 // checks if it is available in the local Docker image store. If not, it loads
214 // the image from Keep.
215 func (runner *ContainerRunner) LoadImage() (err error) {
217 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
219 var collection arvados.Collection
220 err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
222 return fmt.Errorf("While getting container image collection: %v", err)
224 manifest := manifest.Manifest{Text: collection.ManifestText}
225 var img, imageID string
226 for ms := range manifest.StreamIter() {
227 img = ms.FileStreamSegments[0].Name
228 if !strings.HasSuffix(img, ".tar") {
229 return fmt.Errorf("First file in the container image collection does not end in .tar")
231 imageID = img[:len(img)-4]
234 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
236 _, _, err = runner.Docker.ImageInspectWithRaw(context.TODO(), imageID)
238 runner.CrunchLog.Print("Loading Docker image from keep")
240 var readCloser io.ReadCloser
241 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
243 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
246 response, err := runner.Docker.ImageLoad(context.TODO(), readCloser, false)
248 return fmt.Errorf("While loading container image into Docker: %v", err)
250 response.Body.Close()
252 runner.CrunchLog.Print("Docker image is available")
255 runner.ContainerConfig.Image = imageID
260 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
261 c = exec.Command("arv-mount", arvMountCmd...)
263 // Copy our environment, but override ARVADOS_API_TOKEN with
264 // the container auth token.
266 for _, s := range os.Environ() {
267 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
268 c.Env = append(c.Env, s)
271 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
273 nt := NewThrottledLogger(runner.NewLogWriter("arv-mount"))
282 statReadme := make(chan bool)
283 runner.ArvMountExit = make(chan error)
288 time.Sleep(100 * time.Millisecond)
289 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
299 runner.ArvMountExit <- c.Wait()
300 close(runner.ArvMountExit)
306 case err := <-runner.ArvMountExit:
307 runner.ArvMount = nil
315 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
316 if runner.ArvMountPoint == "" {
317 runner.ArvMountPoint, err = runner.MkTempDir("", prefix)
322 func (runner *ContainerRunner) SetupMounts() (err error) {
323 err = runner.SetupArvMountPoint("keep")
325 return fmt.Errorf("While creating keep mount temp dir: %v", err)
328 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.ArvMountPoint)
332 arvMountCmd := []string{"--foreground", "--allow-other", "--read-write"}
334 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
335 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
338 collectionPaths := []string{}
340 runner.Volumes = make(map[string]struct{})
341 needCertMount := true
344 for bind, _ := range runner.Container.Mounts {
345 binds = append(binds, bind)
349 for _, bind := range binds {
350 mnt := runner.Container.Mounts[bind]
351 if bind == "stdout" || bind == "stderr" {
352 // Is it a "file" mount kind?
353 if mnt.Kind != "file" {
354 return fmt.Errorf("Unsupported mount kind '%s' for %s. Only 'file' is supported.", mnt.Kind, bind)
357 // Does path start with OutputPath?
358 prefix := runner.Container.OutputPath
359 if !strings.HasSuffix(prefix, "/") {
362 if !strings.HasPrefix(mnt.Path, prefix) {
363 return fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
368 // Is it a "collection" mount kind?
369 if mnt.Kind != "collection" && mnt.Kind != "json" {
370 return fmt.Errorf("Unsupported mount kind '%s' for stdin. Only 'collection' or 'json' are supported.", mnt.Kind)
374 if bind == "/etc/arvados/ca-certificates.crt" {
375 needCertMount = false
378 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
379 if mnt.Kind != "collection" {
380 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
385 case mnt.Kind == "collection" && bind != "stdin":
387 if mnt.UUID != "" && mnt.PortableDataHash != "" {
388 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
392 return fmt.Errorf("Writing to existing collections currently not permitted.")
395 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
396 } else if mnt.PortableDataHash != "" {
398 return fmt.Errorf("Can never write to a collection specified by portable data hash")
400 idx := strings.Index(mnt.PortableDataHash, "/")
402 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
403 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
404 runner.Container.Mounts[bind] = mnt
406 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
407 if mnt.Path != "" && mnt.Path != "." {
408 if strings.HasPrefix(mnt.Path, "./") {
409 mnt.Path = mnt.Path[2:]
410 } else if strings.HasPrefix(mnt.Path, "/") {
411 mnt.Path = mnt.Path[1:]
413 src += "/" + mnt.Path
416 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
417 arvMountCmd = append(arvMountCmd, "--mount-tmp")
418 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
422 if bind == runner.Container.OutputPath {
423 runner.HostOutputDir = src
424 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
425 return fmt.Errorf("Writable mount points are not permitted underneath the output_path: %v", bind)
427 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
429 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
431 collectionPaths = append(collectionPaths, src)
433 case mnt.Kind == "tmp" && bind == runner.Container.OutputPath:
434 runner.HostOutputDir, err = runner.MkTempDir("", "")
436 return fmt.Errorf("While creating mount temp dir: %v", err)
438 st, staterr := os.Stat(runner.HostOutputDir)
440 return fmt.Errorf("While Stat on temp dir: %v", staterr)
442 err = os.Chmod(runner.HostOutputDir, st.Mode()|os.ModeSetgid|0777)
444 return fmt.Errorf("While Chmod temp dir: %v", err)
446 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.HostOutputDir)
447 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", runner.HostOutputDir, bind))
449 case mnt.Kind == "tmp":
450 runner.Volumes[bind] = struct{}{}
452 case mnt.Kind == "json":
453 jsondata, err := json.Marshal(mnt.Content)
455 return fmt.Errorf("encoding json data: %v", err)
457 // Create a tempdir with a single file
458 // (instead of just a tempfile): this way we
459 // can ensure the file is world-readable
460 // inside the container, without having to
461 // make it world-readable on the docker host.
462 tmpdir, err := runner.MkTempDir("", "")
464 return fmt.Errorf("creating temp dir: %v", err)
466 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
467 tmpfn := filepath.Join(tmpdir, "mountdata.json")
468 err = ioutil.WriteFile(tmpfn, jsondata, 0644)
470 return fmt.Errorf("writing temp file: %v", err)
472 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
476 if runner.HostOutputDir == "" {
477 return fmt.Errorf("Output path does not correspond to a writable mount point")
480 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
481 for _, certfile := range arvadosclient.CertFiles {
482 _, err := os.Stat(certfile)
484 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
491 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
493 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
495 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
497 token, err := runner.ContainerToken()
499 return fmt.Errorf("could not get container token: %s", err)
502 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
504 return fmt.Errorf("While trying to start arv-mount: %v", err)
507 for _, p := range collectionPaths {
510 return fmt.Errorf("While checking that input files exist: %v", err)
517 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
518 // Handle docker log protocol
519 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
521 header := make([]byte, 8)
523 _, readerr := io.ReadAtLeast(containerReader, header, 8)
526 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
529 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
532 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
537 if readerr != io.EOF {
538 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
541 closeerr := runner.Stdout.Close()
543 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
546 closeerr = runner.Stderr.Close()
548 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
551 if runner.statReporter != nil {
552 runner.statReporter.Stop()
553 closeerr = runner.statLogger.Close()
555 runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
559 runner.loggingDone <- true
560 close(runner.loggingDone)
566 func (runner *ContainerRunner) StartCrunchstat() {
567 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
568 runner.statReporter = &crunchstat.Reporter{
569 CID: runner.ContainerID,
570 Logger: log.New(runner.statLogger, "", 0),
571 CgroupParent: runner.expectCgroupParent,
572 CgroupRoot: runner.cgroupRoot,
573 PollPeriod: runner.statInterval,
575 runner.statReporter.Start()
578 type infoCommand struct {
583 // Gather node information and store it on the log for debugging
585 func (runner *ContainerRunner) LogNodeInfo() (err error) {
586 w := runner.NewLogWriter("node-info")
587 logger := log.New(w, "node-info", 0)
589 commands := []infoCommand{
591 label: "Host Information",
592 cmd: []string{"uname", "-a"},
595 label: "CPU Information",
596 cmd: []string{"cat", "/proc/cpuinfo"},
599 label: "Memory Information",
600 cmd: []string{"cat", "/proc/meminfo"},
604 cmd: []string{"df", "-m", "/", os.TempDir()},
607 label: "Disk INodes",
608 cmd: []string{"df", "-i", "/", os.TempDir()},
612 // Run commands with informational output to be logged.
614 for _, command := range commands {
615 out, err = exec.Command(command.cmd[0], command.cmd[1:]...).CombinedOutput()
617 return fmt.Errorf("While running command %q: %v",
620 logger.Println(command.label)
621 for _, line := range strings.Split(string(out), "\n") {
622 logger.Println(" ", line)
628 return fmt.Errorf("While closing node-info logs: %v", err)
633 // Get and save the raw JSON container record from the API server
634 func (runner *ContainerRunner) LogContainerRecord() (err error) {
636 ArvClient: runner.ArvClient,
637 UUID: runner.Container.UUID,
638 loggingStream: "container",
639 writeCloser: runner.LogCollection.Open("container.json"),
642 // Get Container record JSON from the API Server
643 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
645 return fmt.Errorf("While retrieving container record from the API server: %v", err)
648 // Read the API server response as []byte
649 json_bytes, err := ioutil.ReadAll(reader)
651 return fmt.Errorf("While reading container record API server response: %v", err)
653 // Decode the JSON []byte
654 var cr map[string]interface{}
655 if err = json.Unmarshal(json_bytes, &cr); err != nil {
656 return fmt.Errorf("While decoding the container record JSON response: %v", err)
658 // Re-encode it using indentation to improve readability
659 enc := json.NewEncoder(w)
660 enc.SetIndent("", " ")
661 if err = enc.Encode(cr); err != nil {
662 return fmt.Errorf("While logging the JSON container record: %v", err)
666 return fmt.Errorf("While closing container.json log: %v", err)
671 // AttachStreams connects the docker container stdin, stdout and stderr logs
672 // to the Arvados logger which logs to Keep and the API server logs table.
673 func (runner *ContainerRunner) AttachStreams() (err error) {
675 runner.CrunchLog.Print("Attaching container streams")
677 // If stdin mount is provided, attach it to the docker container
678 var stdinRdr keepclient.Reader
680 if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
681 if stdinMnt.Kind == "collection" {
682 var stdinColl arvados.Collection
683 collId := stdinMnt.UUID
685 collId = stdinMnt.PortableDataHash
687 err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
689 return fmt.Errorf("While getting stding collection: %v", err)
692 stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
693 if os.IsNotExist(err) {
694 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
695 } else if err != nil {
696 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
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 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
720 runner.Stdout = stdoutFile
722 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
725 if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
726 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
730 runner.Stderr = stderrFile
732 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
737 _, err := io.Copy(response.Conn, stdinRdr)
739 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
743 response.CloseWrite()
745 } else if len(stdinJson) != 0 {
747 _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
749 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
752 response.CloseWrite()
756 go runner.ProcessDockerAttach(response.Reader)
761 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
762 stdoutPath := mntPath[len(runner.Container.OutputPath):]
763 index := strings.LastIndex(stdoutPath, "/")
765 subdirs := stdoutPath[:index]
767 st, err := os.Stat(runner.HostOutputDir)
769 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
771 stdoutPath := path.Join(runner.HostOutputDir, subdirs)
772 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
774 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
778 stdoutFile, err := os.Create(path.Join(runner.HostOutputDir, stdoutPath))
780 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
783 return stdoutFile, nil
786 // CreateContainer creates the docker container.
787 func (runner *ContainerRunner) CreateContainer() error {
788 runner.CrunchLog.Print("Creating Docker container")
790 runner.ContainerConfig.Cmd = runner.Container.Command
791 if runner.Container.Cwd != "." {
792 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
795 for k, v := range runner.Container.Environment {
796 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
799 runner.ContainerConfig.Volumes = runner.Volumes
801 runner.HostConfig = dockercontainer.HostConfig{
803 Cgroup: dockercontainer.CgroupSpec(runner.setCgroupParent),
804 LogConfig: dockercontainer.LogConfig{
809 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
810 tok, err := runner.ContainerToken()
814 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
815 "ARVADOS_API_TOKEN="+tok,
816 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
817 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
819 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
821 if runner.enableNetwork == "always" {
822 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
824 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
828 _, stdinUsed := runner.Container.Mounts["stdin"]
829 runner.ContainerConfig.OpenStdin = stdinUsed
830 runner.ContainerConfig.StdinOnce = stdinUsed
831 runner.ContainerConfig.AttachStdin = stdinUsed
832 runner.ContainerConfig.AttachStdout = true
833 runner.ContainerConfig.AttachStderr = true
835 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
837 return fmt.Errorf("While creating container: %v", err)
840 runner.ContainerID = createdBody.ID
842 return runner.AttachStreams()
845 // StartContainer starts the docker container created by CreateContainer.
846 func (runner *ContainerRunner) StartContainer() error {
847 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
848 runner.cStateLock.Lock()
849 defer runner.cStateLock.Unlock()
850 if runner.cCancelled {
853 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
854 dockertypes.ContainerStartOptions{})
856 return fmt.Errorf("could not start container: %v", err)
858 runner.cStarted = true
862 // WaitFinish waits for the container to terminate, capture the exit code, and
863 // close the stdout/stderr logging.
864 func (runner *ContainerRunner) WaitFinish() error {
865 runner.CrunchLog.Print("Waiting for container to finish")
867 waitDocker, err := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID)
869 return fmt.Errorf("container wait: %v", err)
872 runner.CrunchLog.Printf("Container exited with code: %v", waitDocker)
873 code := int(waitDocker)
874 runner.ExitCode = &code
876 waitMount := runner.ArvMountExit
878 case err := <-waitMount:
879 runner.CrunchLog.Printf("arv-mount exited before container finished: %v", err)
885 // wait for stdout/stderr to complete
891 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
892 func (runner *ContainerRunner) CaptureOutput() error {
893 if runner.finalState != "Complete" {
897 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
898 // Output may have been set directly by the container, so
899 // refresh the container record to check.
900 err := runner.ArvClient.Get("containers", runner.Container.UUID,
901 nil, &runner.Container)
905 if runner.Container.Output != "" {
906 // Container output is already set.
907 runner.OutputPDH = &runner.Container.Output
912 if runner.HostOutputDir == "" {
916 _, err := os.Stat(runner.HostOutputDir)
918 return fmt.Errorf("While checking host output path: %v", err)
921 var manifestText string
923 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
924 _, err = os.Stat(collectionMetafile)
927 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
928 manifestText, err = cw.WriteTree(runner.HostOutputDir, runner.CrunchLog.Logger)
930 return fmt.Errorf("While uploading output files: %v", err)
933 // FUSE mount directory
934 file, openerr := os.Open(collectionMetafile)
936 return fmt.Errorf("While opening FUSE metafile: %v", err)
940 var rec arvados.Collection
941 err = json.NewDecoder(file).Decode(&rec)
943 return fmt.Errorf("While reading FUSE metafile: %v", err)
945 manifestText = rec.ManifestText
948 // Pre-populate output from the configured mount points
950 for bind, _ := range runner.Container.Mounts {
951 binds = append(binds, bind)
955 for _, bind := range binds {
956 mnt := runner.Container.Mounts[bind]
958 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
960 if bindSuffix == bind || len(bindSuffix) <= 0 {
961 // either does not start with OutputPath or is OutputPath itself
965 if mnt.ExcludeFromOutput == true {
969 // append to manifest_text
970 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
975 manifestText = manifestText + m
979 var response arvados.Collection
980 manifest := manifest.Manifest{Text: manifestText}
981 manifestText = manifest.Extract(".", ".").Text
982 err = runner.ArvClient.Create("collections",
984 "ensure_unique_name": true,
985 "collection": arvadosclient.Dict{
987 "name": "output for " + runner.Container.UUID,
988 "manifest_text": manifestText}},
991 return fmt.Errorf("While creating output collection: %v", err)
993 runner.OutputPDH = &response.PortableDataHash
997 var outputCollections = make(map[string]arvados.Collection)
999 // Fetch the collection for the mnt.PortableDataHash
1000 // Return the manifest_text fragment corresponding to the specified mnt.Path
1001 // after making any required updates.
1003 // If mnt.Path is not specified,
1004 // return the entire manifest_text after replacing any "." with bindSuffix
1005 // If mnt.Path corresponds to one stream,
1006 // return the manifest_text for that stream after replacing that stream name with bindSuffix
1007 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1008 // for that stream after replacing stream name with bindSuffix minus the last word
1009 // and the file name with last word of the bindSuffix
1010 // Allowed path examples:
1012 // "path":"/subdir1"
1013 // "path":"/subdir1/subdir2"
1014 // "path":"/subdir/filename" etc
1015 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1016 collection := outputCollections[mnt.PortableDataHash]
1017 if collection.PortableDataHash == "" {
1018 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1020 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1022 outputCollections[mnt.PortableDataHash] = collection
1025 if collection.ManifestText == "" {
1026 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1030 mft := manifest.Manifest{Text: collection.ManifestText}
1031 extracted := mft.Extract(mnt.Path, bindSuffix)
1032 if extracted.Err != nil {
1033 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1035 return extracted.Text, nil
1038 func (runner *ContainerRunner) CleanupDirs() {
1039 if runner.ArvMount != nil {
1040 umount := exec.Command("fusermount", "-z", "-u", runner.ArvMountPoint)
1041 umnterr := umount.Run()
1043 runner.CrunchLog.Printf("While running fusermount: %v", umnterr)
1046 mnterr := <-runner.ArvMountExit
1048 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
1052 for _, tmpdir := range runner.CleanupTempDir {
1053 rmerr := os.RemoveAll(tmpdir)
1055 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1060 // CommitLogs posts the collection containing the final container logs.
1061 func (runner *ContainerRunner) CommitLogs() error {
1062 runner.CrunchLog.Print(runner.finalState)
1063 runner.CrunchLog.Close()
1065 // Closing CrunchLog above allows it to be committed to Keep at this
1066 // point, but re-open crunch log with ArvClient in case there are any
1067 // other further (such as failing to write the log to Keep!) while
1069 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1070 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1072 if runner.LogsPDH != nil {
1073 // If we have already assigned something to LogsPDH,
1074 // we must be closing the re-opened log, which won't
1075 // end up getting attached to the container record and
1076 // therefore doesn't need to be saved as a collection
1077 // -- it exists only to send logs to other channels.
1081 mt, err := runner.LogCollection.ManifestText()
1083 return fmt.Errorf("While creating log manifest: %v", err)
1086 var response arvados.Collection
1087 err = runner.ArvClient.Create("collections",
1089 "ensure_unique_name": true,
1090 "collection": arvadosclient.Dict{
1092 "name": "logs for " + runner.Container.UUID,
1093 "manifest_text": mt}},
1096 return fmt.Errorf("While creating log collection: %v", err)
1098 runner.LogsPDH = &response.PortableDataHash
1102 // UpdateContainerRunning updates the container state to "Running"
1103 func (runner *ContainerRunner) UpdateContainerRunning() error {
1104 runner.cStateLock.Lock()
1105 defer runner.cStateLock.Unlock()
1106 if runner.cCancelled {
1109 return runner.ArvClient.Update("containers", runner.Container.UUID,
1110 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1113 // ContainerToken returns the api_token the container (and any
1114 // arv-mount processes) are allowed to use.
1115 func (runner *ContainerRunner) ContainerToken() (string, error) {
1116 if runner.token != "" {
1117 return runner.token, nil
1120 var auth arvados.APIClientAuthorization
1121 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1125 runner.token = auth.APIToken
1126 return runner.token, nil
1129 // UpdateContainerComplete updates the container record state on API
1130 // server to "Complete" or "Cancelled"
1131 func (runner *ContainerRunner) UpdateContainerFinal() error {
1132 update := arvadosclient.Dict{}
1133 update["state"] = runner.finalState
1134 if runner.LogsPDH != nil {
1135 update["log"] = *runner.LogsPDH
1137 if runner.finalState == "Complete" {
1138 if runner.ExitCode != nil {
1139 update["exit_code"] = *runner.ExitCode
1141 if runner.OutputPDH != nil {
1142 update["output"] = *runner.OutputPDH
1145 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1148 // IsCancelled returns the value of Cancelled, with goroutine safety.
1149 func (runner *ContainerRunner) IsCancelled() bool {
1150 runner.cStateLock.Lock()
1151 defer runner.cStateLock.Unlock()
1152 return runner.cCancelled
1155 // NewArvLogWriter creates an ArvLogWriter
1156 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1157 return &ArvLogWriter{ArvClient: runner.ArvClient, UUID: runner.Container.UUID, loggingStream: name,
1158 writeCloser: runner.LogCollection.Open(name + ".txt")}
1161 // Run the full container lifecycle.
1162 func (runner *ContainerRunner) Run() (err error) {
1163 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1165 hostname, hosterr := os.Hostname()
1167 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1169 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1172 // Clean up temporary directories _after_ finalizing
1173 // everything (if we've made any by then)
1174 defer runner.CleanupDirs()
1176 runner.finalState = "Queued"
1179 // checkErr prints e (unless it's nil) and sets err to
1180 // e (unless err is already non-nil). Thus, if err
1181 // hasn't already been assigned when Run() returns,
1182 // this cleanup func will cause Run() to return the
1183 // first non-nil error that is passed to checkErr().
1184 checkErr := func(e error) {
1188 runner.CrunchLog.Print(e)
1194 // Log the error encountered in Run(), if any
1197 if runner.finalState == "Queued" {
1198 runner.CrunchLog.Close()
1199 runner.UpdateContainerFinal()
1203 if runner.IsCancelled() {
1204 runner.finalState = "Cancelled"
1205 // but don't return yet -- we still want to
1206 // capture partial output and write logs
1209 checkErr(runner.CaptureOutput())
1210 checkErr(runner.CommitLogs())
1211 checkErr(runner.UpdateContainerFinal())
1213 // The real log is already closed, but then we opened
1214 // a new one in case we needed to log anything while
1216 runner.CrunchLog.Close()
1219 err = runner.ArvClient.Get("containers", runner.Container.UUID, nil, &runner.Container)
1221 err = fmt.Errorf("While getting container record: %v", err)
1225 // setup signal handling
1226 runner.SetupSignals()
1228 // check for and/or load image
1229 err = runner.LoadImage()
1231 runner.finalState = "Cancelled"
1232 err = fmt.Errorf("While loading container image: %v", err)
1236 // set up FUSE mount and binds
1237 err = runner.SetupMounts()
1239 runner.finalState = "Cancelled"
1240 err = fmt.Errorf("While setting up mounts: %v", err)
1244 err = runner.CreateContainer()
1249 // Gather and record node information
1250 err = runner.LogNodeInfo()
1254 // Save container.json record on log collection
1255 err = runner.LogContainerRecord()
1260 runner.StartCrunchstat()
1262 if runner.IsCancelled() {
1266 err = runner.UpdateContainerRunning()
1270 runner.finalState = "Cancelled"
1272 err = runner.StartContainer()
1277 err = runner.WaitFinish()
1279 runner.finalState = "Complete"
1284 // NewContainerRunner creates a new container runner.
1285 func NewContainerRunner(api IArvadosClient,
1287 docker ThinDockerClient,
1288 containerUUID string) *ContainerRunner {
1290 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1291 cr.NewLogWriter = cr.NewArvLogWriter
1292 cr.RunArvMount = cr.ArvMountCmd
1293 cr.MkTempDir = ioutil.TempDir
1294 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1295 cr.Container.UUID = containerUUID
1296 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1297 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1299 loadLogThrottleParams(api)
1305 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1306 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1307 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1308 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1309 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1310 enableNetwork := flag.String("container-enable-networking", "default",
1311 `Specify if networking should be enabled for container. One of 'default', 'always':
1312 default: only enable networking if container requests it.
1313 always: containers always have networking enabled
1315 networkMode := flag.String("container-network-mode", "default",
1316 `Set networking mode for container. Corresponds to Docker network mode (--net).
1320 containerId := flag.Arg(0)
1322 if *caCertsPath != "" {
1323 arvadosclient.CertFiles = []string{*caCertsPath}
1326 api, err := arvadosclient.MakeArvadosClient()
1328 log.Fatalf("%s: %v", containerId, err)
1332 var kc *keepclient.KeepClient
1333 kc, err = keepclient.MakeKeepClient(api)
1335 log.Fatalf("%s: %v", containerId, err)
1339 var docker *dockerclient.Client
1340 // API version 1.21 corresponds to Docker 1.9, which is currently the
1341 // minimum version we want to support.
1342 docker, err = dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1344 log.Fatalf("%s: %v", containerId, err)
1347 dockerClientProxy := ThinDockerClientProxy{Docker: docker}
1349 cr := NewContainerRunner(api, kc, dockerClientProxy, containerId)
1350 cr.statInterval = *statInterval
1351 cr.cgroupRoot = *cgroupRoot
1352 cr.expectCgroupParent = *cgroupParent
1353 cr.enableNetwork = *enableNetwork
1354 cr.networkMode = *networkMode
1355 if *cgroupParentSubsystem != "" {
1356 p := findCgroup(*cgroupParentSubsystem)
1357 cr.setCgroupParent = p
1358 cr.expectCgroupParent = p
1363 log.Fatalf("%s: %v", containerId, err)