22 "git.curoverse.com/arvados.git/lib/crunchstat"
23 "git.curoverse.com/arvados.git/sdk/go/arvados"
24 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
25 "git.curoverse.com/arvados.git/sdk/go/keepclient"
26 "git.curoverse.com/arvados.git/sdk/go/manifest"
27 "github.com/curoverse/dockerclient"
30 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
31 type IArvadosClient interface {
32 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
33 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
34 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
35 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
36 Discovery(key string) (interface{}, error)
39 // ErrCancelled is the error returned when the container is cancelled.
40 var ErrCancelled = errors.New("Cancelled")
42 // IKeepClient is the minimal Keep API methods used by crunch-run.
43 type IKeepClient interface {
44 PutHB(hash string, buf []byte) (string, int, error)
45 ManifestFileReader(m manifest.Manifest, filename string) (keepclient.Reader, error)
48 // NewLogWriter is a factory function to create a new log writer.
49 type NewLogWriter func(name string) io.WriteCloser
51 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
53 type MkTempDir func(string, string) (string, error)
55 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
56 type ThinDockerClient interface {
57 StopContainer(id string, timeout int) error
58 InspectImage(id string) (*dockerclient.ImageInfo, error)
59 LoadImage(reader io.Reader) error
60 CreateContainer(config *dockerclient.ContainerConfig, name string, authConfig *dockerclient.AuthConfig) (string, error)
61 StartContainer(id string, config *dockerclient.HostConfig) error
62 AttachContainer(id string, options *dockerclient.AttachOptions) (io.ReadCloser, error)
63 Wait(id string) <-chan dockerclient.WaitResult
64 RemoveImage(name string, force bool) ([]*dockerclient.ImageDelete, error)
67 // ContainerRunner is the main stateful struct used for a single execution of a
69 type ContainerRunner struct {
70 Docker ThinDockerClient
71 ArvClient IArvadosClient
74 dockerclient.ContainerConfig
75 dockerclient.HostConfig
81 CrunchLog *ThrottledLogger
83 Stderr *ThrottledLogger
84 LogCollection *CollectionWriter
91 CleanupTempDir []string
94 SigChan chan os.Signal
95 ArvMountExit chan error
98 statLogger io.WriteCloser
99 statReporter *crunchstat.Reporter
100 statInterval time.Duration
102 // What we expect the container's cgroup parent to be.
103 expectCgroupParent string
104 // What we tell docker to use as the container's cgroup
105 // parent. Note: Ideally we would use the same field for both
106 // expectCgroupParent and setCgroupParent, and just make it
107 // default to "docker". However, when using docker < 1.10 with
108 // systemd, specifying a non-empty cgroup parent (even the
109 // default value "docker") hits a docker bug
110 // (https://github.com/docker/docker/issues/17126). Using two
111 // separate fields makes it possible to use the "expect cgroup
112 // parent to be X" feature even on sites where the "specify
113 // cgroup parent" feature breaks.
114 setCgroupParent string
116 cStateLock sync.Mutex
117 cStarted bool // StartContainer() succeeded
118 cCancelled bool // StopContainer() invoked
121 // SetupSignals sets up signal handling to gracefully terminate the underlying
122 // Docker container and update state when receiving a TERM, INT or QUIT signal.
123 func (runner *ContainerRunner) SetupSignals() {
124 runner.SigChan = make(chan os.Signal, 1)
125 signal.Notify(runner.SigChan, syscall.SIGTERM)
126 signal.Notify(runner.SigChan, syscall.SIGINT)
127 signal.Notify(runner.SigChan, syscall.SIGQUIT)
129 go func(sig chan os.Signal) {
131 log.Print("signal handler calling runner.stop()")
137 // stop the underlying Docker container.
138 func (runner *ContainerRunner) stop() {
139 runner.cStateLock.Lock()
140 defer runner.cStateLock.Unlock()
141 if runner.cCancelled {
144 runner.cCancelled = true
146 err := runner.Docker.StopContainer(runner.ContainerID, 10)
148 log.Printf("StopContainer failed: %s", err)
153 // LoadImage determines the docker image id from the container record and
154 // checks if it is available in the local Docker image store. If not, it loads
155 // the image from Keep.
156 func (runner *ContainerRunner) LoadImage() (err error) {
158 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
160 var collection arvados.Collection
161 err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
163 return fmt.Errorf("While getting container image collection: %v", err)
165 manifest := manifest.Manifest{Text: collection.ManifestText}
166 var img, imageID string
167 for ms := range manifest.StreamIter() {
168 img = ms.FileStreamSegments[0].Name
169 if !strings.HasSuffix(img, ".tar") {
170 return fmt.Errorf("First file in the container image collection does not end in .tar")
172 imageID = img[:len(img)-4]
175 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
177 _, err = runner.Docker.InspectImage(imageID)
179 runner.CrunchLog.Print("Loading Docker image from keep")
181 var readCloser io.ReadCloser
182 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
184 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
187 err = runner.Docker.LoadImage(readCloser)
189 return fmt.Errorf("While loading container image into Docker: %v", err)
192 runner.CrunchLog.Print("Docker image is available")
195 runner.ContainerConfig.Image = imageID
200 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
201 c = exec.Command("arv-mount", arvMountCmd...)
203 // Copy our environment, but override ARVADOS_API_TOKEN with
204 // the container auth token.
206 for _, s := range os.Environ() {
207 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
208 c.Env = append(c.Env, s)
211 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
213 nt := NewThrottledLogger(runner.NewLogWriter("arv-mount"))
222 statReadme := make(chan bool)
223 runner.ArvMountExit = make(chan error)
228 time.Sleep(100 * time.Millisecond)
229 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
239 runner.ArvMountExit <- c.Wait()
240 close(runner.ArvMountExit)
246 case err := <-runner.ArvMountExit:
247 runner.ArvMount = nil
255 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
256 if runner.ArvMountPoint == "" {
257 runner.ArvMountPoint, err = runner.MkTempDir("", prefix)
262 func (runner *ContainerRunner) SetupMounts() (err error) {
263 err = runner.SetupArvMountPoint("keep")
265 return fmt.Errorf("While creating keep mount temp dir: %v", err)
268 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.ArvMountPoint)
272 arvMountCmd := []string{"--foreground", "--allow-other", "--read-write"}
274 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
275 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
278 collectionPaths := []string{}
280 needCertMount := true
283 for bind, _ := range runner.Container.Mounts {
284 binds = append(binds, bind)
288 for _, bind := range binds {
289 mnt := runner.Container.Mounts[bind]
290 if bind == "stdout" {
291 // Is it a "file" mount kind?
292 if mnt.Kind != "file" {
293 return fmt.Errorf("Unsupported mount kind '%s' for stdout. Only 'file' is supported.", mnt.Kind)
296 // Does path start with OutputPath?
297 prefix := runner.Container.OutputPath
298 if !strings.HasSuffix(prefix, "/") {
301 if !strings.HasPrefix(mnt.Path, prefix) {
302 return fmt.Errorf("Stdout path does not start with OutputPath: %s, %s", mnt.Path, prefix)
306 if bind == "/etc/arvados/ca-certificates.crt" {
307 needCertMount = false
310 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
311 if mnt.Kind != "collection" {
312 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
317 case mnt.Kind == "collection":
319 if mnt.UUID != "" && mnt.PortableDataHash != "" {
320 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
324 return fmt.Errorf("Writing to existing collections currently not permitted.")
327 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
328 } else if mnt.PortableDataHash != "" {
330 return fmt.Errorf("Can never write to a collection specified by portable data hash")
332 idx := strings.Index(mnt.PortableDataHash, "/")
334 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
335 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
336 runner.Container.Mounts[bind] = mnt
338 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
339 if mnt.Path != "" && mnt.Path != "." {
340 if strings.HasPrefix(mnt.Path, "./") {
341 mnt.Path = mnt.Path[2:]
342 } else if strings.HasPrefix(mnt.Path, "/") {
343 mnt.Path = mnt.Path[1:]
345 src += "/" + mnt.Path
348 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
349 arvMountCmd = append(arvMountCmd, "--mount-tmp")
350 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
354 if bind == runner.Container.OutputPath {
355 runner.HostOutputDir = src
356 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
357 return fmt.Errorf("Writable mount points are not permitted underneath the output_path: %v", bind)
359 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
361 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
363 collectionPaths = append(collectionPaths, src)
365 case mnt.Kind == "tmp" && bind == runner.Container.OutputPath:
366 runner.HostOutputDir, err = runner.MkTempDir("", "")
368 return fmt.Errorf("While creating mount temp dir: %v", err)
370 st, staterr := os.Stat(runner.HostOutputDir)
372 return fmt.Errorf("While Stat on temp dir: %v", staterr)
374 err = os.Chmod(runner.HostOutputDir, st.Mode()|os.ModeSetgid|0777)
376 return fmt.Errorf("While Chmod temp dir: %v", err)
378 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.HostOutputDir)
379 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", runner.HostOutputDir, bind))
381 case mnt.Kind == "tmp":
382 runner.Binds = append(runner.Binds, bind)
384 case mnt.Kind == "json":
385 jsondata, err := json.Marshal(mnt.Content)
387 return fmt.Errorf("encoding json data: %v", err)
389 // Create a tempdir with a single file
390 // (instead of just a tempfile): this way we
391 // can ensure the file is world-readable
392 // inside the container, without having to
393 // make it world-readable on the docker host.
394 tmpdir, err := runner.MkTempDir("", "")
396 return fmt.Errorf("creating temp dir: %v", err)
398 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
399 tmpfn := filepath.Join(tmpdir, "mountdata.json")
400 err = ioutil.WriteFile(tmpfn, jsondata, 0644)
402 return fmt.Errorf("writing temp file: %v", err)
404 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
408 if runner.HostOutputDir == "" {
409 return fmt.Errorf("Output path does not correspond to a writable mount point")
412 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
413 for _, certfile := range arvadosclient.CertFiles {
414 _, err := os.Stat(certfile)
416 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
423 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
425 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
427 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
429 token, err := runner.ContainerToken()
431 return fmt.Errorf("could not get container token: %s", err)
434 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
436 return fmt.Errorf("While trying to start arv-mount: %v", err)
439 for _, p := range collectionPaths {
442 return fmt.Errorf("While checking that input files exist: %v", err)
449 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
450 // Handle docker log protocol
451 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
453 header := make([]byte, 8)
455 _, readerr := io.ReadAtLeast(containerReader, header, 8)
458 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
461 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
464 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
469 if readerr != io.EOF {
470 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
473 closeerr := runner.Stdout.Close()
475 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
478 closeerr = runner.Stderr.Close()
480 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
483 if runner.statReporter != nil {
484 runner.statReporter.Stop()
485 closeerr = runner.statLogger.Close()
487 runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
491 runner.loggingDone <- true
492 close(runner.loggingDone)
498 func (runner *ContainerRunner) StartCrunchstat() {
499 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
500 runner.statReporter = &crunchstat.Reporter{
501 CID: runner.ContainerID,
502 Logger: log.New(runner.statLogger, "", 0),
503 CgroupParent: runner.expectCgroupParent,
504 CgroupRoot: runner.cgroupRoot,
505 PollPeriod: runner.statInterval,
507 runner.statReporter.Start()
510 type infoCommand struct {
515 // Gather node information and store it on the log for debugging
517 func (runner *ContainerRunner) LogNodeInfo() (err error) {
518 w := runner.NewLogWriter("node-info")
519 logger := log.New(w, "node-info", 0)
521 commands := []infoCommand{
523 label: "Host Information",
524 cmd: []string{"uname", "-a"},
527 label: "CPU Information",
528 cmd: []string{"cat", "/proc/cpuinfo"},
531 label: "Memory Information",
532 cmd: []string{"cat", "/proc/meminfo"},
536 cmd: []string{"df", "-m"},
540 // Run commands with informational output to be logged.
542 for _, command := range commands {
543 out, err = exec.Command(command.cmd[0], command.cmd[1:]...).Output()
545 return fmt.Errorf("While running command '%s': %v",
548 logger.Println(command.label)
549 for _, line := range strings.Split(string(out), "\n") {
550 logger.Println(" ", line)
556 return fmt.Errorf("While closing node-info logs: %v", err)
561 // Get and save the raw JSON container record from the API server
562 func (runner *ContainerRunner) LogContainerRecord() (err error) {
565 runner.Container.UUID,
567 runner.LogCollection.Open("container.json"),
569 logger := log.New(w, "container", 0)
571 // Convert container record to pretty-printed JSON []byte
572 rec, err := json.MarshalIndent(runner.Container, "", " ")
574 return fmt.Errorf("While converting container record to JSON: %v", err)
577 // Write JSON record line-by-line
578 for _, line := range strings.Split(string(rec), "\n") {
584 return fmt.Errorf("While closing container.json log: %v", err)
589 // AttachLogs connects the docker container stdout and stderr logs to the
590 // Arvados logger which logs to Keep and the API server logs table.
591 func (runner *ContainerRunner) AttachStreams() (err error) {
593 runner.CrunchLog.Print("Attaching container streams")
595 var containerReader io.Reader
596 containerReader, err = runner.Docker.AttachContainer(runner.ContainerID,
597 &dockerclient.AttachOptions{Stream: true, Stdout: true, Stderr: true})
599 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
602 runner.loggingDone = make(chan bool)
604 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
605 stdoutPath := stdoutMnt.Path[len(runner.Container.OutputPath):]
606 index := strings.LastIndex(stdoutPath, "/")
608 subdirs := stdoutPath[:index]
610 st, err := os.Stat(runner.HostOutputDir)
612 return fmt.Errorf("While Stat on temp dir: %v", err)
614 stdoutPath := path.Join(runner.HostOutputDir, subdirs)
615 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
617 return fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
621 stdoutFile, err := os.Create(path.Join(runner.HostOutputDir, stdoutPath))
623 return fmt.Errorf("While creating stdout file: %v", err)
625 runner.Stdout = stdoutFile
627 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
629 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
631 go runner.ProcessDockerAttach(containerReader)
636 // CreateContainer creates the docker container.
637 func (runner *ContainerRunner) CreateContainer() error {
638 runner.CrunchLog.Print("Creating Docker container")
640 runner.ContainerConfig.Cmd = runner.Container.Command
641 if runner.Container.Cwd != "." {
642 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
645 for k, v := range runner.Container.Environment {
646 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
648 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
649 tok, err := runner.ContainerToken()
653 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
654 "ARVADOS_API_TOKEN="+tok,
655 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
656 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
658 runner.ContainerConfig.NetworkDisabled = false
660 runner.ContainerConfig.NetworkDisabled = true
664 runner.ContainerID, err = runner.Docker.CreateContainer(&runner.ContainerConfig, "", nil)
666 return fmt.Errorf("While creating container: %v", err)
669 runner.HostConfig = dockerclient.HostConfig{
671 CgroupParent: runner.setCgroupParent,
672 LogConfig: dockerclient.LogConfig{
677 return runner.AttachStreams()
680 // StartContainer starts the docker container created by CreateContainer.
681 func (runner *ContainerRunner) StartContainer() error {
682 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
683 runner.cStateLock.Lock()
684 defer runner.cStateLock.Unlock()
685 if runner.cCancelled {
688 err := runner.Docker.StartContainer(runner.ContainerID, &runner.HostConfig)
690 return fmt.Errorf("could not start container: %v", err)
692 runner.cStarted = true
696 // WaitFinish waits for the container to terminate, capture the exit code, and
697 // close the stdout/stderr logging.
698 func (runner *ContainerRunner) WaitFinish() error {
699 runner.CrunchLog.Print("Waiting for container to finish")
701 waitDocker := runner.Docker.Wait(runner.ContainerID)
702 waitMount := runner.ArvMountExit
703 for waitDocker != nil {
705 case err := <-waitMount:
706 runner.CrunchLog.Printf("arv-mount exited before container finished: %v", err)
709 case wr := <-waitDocker:
711 return fmt.Errorf("While waiting for container to finish: %v", wr.Error)
713 runner.ExitCode = &wr.ExitCode
718 // wait for stdout/stderr to complete
724 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
725 func (runner *ContainerRunner) CaptureOutput() error {
726 if runner.finalState != "Complete" {
730 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
731 // Output may have been set directly by the container, so
732 // refresh the container record to check.
733 err := runner.ArvClient.Get("containers", runner.Container.UUID,
734 nil, &runner.Container)
738 if runner.Container.Output != "" {
739 // Container output is already set.
740 runner.OutputPDH = &runner.Container.Output
745 if runner.HostOutputDir == "" {
749 _, err := os.Stat(runner.HostOutputDir)
751 return fmt.Errorf("While checking host output path: %v", err)
754 var manifestText string
756 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
757 _, err = os.Stat(collectionMetafile)
760 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
761 manifestText, err = cw.WriteTree(runner.HostOutputDir, runner.CrunchLog.Logger)
763 return fmt.Errorf("While uploading output files: %v", err)
766 // FUSE mount directory
767 file, openerr := os.Open(collectionMetafile)
769 return fmt.Errorf("While opening FUSE metafile: %v", err)
773 var rec arvados.Collection
774 err = json.NewDecoder(file).Decode(&rec)
776 return fmt.Errorf("While reading FUSE metafile: %v", err)
778 manifestText = rec.ManifestText
781 // Pre-populate output from the configured mount points
783 for bind, _ := range runner.Container.Mounts {
784 binds = append(binds, bind)
788 for _, bind := range binds {
789 mnt := runner.Container.Mounts[bind]
791 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
793 if bindSuffix == bind || len(bindSuffix) <= 0 {
794 // either does not start with OutputPath or is OutputPath itself
798 if mnt.ExcludeFromOutput == true {
802 // append to manifest_text
803 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
808 manifestText = manifestText + m
812 var response arvados.Collection
813 manifest := manifest.Manifest{Text: manifestText}
814 manifestText = manifest.Extract(".", ".").Text
815 err = runner.ArvClient.Create("collections",
817 "ensure_unique_name": true,
818 "collection": arvadosclient.Dict{
820 "name": "output for " + runner.Container.UUID,
821 "manifest_text": manifestText}},
824 return fmt.Errorf("While creating output collection: %v", err)
826 runner.OutputPDH = &response.PortableDataHash
830 var outputCollections = make(map[string]arvados.Collection)
832 // Fetch the collection for the mnt.PortableDataHash
833 // Return the manifest_text fragment corresponding to the specified mnt.Path
834 // after making any required updates.
836 // If mnt.Path is not specified,
837 // return the entire manifest_text after replacing any "." with bindSuffix
838 // If mnt.Path corresponds to one stream,
839 // return the manifest_text for that stream after replacing that stream name with bindSuffix
840 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
841 // for that stream after replacing stream name with bindSuffix minus the last word
842 // and the file name with last word of the bindSuffix
843 // Allowed path examples:
846 // "path":"/subdir1/subdir2"
847 // "path":"/subdir/filename" etc
848 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
849 collection := outputCollections[mnt.PortableDataHash]
850 if collection.PortableDataHash == "" {
851 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
853 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
855 outputCollections[mnt.PortableDataHash] = collection
858 if collection.ManifestText == "" {
859 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
863 mft := manifest.Manifest{Text: collection.ManifestText}
864 extracted := mft.Extract(mnt.Path, bindSuffix)
865 if extracted.Err != nil {
866 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
868 return extracted.Text, nil
871 func (runner *ContainerRunner) CleanupDirs() {
872 if runner.ArvMount != nil {
873 umount := exec.Command("fusermount", "-z", "-u", runner.ArvMountPoint)
874 umnterr := umount.Run()
876 runner.CrunchLog.Printf("While running fusermount: %v", umnterr)
879 mnterr := <-runner.ArvMountExit
881 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
885 for _, tmpdir := range runner.CleanupTempDir {
886 rmerr := os.RemoveAll(tmpdir)
888 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
893 // CommitLogs posts the collection containing the final container logs.
894 func (runner *ContainerRunner) CommitLogs() error {
895 runner.CrunchLog.Print(runner.finalState)
896 runner.CrunchLog.Close()
898 // Closing CrunchLog above allows it to be committed to Keep at this
899 // point, but re-open crunch log with ArvClient in case there are any
900 // other further (such as failing to write the log to Keep!) while
902 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{runner.ArvClient, runner.Container.UUID,
905 if runner.LogsPDH != nil {
906 // If we have already assigned something to LogsPDH,
907 // we must be closing the re-opened log, which won't
908 // end up getting attached to the container record and
909 // therefore doesn't need to be saved as a collection
910 // -- it exists only to send logs to other channels.
914 mt, err := runner.LogCollection.ManifestText()
916 return fmt.Errorf("While creating log manifest: %v", err)
919 var response arvados.Collection
920 err = runner.ArvClient.Create("collections",
922 "ensure_unique_name": true,
923 "collection": arvadosclient.Dict{
925 "name": "logs for " + runner.Container.UUID,
926 "manifest_text": mt}},
929 return fmt.Errorf("While creating log collection: %v", err)
931 runner.LogsPDH = &response.PortableDataHash
935 // UpdateContainerRunning updates the container state to "Running"
936 func (runner *ContainerRunner) UpdateContainerRunning() error {
937 runner.cStateLock.Lock()
938 defer runner.cStateLock.Unlock()
939 if runner.cCancelled {
942 return runner.ArvClient.Update("containers", runner.Container.UUID,
943 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
946 // ContainerToken returns the api_token the container (and any
947 // arv-mount processes) are allowed to use.
948 func (runner *ContainerRunner) ContainerToken() (string, error) {
949 if runner.token != "" {
950 return runner.token, nil
953 var auth arvados.APIClientAuthorization
954 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
958 runner.token = auth.APIToken
959 return runner.token, nil
962 // UpdateContainerComplete updates the container record state on API
963 // server to "Complete" or "Cancelled"
964 func (runner *ContainerRunner) UpdateContainerFinal() error {
965 update := arvadosclient.Dict{}
966 update["state"] = runner.finalState
967 if runner.LogsPDH != nil {
968 update["log"] = *runner.LogsPDH
970 if runner.finalState == "Complete" {
971 if runner.ExitCode != nil {
972 update["exit_code"] = *runner.ExitCode
974 if runner.OutputPDH != nil {
975 update["output"] = *runner.OutputPDH
978 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
981 // IsCancelled returns the value of Cancelled, with goroutine safety.
982 func (runner *ContainerRunner) IsCancelled() bool {
983 runner.cStateLock.Lock()
984 defer runner.cStateLock.Unlock()
985 return runner.cCancelled
988 // NewArvLogWriter creates an ArvLogWriter
989 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
990 return &ArvLogWriter{runner.ArvClient, runner.Container.UUID, name, runner.LogCollection.Open(name + ".txt")}
993 // Run the full container lifecycle.
994 func (runner *ContainerRunner) Run() (err error) {
995 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
997 hostname, hosterr := os.Hostname()
999 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1001 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1004 // Clean up temporary directories _after_ finalizing
1005 // everything (if we've made any by then)
1006 defer runner.CleanupDirs()
1008 runner.finalState = "Queued"
1011 // checkErr prints e (unless it's nil) and sets err to
1012 // e (unless err is already non-nil). Thus, if err
1013 // hasn't already been assigned when Run() returns,
1014 // this cleanup func will cause Run() to return the
1015 // first non-nil error that is passed to checkErr().
1016 checkErr := func(e error) {
1020 runner.CrunchLog.Print(e)
1026 // Log the error encountered in Run(), if any
1029 if runner.finalState == "Queued" {
1030 runner.CrunchLog.Close()
1031 runner.UpdateContainerFinal()
1035 if runner.IsCancelled() {
1036 runner.finalState = "Cancelled"
1037 // but don't return yet -- we still want to
1038 // capture partial output and write logs
1041 checkErr(runner.CaptureOutput())
1042 checkErr(runner.CommitLogs())
1043 checkErr(runner.UpdateContainerFinal())
1045 // The real log is already closed, but then we opened
1046 // a new one in case we needed to log anything while
1048 runner.CrunchLog.Close()
1051 err = runner.ArvClient.Get("containers", runner.Container.UUID, nil, &runner.Container)
1053 err = fmt.Errorf("While getting container record: %v", err)
1057 // setup signal handling
1058 runner.SetupSignals()
1060 // check for and/or load image
1061 err = runner.LoadImage()
1063 runner.finalState = "Cancelled"
1064 err = fmt.Errorf("While loading container image: %v", err)
1068 // set up FUSE mount and binds
1069 err = runner.SetupMounts()
1071 runner.finalState = "Cancelled"
1072 err = fmt.Errorf("While setting up mounts: %v", err)
1076 err = runner.CreateContainer()
1081 // Gather and record node information
1082 err = runner.LogNodeInfo()
1086 // Save container.json record on log collection
1087 err = runner.LogContainerRecord()
1092 runner.StartCrunchstat()
1094 if runner.IsCancelled() {
1098 err = runner.UpdateContainerRunning()
1102 runner.finalState = "Cancelled"
1104 err = runner.StartContainer()
1109 err = runner.WaitFinish()
1111 runner.finalState = "Complete"
1116 // NewContainerRunner creates a new container runner.
1117 func NewContainerRunner(api IArvadosClient,
1119 docker ThinDockerClient,
1120 containerUUID string) *ContainerRunner {
1122 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1123 cr.NewLogWriter = cr.NewArvLogWriter
1124 cr.RunArvMount = cr.ArvMountCmd
1125 cr.MkTempDir = ioutil.TempDir
1126 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1127 cr.Container.UUID = containerUUID
1128 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1129 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1134 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1135 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1136 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1137 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1138 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1141 containerId := flag.Arg(0)
1143 if *caCertsPath != "" {
1144 arvadosclient.CertFiles = []string{*caCertsPath}
1147 api, err := arvadosclient.MakeArvadosClient()
1149 log.Fatalf("%s: %v", containerId, err)
1153 var kc *keepclient.KeepClient
1154 kc, err = keepclient.MakeKeepClient(api)
1156 log.Fatalf("%s: %v", containerId, err)
1160 var docker *dockerclient.DockerClient
1161 docker, err = dockerclient.NewDockerClient("unix:///var/run/docker.sock", nil)
1163 log.Fatalf("%s: %v", containerId, err)
1166 cr := NewContainerRunner(api, kc, docker, containerId)
1167 cr.statInterval = *statInterval
1168 cr.cgroupRoot = *cgroupRoot
1169 cr.expectCgroupParent = *cgroupParent
1170 if *cgroupParentSubsystem != "" {
1171 p := findCgroup(*cgroupParentSubsystem)
1172 cr.setCgroupParent = p
1173 cr.expectCgroupParent = p
1178 log.Fatalf("%s: %v", containerId, err)