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 CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
37 Discovery(key string) (interface{}, error)
40 // ErrCancelled is the error returned when the container is cancelled.
41 var ErrCancelled = errors.New("Cancelled")
43 // IKeepClient is the minimal Keep API methods used by crunch-run.
44 type IKeepClient interface {
45 PutHB(hash string, buf []byte) (string, int, error)
46 ManifestFileReader(m manifest.Manifest, filename string) (keepclient.Reader, error)
49 // NewLogWriter is a factory function to create a new log writer.
50 type NewLogWriter func(name string) io.WriteCloser
52 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
54 type MkTempDir func(string, string) (string, error)
56 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
57 type ThinDockerClient interface {
58 StopContainer(id string, timeout int) error
59 InspectImage(id string) (*dockerclient.ImageInfo, error)
60 LoadImage(reader io.Reader) error
61 CreateContainer(config *dockerclient.ContainerConfig, name string, authConfig *dockerclient.AuthConfig) (string, error)
62 StartContainer(id string, config *dockerclient.HostConfig) error
63 AttachContainer(id string, options *dockerclient.AttachOptions) (io.ReadCloser, error)
64 Wait(id string) <-chan dockerclient.WaitResult
65 RemoveImage(name string, force bool) ([]*dockerclient.ImageDelete, error)
68 // ContainerRunner is the main stateful struct used for a single execution of a
70 type ContainerRunner struct {
71 Docker ThinDockerClient
72 ArvClient IArvadosClient
75 dockerclient.ContainerConfig
76 dockerclient.HostConfig
82 CrunchLog *ThrottledLogger
84 Stderr *ThrottledLogger
85 LogCollection *CollectionWriter
92 CleanupTempDir []string
95 SigChan chan os.Signal
96 ArvMountExit chan error
99 statLogger io.WriteCloser
100 statReporter *crunchstat.Reporter
101 statInterval time.Duration
103 // What we expect the container's cgroup parent to be.
104 expectCgroupParent string
105 // What we tell docker to use as the container's cgroup
106 // parent. Note: Ideally we would use the same field for both
107 // expectCgroupParent and setCgroupParent, and just make it
108 // default to "docker". However, when using docker < 1.10 with
109 // systemd, specifying a non-empty cgroup parent (even the
110 // default value "docker") hits a docker bug
111 // (https://github.com/docker/docker/issues/17126). Using two
112 // separate fields makes it possible to use the "expect cgroup
113 // parent to be X" feature even on sites where the "specify
114 // cgroup parent" feature breaks.
115 setCgroupParent string
117 cStateLock sync.Mutex
118 cStarted bool // StartContainer() succeeded
119 cCancelled bool // StopContainer() invoked
121 enableNetwork string // one of "default" or "always"
122 networkMode string // passed through to HostConfig.NetworkMode
125 // SetupSignals sets up signal handling to gracefully terminate the underlying
126 // Docker container and update state when receiving a TERM, INT or QUIT signal.
127 func (runner *ContainerRunner) SetupSignals() {
128 runner.SigChan = make(chan os.Signal, 1)
129 signal.Notify(runner.SigChan, syscall.SIGTERM)
130 signal.Notify(runner.SigChan, syscall.SIGINT)
131 signal.Notify(runner.SigChan, syscall.SIGQUIT)
133 go func(sig chan os.Signal) {
140 // stop the underlying Docker container.
141 func (runner *ContainerRunner) stop() {
142 runner.cStateLock.Lock()
143 defer runner.cStateLock.Unlock()
144 if runner.cCancelled {
147 runner.cCancelled = true
149 err := runner.Docker.StopContainer(runner.ContainerID, 10)
151 log.Printf("StopContainer failed: %s", err)
156 // LoadImage determines the docker image id from the container record and
157 // checks if it is available in the local Docker image store. If not, it loads
158 // the image from Keep.
159 func (runner *ContainerRunner) LoadImage() (err error) {
161 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
163 var collection arvados.Collection
164 err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
166 return fmt.Errorf("While getting container image collection: %v", err)
168 manifest := manifest.Manifest{Text: collection.ManifestText}
169 var img, imageID string
170 for ms := range manifest.StreamIter() {
171 img = ms.FileStreamSegments[0].Name
172 if !strings.HasSuffix(img, ".tar") {
173 return fmt.Errorf("First file in the container image collection does not end in .tar")
175 imageID = img[:len(img)-4]
178 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
180 _, err = runner.Docker.InspectImage(imageID)
182 runner.CrunchLog.Print("Loading Docker image from keep")
184 var readCloser io.ReadCloser
185 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
187 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
190 err = runner.Docker.LoadImage(readCloser)
192 return fmt.Errorf("While loading container image into Docker: %v", err)
195 runner.CrunchLog.Print("Docker image is available")
198 runner.ContainerConfig.Image = imageID
203 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
204 c = exec.Command("arv-mount", arvMountCmd...)
206 // Copy our environment, but override ARVADOS_API_TOKEN with
207 // the container auth token.
209 for _, s := range os.Environ() {
210 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
211 c.Env = append(c.Env, s)
214 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
216 nt := NewThrottledLogger(runner.NewLogWriter("arv-mount"))
225 statReadme := make(chan bool)
226 runner.ArvMountExit = make(chan error)
231 time.Sleep(100 * time.Millisecond)
232 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
242 runner.ArvMountExit <- c.Wait()
243 close(runner.ArvMountExit)
249 case err := <-runner.ArvMountExit:
250 runner.ArvMount = nil
258 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
259 if runner.ArvMountPoint == "" {
260 runner.ArvMountPoint, err = runner.MkTempDir("", prefix)
265 func (runner *ContainerRunner) SetupMounts() (err error) {
266 err = runner.SetupArvMountPoint("keep")
268 return fmt.Errorf("While creating keep mount temp dir: %v", err)
271 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.ArvMountPoint)
275 arvMountCmd := []string{"--foreground", "--allow-other", "--read-write"}
277 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
278 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
281 collectionPaths := []string{}
283 needCertMount := true
286 for bind, _ := range runner.Container.Mounts {
287 binds = append(binds, bind)
291 for _, bind := range binds {
292 mnt := runner.Container.Mounts[bind]
293 if bind == "stdout" {
294 // Is it a "file" mount kind?
295 if mnt.Kind != "file" {
296 return fmt.Errorf("Unsupported mount kind '%s' for stdout. Only 'file' is supported.", mnt.Kind)
299 // Does path start with OutputPath?
300 prefix := runner.Container.OutputPath
301 if !strings.HasSuffix(prefix, "/") {
304 if !strings.HasPrefix(mnt.Path, prefix) {
305 return fmt.Errorf("Stdout path does not start with OutputPath: %s, %s", mnt.Path, prefix)
309 if bind == "/etc/arvados/ca-certificates.crt" {
310 needCertMount = false
313 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
314 if mnt.Kind != "collection" {
315 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
320 case mnt.Kind == "collection":
322 if mnt.UUID != "" && mnt.PortableDataHash != "" {
323 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
327 return fmt.Errorf("Writing to existing collections currently not permitted.")
330 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
331 } else if mnt.PortableDataHash != "" {
333 return fmt.Errorf("Can never write to a collection specified by portable data hash")
335 idx := strings.Index(mnt.PortableDataHash, "/")
337 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
338 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
339 runner.Container.Mounts[bind] = mnt
341 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
342 if mnt.Path != "" && mnt.Path != "." {
343 if strings.HasPrefix(mnt.Path, "./") {
344 mnt.Path = mnt.Path[2:]
345 } else if strings.HasPrefix(mnt.Path, "/") {
346 mnt.Path = mnt.Path[1:]
348 src += "/" + mnt.Path
351 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
352 arvMountCmd = append(arvMountCmd, "--mount-tmp")
353 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
357 if bind == runner.Container.OutputPath {
358 runner.HostOutputDir = src
359 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
360 return fmt.Errorf("Writable mount points are not permitted underneath the output_path: %v", bind)
362 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
364 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
366 collectionPaths = append(collectionPaths, src)
368 case mnt.Kind == "tmp" && bind == runner.Container.OutputPath:
369 runner.HostOutputDir, err = runner.MkTempDir("", "")
371 return fmt.Errorf("While creating mount temp dir: %v", err)
373 st, staterr := os.Stat(runner.HostOutputDir)
375 return fmt.Errorf("While Stat on temp dir: %v", staterr)
377 err = os.Chmod(runner.HostOutputDir, st.Mode()|os.ModeSetgid|0777)
379 return fmt.Errorf("While Chmod temp dir: %v", err)
381 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.HostOutputDir)
382 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", runner.HostOutputDir, bind))
384 case mnt.Kind == "tmp":
385 runner.Binds = append(runner.Binds, bind)
387 case mnt.Kind == "json":
388 jsondata, err := json.Marshal(mnt.Content)
390 return fmt.Errorf("encoding json data: %v", err)
392 // Create a tempdir with a single file
393 // (instead of just a tempfile): this way we
394 // can ensure the file is world-readable
395 // inside the container, without having to
396 // make it world-readable on the docker host.
397 tmpdir, err := runner.MkTempDir("", "")
399 return fmt.Errorf("creating temp dir: %v", err)
401 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
402 tmpfn := filepath.Join(tmpdir, "mountdata.json")
403 err = ioutil.WriteFile(tmpfn, jsondata, 0644)
405 return fmt.Errorf("writing temp file: %v", err)
407 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
411 if runner.HostOutputDir == "" {
412 return fmt.Errorf("Output path does not correspond to a writable mount point")
415 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
416 for _, certfile := range arvadosclient.CertFiles {
417 _, err := os.Stat(certfile)
419 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
426 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
428 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
430 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
432 token, err := runner.ContainerToken()
434 return fmt.Errorf("could not get container token: %s", err)
437 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
439 return fmt.Errorf("While trying to start arv-mount: %v", err)
442 for _, p := range collectionPaths {
445 return fmt.Errorf("While checking that input files exist: %v", err)
452 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
453 // Handle docker log protocol
454 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
456 header := make([]byte, 8)
458 _, readerr := io.ReadAtLeast(containerReader, header, 8)
461 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
464 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
467 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
472 if readerr != io.EOF {
473 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
476 closeerr := runner.Stdout.Close()
478 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
481 closeerr = runner.Stderr.Close()
483 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
486 if runner.statReporter != nil {
487 runner.statReporter.Stop()
488 closeerr = runner.statLogger.Close()
490 runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
494 runner.loggingDone <- true
495 close(runner.loggingDone)
501 func (runner *ContainerRunner) StartCrunchstat() {
502 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
503 runner.statReporter = &crunchstat.Reporter{
504 CID: runner.ContainerID,
505 Logger: log.New(runner.statLogger, "", 0),
506 CgroupParent: runner.expectCgroupParent,
507 CgroupRoot: runner.cgroupRoot,
508 PollPeriod: runner.statInterval,
510 runner.statReporter.Start()
513 type infoCommand struct {
518 // Gather node information and store it on the log for debugging
520 func (runner *ContainerRunner) LogNodeInfo() (err error) {
521 w := runner.NewLogWriter("node-info")
522 logger := log.New(w, "node-info", 0)
524 commands := []infoCommand{
526 label: "Host Information",
527 cmd: []string{"uname", "-a"},
530 label: "CPU Information",
531 cmd: []string{"cat", "/proc/cpuinfo"},
534 label: "Memory Information",
535 cmd: []string{"cat", "/proc/meminfo"},
539 cmd: []string{"df", "-m", "/", os.TempDir()},
542 label: "Disk INodes",
543 cmd: []string{"df", "-i", "/", os.TempDir()},
547 // Run commands with informational output to be logged.
549 for _, command := range commands {
550 out, err = exec.Command(command.cmd[0], command.cmd[1:]...).CombinedOutput()
552 return fmt.Errorf("While running command %q: %v",
555 logger.Println(command.label)
556 for _, line := range strings.Split(string(out), "\n") {
557 logger.Println(" ", line)
563 return fmt.Errorf("While closing node-info logs: %v", err)
568 // Get and save the raw JSON container record from the API server
569 func (runner *ContainerRunner) LogContainerRecord() (err error) {
572 runner.Container.UUID,
574 runner.LogCollection.Open("container.json"),
576 // Get Container record JSON from the API Server
577 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
579 return fmt.Errorf("While retrieving container record from the API server: %v", err)
582 // Read the API server response as []byte
583 json_bytes, err := ioutil.ReadAll(reader)
585 return fmt.Errorf("While reading container record API server response: %v", err)
587 // Decode the JSON []byte
588 var cr map[string]interface{}
589 if err = json.Unmarshal(json_bytes, &cr); err != nil {
590 return fmt.Errorf("While decoding the container record JSON response: %v", err)
592 // Re-encode it using indentation to improve readability
593 enc := json.NewEncoder(w)
594 enc.SetIndent("", " ")
595 if err = enc.Encode(cr); err != nil {
596 return fmt.Errorf("While logging the JSON container record: %v", err)
600 return fmt.Errorf("While closing container.json log: %v", err)
605 // AttachLogs connects the docker container stdout and stderr logs to the
606 // Arvados logger which logs to Keep and the API server logs table.
607 func (runner *ContainerRunner) AttachStreams() (err error) {
609 runner.CrunchLog.Print("Attaching container streams")
611 var containerReader io.Reader
612 containerReader, err = runner.Docker.AttachContainer(runner.ContainerID,
613 &dockerclient.AttachOptions{Stream: true, Stdout: true, Stderr: true})
615 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
618 runner.loggingDone = make(chan bool)
620 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
621 stdoutPath := stdoutMnt.Path[len(runner.Container.OutputPath):]
622 index := strings.LastIndex(stdoutPath, "/")
624 subdirs := stdoutPath[:index]
626 st, err := os.Stat(runner.HostOutputDir)
628 return fmt.Errorf("While Stat on temp dir: %v", err)
630 stdoutPath := path.Join(runner.HostOutputDir, subdirs)
631 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
633 return fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
637 stdoutFile, err := os.Create(path.Join(runner.HostOutputDir, stdoutPath))
639 return fmt.Errorf("While creating stdout file: %v", err)
641 runner.Stdout = stdoutFile
643 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
645 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
647 go runner.ProcessDockerAttach(containerReader)
652 // CreateContainer creates the docker container.
653 func (runner *ContainerRunner) CreateContainer() error {
654 runner.CrunchLog.Print("Creating Docker container")
656 runner.ContainerConfig.Cmd = runner.Container.Command
657 if runner.Container.Cwd != "." {
658 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
661 for k, v := range runner.Container.Environment {
662 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
665 runner.HostConfig = dockerclient.HostConfig{
667 CgroupParent: runner.setCgroupParent,
668 LogConfig: dockerclient.LogConfig{
673 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
674 tok, err := runner.ContainerToken()
678 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
679 "ARVADOS_API_TOKEN="+tok,
680 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
681 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
683 runner.HostConfig.NetworkMode = runner.networkMode
685 if runner.enableNetwork == "always" {
686 runner.HostConfig.NetworkMode = runner.networkMode
688 runner.HostConfig.NetworkMode = "none"
693 runner.ContainerID, err = runner.Docker.CreateContainer(&runner.ContainerConfig, "", nil)
695 return fmt.Errorf("While creating container: %v", err)
698 return runner.AttachStreams()
701 // StartContainer starts the docker container created by CreateContainer.
702 func (runner *ContainerRunner) StartContainer() error {
703 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
704 runner.cStateLock.Lock()
705 defer runner.cStateLock.Unlock()
706 if runner.cCancelled {
709 err := runner.Docker.StartContainer(runner.ContainerID, &runner.HostConfig)
711 return fmt.Errorf("could not start container: %v", err)
713 runner.cStarted = true
717 // WaitFinish waits for the container to terminate, capture the exit code, and
718 // close the stdout/stderr logging.
719 func (runner *ContainerRunner) WaitFinish() error {
720 runner.CrunchLog.Print("Waiting for container to finish")
722 waitDocker := runner.Docker.Wait(runner.ContainerID)
723 waitMount := runner.ArvMountExit
724 for waitDocker != nil {
726 case err := <-waitMount:
727 runner.CrunchLog.Printf("arv-mount exited before container finished: %v", err)
730 case wr := <-waitDocker:
732 return fmt.Errorf("While waiting for container to finish: %v", wr.Error)
734 runner.ExitCode = &wr.ExitCode
739 // wait for stdout/stderr to complete
745 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
746 func (runner *ContainerRunner) CaptureOutput() error {
747 if runner.finalState != "Complete" {
751 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
752 // Output may have been set directly by the container, so
753 // refresh the container record to check.
754 err := runner.ArvClient.Get("containers", runner.Container.UUID,
755 nil, &runner.Container)
759 if runner.Container.Output != "" {
760 // Container output is already set.
761 runner.OutputPDH = &runner.Container.Output
766 if runner.HostOutputDir == "" {
770 _, err := os.Stat(runner.HostOutputDir)
772 return fmt.Errorf("While checking host output path: %v", err)
775 var manifestText string
777 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
778 _, err = os.Stat(collectionMetafile)
781 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
782 manifestText, err = cw.WriteTree(runner.HostOutputDir, runner.CrunchLog.Logger)
784 return fmt.Errorf("While uploading output files: %v", err)
787 // FUSE mount directory
788 file, openerr := os.Open(collectionMetafile)
790 return fmt.Errorf("While opening FUSE metafile: %v", err)
794 var rec arvados.Collection
795 err = json.NewDecoder(file).Decode(&rec)
797 return fmt.Errorf("While reading FUSE metafile: %v", err)
799 manifestText = rec.ManifestText
802 // Pre-populate output from the configured mount points
804 for bind, _ := range runner.Container.Mounts {
805 binds = append(binds, bind)
809 for _, bind := range binds {
810 mnt := runner.Container.Mounts[bind]
812 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
814 if bindSuffix == bind || len(bindSuffix) <= 0 {
815 // either does not start with OutputPath or is OutputPath itself
819 if mnt.ExcludeFromOutput == true {
823 // append to manifest_text
824 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
829 manifestText = manifestText + m
833 var response arvados.Collection
834 manifest := manifest.Manifest{Text: manifestText}
835 manifestText = manifest.Extract(".", ".").Text
836 err = runner.ArvClient.Create("collections",
838 "ensure_unique_name": true,
839 "collection": arvadosclient.Dict{
841 "name": "output for " + runner.Container.UUID,
842 "manifest_text": manifestText}},
845 return fmt.Errorf("While creating output collection: %v", err)
847 runner.OutputPDH = &response.PortableDataHash
851 var outputCollections = make(map[string]arvados.Collection)
853 // Fetch the collection for the mnt.PortableDataHash
854 // Return the manifest_text fragment corresponding to the specified mnt.Path
855 // after making any required updates.
857 // If mnt.Path is not specified,
858 // return the entire manifest_text after replacing any "." with bindSuffix
859 // If mnt.Path corresponds to one stream,
860 // return the manifest_text for that stream after replacing that stream name with bindSuffix
861 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
862 // for that stream after replacing stream name with bindSuffix minus the last word
863 // and the file name with last word of the bindSuffix
864 // Allowed path examples:
867 // "path":"/subdir1/subdir2"
868 // "path":"/subdir/filename" etc
869 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
870 collection := outputCollections[mnt.PortableDataHash]
871 if collection.PortableDataHash == "" {
872 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
874 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
876 outputCollections[mnt.PortableDataHash] = collection
879 if collection.ManifestText == "" {
880 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
884 mft := manifest.Manifest{Text: collection.ManifestText}
885 extracted := mft.Extract(mnt.Path, bindSuffix)
886 if extracted.Err != nil {
887 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
889 return extracted.Text, nil
892 func (runner *ContainerRunner) CleanupDirs() {
893 if runner.ArvMount != nil {
894 umount := exec.Command("fusermount", "-z", "-u", runner.ArvMountPoint)
895 umnterr := umount.Run()
897 runner.CrunchLog.Printf("While running fusermount: %v", umnterr)
900 mnterr := <-runner.ArvMountExit
902 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
906 for _, tmpdir := range runner.CleanupTempDir {
907 rmerr := os.RemoveAll(tmpdir)
909 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
914 // CommitLogs posts the collection containing the final container logs.
915 func (runner *ContainerRunner) CommitLogs() error {
916 runner.CrunchLog.Print(runner.finalState)
917 runner.CrunchLog.Close()
919 // Closing CrunchLog above allows it to be committed to Keep at this
920 // point, but re-open crunch log with ArvClient in case there are any
921 // other further (such as failing to write the log to Keep!) while
923 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{runner.ArvClient, runner.Container.UUID,
926 if runner.LogsPDH != nil {
927 // If we have already assigned something to LogsPDH,
928 // we must be closing the re-opened log, which won't
929 // end up getting attached to the container record and
930 // therefore doesn't need to be saved as a collection
931 // -- it exists only to send logs to other channels.
935 mt, err := runner.LogCollection.ManifestText()
937 return fmt.Errorf("While creating log manifest: %v", err)
940 var response arvados.Collection
941 err = runner.ArvClient.Create("collections",
943 "ensure_unique_name": true,
944 "collection": arvadosclient.Dict{
946 "name": "logs for " + runner.Container.UUID,
947 "manifest_text": mt}},
950 return fmt.Errorf("While creating log collection: %v", err)
952 runner.LogsPDH = &response.PortableDataHash
956 // UpdateContainerRunning updates the container state to "Running"
957 func (runner *ContainerRunner) UpdateContainerRunning() error {
958 runner.cStateLock.Lock()
959 defer runner.cStateLock.Unlock()
960 if runner.cCancelled {
963 return runner.ArvClient.Update("containers", runner.Container.UUID,
964 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
967 // ContainerToken returns the api_token the container (and any
968 // arv-mount processes) are allowed to use.
969 func (runner *ContainerRunner) ContainerToken() (string, error) {
970 if runner.token != "" {
971 return runner.token, nil
974 var auth arvados.APIClientAuthorization
975 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
979 runner.token = auth.APIToken
980 return runner.token, nil
983 // UpdateContainerComplete updates the container record state on API
984 // server to "Complete" or "Cancelled"
985 func (runner *ContainerRunner) UpdateContainerFinal() error {
986 update := arvadosclient.Dict{}
987 update["state"] = runner.finalState
988 if runner.LogsPDH != nil {
989 update["log"] = *runner.LogsPDH
991 if runner.finalState == "Complete" {
992 if runner.ExitCode != nil {
993 update["exit_code"] = *runner.ExitCode
995 if runner.OutputPDH != nil {
996 update["output"] = *runner.OutputPDH
999 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1002 // IsCancelled returns the value of Cancelled, with goroutine safety.
1003 func (runner *ContainerRunner) IsCancelled() bool {
1004 runner.cStateLock.Lock()
1005 defer runner.cStateLock.Unlock()
1006 return runner.cCancelled
1009 // NewArvLogWriter creates an ArvLogWriter
1010 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1011 return &ArvLogWriter{runner.ArvClient, runner.Container.UUID, name, runner.LogCollection.Open(name + ".txt")}
1014 // Run the full container lifecycle.
1015 func (runner *ContainerRunner) Run() (err error) {
1016 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1018 hostname, hosterr := os.Hostname()
1020 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1022 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1025 // Clean up temporary directories _after_ finalizing
1026 // everything (if we've made any by then)
1027 defer runner.CleanupDirs()
1029 runner.finalState = "Queued"
1032 // checkErr prints e (unless it's nil) and sets err to
1033 // e (unless err is already non-nil). Thus, if err
1034 // hasn't already been assigned when Run() returns,
1035 // this cleanup func will cause Run() to return the
1036 // first non-nil error that is passed to checkErr().
1037 checkErr := func(e error) {
1041 runner.CrunchLog.Print(e)
1047 // Log the error encountered in Run(), if any
1050 if runner.finalState == "Queued" {
1051 runner.CrunchLog.Close()
1052 runner.UpdateContainerFinal()
1056 if runner.IsCancelled() {
1057 runner.finalState = "Cancelled"
1058 // but don't return yet -- we still want to
1059 // capture partial output and write logs
1062 checkErr(runner.CaptureOutput())
1063 checkErr(runner.CommitLogs())
1064 checkErr(runner.UpdateContainerFinal())
1066 // The real log is already closed, but then we opened
1067 // a new one in case we needed to log anything while
1069 runner.CrunchLog.Close()
1072 err = runner.ArvClient.Get("containers", runner.Container.UUID, nil, &runner.Container)
1074 err = fmt.Errorf("While getting container record: %v", err)
1078 // setup signal handling
1079 runner.SetupSignals()
1081 // check for and/or load image
1082 err = runner.LoadImage()
1084 runner.finalState = "Cancelled"
1085 err = fmt.Errorf("While loading container image: %v", err)
1089 // set up FUSE mount and binds
1090 err = runner.SetupMounts()
1092 runner.finalState = "Cancelled"
1093 err = fmt.Errorf("While setting up mounts: %v", err)
1097 err = runner.CreateContainer()
1102 // Gather and record node information
1103 err = runner.LogNodeInfo()
1107 // Save container.json record on log collection
1108 err = runner.LogContainerRecord()
1113 runner.StartCrunchstat()
1115 if runner.IsCancelled() {
1119 err = runner.UpdateContainerRunning()
1123 runner.finalState = "Cancelled"
1125 err = runner.StartContainer()
1130 err = runner.WaitFinish()
1132 runner.finalState = "Complete"
1137 // NewContainerRunner creates a new container runner.
1138 func NewContainerRunner(api IArvadosClient,
1140 docker ThinDockerClient,
1141 containerUUID string) *ContainerRunner {
1143 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1144 cr.NewLogWriter = cr.NewArvLogWriter
1145 cr.RunArvMount = cr.ArvMountCmd
1146 cr.MkTempDir = ioutil.TempDir
1147 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1148 cr.Container.UUID = containerUUID
1149 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1150 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1155 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1156 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1157 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1158 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1159 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1160 enableNetwork := flag.String("container-enable-networking", "default",
1161 `Specify if networking should be enabled for container. One of 'default', 'always':
1162 default: only enable networking if container requests it.
1163 always: containers always have networking enabled
1165 networkMode := flag.String("container-network-mode", "default",
1166 `Set networking mode for container. Corresponds to Docker network mode (--net).
1170 containerId := flag.Arg(0)
1172 if *caCertsPath != "" {
1173 arvadosclient.CertFiles = []string{*caCertsPath}
1176 api, err := arvadosclient.MakeArvadosClient()
1178 log.Fatalf("%s: %v", containerId, err)
1182 var kc *keepclient.KeepClient
1183 kc, err = keepclient.MakeKeepClient(api)
1185 log.Fatalf("%s: %v", containerId, err)
1189 var docker *dockerclient.DockerClient
1190 docker, err = dockerclient.NewDockerClient("unix:///var/run/docker.sock", nil)
1192 log.Fatalf("%s: %v", containerId, err)
1195 cr := NewContainerRunner(api, kc, docker, containerId)
1196 cr.statInterval = *statInterval
1197 cr.cgroupRoot = *cgroupRoot
1198 cr.expectCgroupParent = *cgroupParent
1199 cr.enableNetwork = *enableNetwork
1200 cr.networkMode = *networkMode
1201 if *cgroupParentSubsystem != "" {
1202 p := findCgroup(*cgroupParentSubsystem)
1203 cr.setCgroupParent = p
1204 cr.expectCgroupParent = p
1209 log.Fatalf("%s: %v", containerId, err)