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) (arvados.File, 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, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan 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, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error) {
104 return proxy.Docker.ContainerWait(ctx, container, condition)
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 arvados.File
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 LogConfig: dockercontainer.LogConfig{
807 Resources: dockercontainer.Resources{
808 CgroupParent: runner.setCgroupParent,
812 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
813 tok, err := runner.ContainerToken()
817 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
818 "ARVADOS_API_TOKEN="+tok,
819 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
820 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
822 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
824 if runner.enableNetwork == "always" {
825 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
827 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
831 _, stdinUsed := runner.Container.Mounts["stdin"]
832 runner.ContainerConfig.OpenStdin = stdinUsed
833 runner.ContainerConfig.StdinOnce = stdinUsed
834 runner.ContainerConfig.AttachStdin = stdinUsed
835 runner.ContainerConfig.AttachStdout = true
836 runner.ContainerConfig.AttachStderr = true
838 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
840 return fmt.Errorf("While creating container: %v", err)
843 runner.ContainerID = createdBody.ID
845 return runner.AttachStreams()
848 // StartContainer starts the docker container created by CreateContainer.
849 func (runner *ContainerRunner) StartContainer() error {
850 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
851 runner.cStateLock.Lock()
852 defer runner.cStateLock.Unlock()
853 if runner.cCancelled {
856 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
857 dockertypes.ContainerStartOptions{})
859 return fmt.Errorf("could not start container: %v", err)
861 runner.cStarted = true
865 // WaitFinish waits for the container to terminate, capture the exit code, and
866 // close the stdout/stderr logging.
867 func (runner *ContainerRunner) WaitFinish() (err error) {
868 runner.CrunchLog.Print("Waiting for container to finish")
870 waitOk, waitErr := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID, "not-running")
872 var waitBody dockercontainer.ContainerWaitOKBody
874 case waitBody = <-waitOk:
875 case err = <-waitErr:
879 return fmt.Errorf("container wait: %v", err)
882 runner.CrunchLog.Printf("Container exited with code: %v", waitBody.StatusCode)
883 code := int(waitBody.StatusCode)
884 runner.ExitCode = &code
886 waitMount := runner.ArvMountExit
888 case err = <-waitMount:
889 runner.CrunchLog.Printf("arv-mount exited before container finished: %v", err)
895 // wait for stdout/stderr to complete
901 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
902 func (runner *ContainerRunner) CaptureOutput() error {
903 if runner.finalState != "Complete" {
907 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
908 // Output may have been set directly by the container, so
909 // refresh the container record to check.
910 err := runner.ArvClient.Get("containers", runner.Container.UUID,
911 nil, &runner.Container)
915 if runner.Container.Output != "" {
916 // Container output is already set.
917 runner.OutputPDH = &runner.Container.Output
922 if runner.HostOutputDir == "" {
926 _, err := os.Stat(runner.HostOutputDir)
928 return fmt.Errorf("While checking host output path: %v", err)
931 // Pre-populate output from the configured mount points
933 for bind, mnt := range runner.Container.Mounts {
934 if mnt.Kind == "collection" {
935 binds = append(binds, bind)
940 var manifestText string
942 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
943 _, err = os.Stat(collectionMetafile)
947 // Find symlinks to arv-mounted files & dirs.
948 err = filepath.Walk(runner.HostOutputDir, func(path string, info os.FileInfo, err error) error {
952 if info.Mode()&os.ModeSymlink == 0 {
955 // read link to get container internal path
956 // only support 1 level of symlinking here.
958 tgt, err = os.Readlink(path)
963 // get path relative to output dir
964 outputSuffix := path[len(runner.HostOutputDir):]
966 if strings.HasPrefix(tgt, "/") {
967 // go through mounts and try reverse map to collection reference
968 for _, bind := range binds {
969 mnt := runner.Container.Mounts[bind]
970 if tgt == bind || strings.HasPrefix(tgt, bind+"/") {
971 // get path relative to bind
972 targetSuffix := tgt[len(bind):]
974 // Copy mount and adjust the path to add path relative to the bind
976 adjustedMount.Path = filepath.Join(adjustedMount.Path, targetSuffix)
980 m, err = runner.getCollectionManifestForPath(adjustedMount, outputSuffix)
984 manifestText = manifestText + m
985 // delete symlink so WriteTree won't try to to dereference it.
992 // Not a link to a mount. Must be dereferencible and
993 // point into the output directory.
994 tgt, err = filepath.EvalSymlinks(path)
1000 // Symlink target must be within the output directory otherwise it's an error.
1001 if !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
1003 return fmt.Errorf("Output directory symlink %q points to invalid location %q, must point to mount or output directory.",
1009 return fmt.Errorf("While checking output symlinks: %v", err)
1012 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
1014 m, err = cw.WriteTree(runner.HostOutputDir, runner.CrunchLog.Logger)
1015 manifestText = manifestText + m
1017 return fmt.Errorf("While uploading output files: %v", err)
1020 // FUSE mount directory
1021 file, openerr := os.Open(collectionMetafile)
1023 return fmt.Errorf("While opening FUSE metafile: %v", err)
1027 var rec arvados.Collection
1028 err = json.NewDecoder(file).Decode(&rec)
1030 return fmt.Errorf("While reading FUSE metafile: %v", err)
1032 manifestText = rec.ManifestText
1035 for _, bind := range binds {
1036 mnt := runner.Container.Mounts[bind]
1038 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
1040 if bindSuffix == bind || len(bindSuffix) <= 0 {
1041 // either does not start with OutputPath or is OutputPath itself
1045 if mnt.ExcludeFromOutput == true {
1049 // append to manifest_text
1050 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
1055 manifestText = manifestText + m
1059 var response arvados.Collection
1060 manifest := manifest.Manifest{Text: manifestText}
1061 manifestText = manifest.Extract(".", ".").Text
1062 err = runner.ArvClient.Create("collections",
1064 "ensure_unique_name": true,
1065 "collection": arvadosclient.Dict{
1067 "name": "output for " + runner.Container.UUID,
1068 "manifest_text": manifestText}},
1071 return fmt.Errorf("While creating output collection: %v", err)
1073 runner.OutputPDH = &response.PortableDataHash
1077 var outputCollections = make(map[string]arvados.Collection)
1079 // Fetch the collection for the mnt.PortableDataHash
1080 // Return the manifest_text fragment corresponding to the specified mnt.Path
1081 // after making any required updates.
1083 // If mnt.Path is not specified,
1084 // return the entire manifest_text after replacing any "." with bindSuffix
1085 // If mnt.Path corresponds to one stream,
1086 // return the manifest_text for that stream after replacing that stream name with bindSuffix
1087 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1088 // for that stream after replacing stream name with bindSuffix minus the last word
1089 // and the file name with last word of the bindSuffix
1090 // Allowed path examples:
1092 // "path":"/subdir1"
1093 // "path":"/subdir1/subdir2"
1094 // "path":"/subdir/filename" etc
1095 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1096 collection := outputCollections[mnt.PortableDataHash]
1097 if collection.PortableDataHash == "" {
1098 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1100 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1102 outputCollections[mnt.PortableDataHash] = collection
1105 if collection.ManifestText == "" {
1106 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1110 mft := manifest.Manifest{Text: collection.ManifestText}
1111 extracted := mft.Extract(mnt.Path, bindSuffix)
1112 if extracted.Err != nil {
1113 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1115 return extracted.Text, nil
1118 func (runner *ContainerRunner) CleanupDirs() {
1119 if runner.ArvMount != nil {
1120 umount := exec.Command("fusermount", "-z", "-u", runner.ArvMountPoint)
1121 umnterr := umount.Run()
1123 runner.CrunchLog.Printf("While running fusermount: %v", umnterr)
1126 mnterr := <-runner.ArvMountExit
1128 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
1132 for _, tmpdir := range runner.CleanupTempDir {
1133 rmerr := os.RemoveAll(tmpdir)
1135 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1140 // CommitLogs posts the collection containing the final container logs.
1141 func (runner *ContainerRunner) CommitLogs() error {
1142 runner.CrunchLog.Print(runner.finalState)
1143 runner.CrunchLog.Close()
1145 // Closing CrunchLog above allows it to be committed to Keep at this
1146 // point, but re-open crunch log with ArvClient in case there are any
1147 // other further (such as failing to write the log to Keep!) while
1149 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1150 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1152 if runner.LogsPDH != nil {
1153 // If we have already assigned something to LogsPDH,
1154 // we must be closing the re-opened log, which won't
1155 // end up getting attached to the container record and
1156 // therefore doesn't need to be saved as a collection
1157 // -- it exists only to send logs to other channels.
1161 mt, err := runner.LogCollection.ManifestText()
1163 return fmt.Errorf("While creating log manifest: %v", err)
1166 var response arvados.Collection
1167 err = runner.ArvClient.Create("collections",
1169 "ensure_unique_name": true,
1170 "collection": arvadosclient.Dict{
1172 "name": "logs for " + runner.Container.UUID,
1173 "manifest_text": mt}},
1176 return fmt.Errorf("While creating log collection: %v", err)
1178 runner.LogsPDH = &response.PortableDataHash
1182 // UpdateContainerRunning updates the container state to "Running"
1183 func (runner *ContainerRunner) UpdateContainerRunning() error {
1184 runner.cStateLock.Lock()
1185 defer runner.cStateLock.Unlock()
1186 if runner.cCancelled {
1189 return runner.ArvClient.Update("containers", runner.Container.UUID,
1190 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1193 // ContainerToken returns the api_token the container (and any
1194 // arv-mount processes) are allowed to use.
1195 func (runner *ContainerRunner) ContainerToken() (string, error) {
1196 if runner.token != "" {
1197 return runner.token, nil
1200 var auth arvados.APIClientAuthorization
1201 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1205 runner.token = auth.APIToken
1206 return runner.token, nil
1209 // UpdateContainerComplete updates the container record state on API
1210 // server to "Complete" or "Cancelled"
1211 func (runner *ContainerRunner) UpdateContainerFinal() error {
1212 update := arvadosclient.Dict{}
1213 update["state"] = runner.finalState
1214 if runner.LogsPDH != nil {
1215 update["log"] = *runner.LogsPDH
1217 if runner.finalState == "Complete" {
1218 if runner.ExitCode != nil {
1219 update["exit_code"] = *runner.ExitCode
1221 if runner.OutputPDH != nil {
1222 update["output"] = *runner.OutputPDH
1225 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1228 // IsCancelled returns the value of Cancelled, with goroutine safety.
1229 func (runner *ContainerRunner) IsCancelled() bool {
1230 runner.cStateLock.Lock()
1231 defer runner.cStateLock.Unlock()
1232 return runner.cCancelled
1235 // NewArvLogWriter creates an ArvLogWriter
1236 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1237 return &ArvLogWriter{ArvClient: runner.ArvClient, UUID: runner.Container.UUID, loggingStream: name,
1238 writeCloser: runner.LogCollection.Open(name + ".txt")}
1241 // Run the full container lifecycle.
1242 func (runner *ContainerRunner) Run() (err error) {
1243 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1245 hostname, hosterr := os.Hostname()
1247 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1249 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1252 // Clean up temporary directories _after_ finalizing
1253 // everything (if we've made any by then)
1254 defer runner.CleanupDirs()
1256 runner.finalState = "Queued"
1259 // checkErr prints e (unless it's nil) and sets err to
1260 // e (unless err is already non-nil). Thus, if err
1261 // hasn't already been assigned when Run() returns,
1262 // this cleanup func will cause Run() to return the
1263 // first non-nil error that is passed to checkErr().
1264 checkErr := func(e error) {
1268 runner.CrunchLog.Print(e)
1272 if runner.finalState == "Complete" {
1273 // There was an error in the finalization.
1274 runner.finalState = "Cancelled"
1278 // Log the error encountered in Run(), if any
1281 if runner.finalState == "Queued" {
1282 runner.CrunchLog.Close()
1283 runner.UpdateContainerFinal()
1287 if runner.IsCancelled() {
1288 runner.finalState = "Cancelled"
1289 // but don't return yet -- we still want to
1290 // capture partial output and write logs
1293 checkErr(runner.CaptureOutput())
1294 checkErr(runner.CommitLogs())
1295 checkErr(runner.UpdateContainerFinal())
1297 // The real log is already closed, but then we opened
1298 // a new one in case we needed to log anything while
1300 runner.CrunchLog.Close()
1303 err = runner.ArvClient.Get("containers", runner.Container.UUID, nil, &runner.Container)
1305 err = fmt.Errorf("While getting container record: %v", err)
1309 // setup signal handling
1310 runner.SetupSignals()
1312 // check for and/or load image
1313 err = runner.LoadImage()
1315 runner.finalState = "Cancelled"
1316 err = fmt.Errorf("While loading container image: %v", err)
1320 // set up FUSE mount and binds
1321 err = runner.SetupMounts()
1323 runner.finalState = "Cancelled"
1324 err = fmt.Errorf("While setting up mounts: %v", err)
1328 err = runner.CreateContainer()
1333 // Gather and record node information
1334 err = runner.LogNodeInfo()
1338 // Save container.json record on log collection
1339 err = runner.LogContainerRecord()
1344 runner.StartCrunchstat()
1346 if runner.IsCancelled() {
1350 err = runner.UpdateContainerRunning()
1354 runner.finalState = "Cancelled"
1356 err = runner.StartContainer()
1361 err = runner.WaitFinish()
1363 runner.finalState = "Complete"
1368 // NewContainerRunner creates a new container runner.
1369 func NewContainerRunner(api IArvadosClient,
1371 docker ThinDockerClient,
1372 containerUUID string) *ContainerRunner {
1374 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1375 cr.NewLogWriter = cr.NewArvLogWriter
1376 cr.RunArvMount = cr.ArvMountCmd
1377 cr.MkTempDir = ioutil.TempDir
1378 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1379 cr.Container.UUID = containerUUID
1380 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1381 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1383 loadLogThrottleParams(api)
1389 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1390 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1391 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1392 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1393 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1394 enableNetwork := flag.String("container-enable-networking", "default",
1395 `Specify if networking should be enabled for container. One of 'default', 'always':
1396 default: only enable networking if container requests it.
1397 always: containers always have networking enabled
1399 networkMode := flag.String("container-network-mode", "default",
1400 `Set networking mode for container. Corresponds to Docker network mode (--net).
1404 containerId := flag.Arg(0)
1406 if *caCertsPath != "" {
1407 arvadosclient.CertFiles = []string{*caCertsPath}
1410 api, err := arvadosclient.MakeArvadosClient()
1412 log.Fatalf("%s: %v", containerId, err)
1416 var kc *keepclient.KeepClient
1417 kc, err = keepclient.MakeKeepClient(api)
1419 log.Fatalf("%s: %v", containerId, err)
1423 var docker *dockerclient.Client
1424 // API version 1.21 corresponds to Docker 1.9, which is currently the
1425 // minimum version we want to support.
1426 docker, err = dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1428 log.Fatalf("%s: %v", containerId, err)
1431 dockerClientProxy := ThinDockerClientProxy{Docker: docker}
1433 cr := NewContainerRunner(api, kc, dockerClientProxy, containerId)
1434 cr.statInterval = *statInterval
1435 cr.cgroupRoot = *cgroupRoot
1436 cr.expectCgroupParent = *cgroupParent
1437 cr.enableNetwork = *enableNetwork
1438 cr.networkMode = *networkMode
1439 if *cgroupParentSubsystem != "" {
1440 p := findCgroup(*cgroupParentSubsystem)
1441 cr.setCgroupParent = p
1442 cr.expectCgroupParent = p
1447 log.Fatalf("%s: %v", containerId, err)