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
96 SigChan chan os.Signal
97 ArvMountExit chan error
100 statLogger io.WriteCloser
101 statReporter *crunchstat.Reporter
102 statInterval time.Duration
104 // What we expect the container's cgroup parent to be.
105 expectCgroupParent string
106 // What we tell docker to use as the container's cgroup
107 // parent. Note: Ideally we would use the same field for both
108 // expectCgroupParent and setCgroupParent, and just make it
109 // default to "docker". However, when using docker < 1.10 with
110 // systemd, specifying a non-empty cgroup parent (even the
111 // default value "docker") hits a docker bug
112 // (https://github.com/docker/docker/issues/17126). Using two
113 // separate fields makes it possible to use the "expect cgroup
114 // parent to be X" feature even on sites where the "specify
115 // cgroup parent" feature breaks.
116 setCgroupParent string
119 // SetupSignals sets up signal handling to gracefully terminate the underlying
120 // Docker container and update state when receiving a TERM, INT or QUIT signal.
121 func (runner *ContainerRunner) SetupSignals() {
122 runner.SigChan = make(chan os.Signal, 1)
123 signal.Notify(runner.SigChan, syscall.SIGTERM)
124 signal.Notify(runner.SigChan, syscall.SIGINT)
125 signal.Notify(runner.SigChan, syscall.SIGQUIT)
127 go func(sig chan os.Signal) {
134 // stop the underlying Docker container.
135 func (runner *ContainerRunner) stop() {
136 runner.CancelLock.Lock()
137 defer runner.CancelLock.Unlock()
138 if runner.Cancelled {
141 runner.Cancelled = true
142 if runner.ContainerID != "" {
143 err := runner.Docker.StopContainer(runner.ContainerID, 10)
145 log.Printf("StopContainer failed: %s", err)
150 // LoadImage determines the docker image id from the container record and
151 // checks if it is available in the local Docker image store. If not, it loads
152 // the image from Keep.
153 func (runner *ContainerRunner) LoadImage() (err error) {
155 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
157 var collection arvados.Collection
158 err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
160 return fmt.Errorf("While getting container image collection: %v", err)
162 manifest := manifest.Manifest{Text: collection.ManifestText}
163 var img, imageID string
164 for ms := range manifest.StreamIter() {
165 img = ms.FileStreamSegments[0].Name
166 if !strings.HasSuffix(img, ".tar") {
167 return fmt.Errorf("First file in the container image collection does not end in .tar")
169 imageID = img[:len(img)-4]
172 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
174 _, err = runner.Docker.InspectImage(imageID)
176 runner.CrunchLog.Print("Loading Docker image from keep")
178 var readCloser io.ReadCloser
179 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
181 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
184 err = runner.Docker.LoadImage(readCloser)
186 return fmt.Errorf("While loading container image into Docker: %v", err)
189 runner.CrunchLog.Print("Docker image is available")
192 runner.ContainerConfig.Image = imageID
197 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
198 c = exec.Command("arv-mount", arvMountCmd...)
200 // Copy our environment, but override ARVADOS_API_TOKEN with
201 // the container auth token.
203 for _, s := range os.Environ() {
204 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
205 c.Env = append(c.Env, s)
208 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
210 nt := NewThrottledLogger(runner.NewLogWriter("arv-mount"))
219 statReadme := make(chan bool)
220 runner.ArvMountExit = make(chan error)
225 time.Sleep(100 * time.Millisecond)
226 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
236 runner.ArvMountExit <- c.Wait()
237 close(runner.ArvMountExit)
243 case err := <-runner.ArvMountExit:
244 runner.ArvMount = nil
252 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
253 if runner.ArvMountPoint == "" {
254 runner.ArvMountPoint, err = runner.MkTempDir("", prefix)
259 func (runner *ContainerRunner) SetupMounts() (err error) {
260 err = runner.SetupArvMountPoint("keep")
262 return fmt.Errorf("While creating keep mount temp dir: %v", err)
265 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.ArvMountPoint)
269 arvMountCmd := []string{"--foreground", "--allow-other", "--read-write"}
271 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
272 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
275 collectionPaths := []string{}
277 needCertMount := true
280 for bind, _ := range runner.Container.Mounts {
281 binds = append(binds, bind)
285 for _, bind := range binds {
286 mnt := runner.Container.Mounts[bind]
287 if bind == "stdout" {
288 // Is it a "file" mount kind?
289 if mnt.Kind != "file" {
290 return fmt.Errorf("Unsupported mount kind '%s' for stdout. Only 'file' is supported.", mnt.Kind)
293 // Does path start with OutputPath?
294 prefix := runner.Container.OutputPath
295 if !strings.HasSuffix(prefix, "/") {
298 if !strings.HasPrefix(mnt.Path, prefix) {
299 return fmt.Errorf("Stdout path does not start with OutputPath: %s, %s", mnt.Path, prefix)
303 if bind == "/etc/arvados/ca-certificates.crt" {
304 needCertMount = false
307 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
308 if mnt.Kind != "collection" {
309 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
314 case mnt.Kind == "collection":
316 if mnt.UUID != "" && mnt.PortableDataHash != "" {
317 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
321 return fmt.Errorf("Writing to existing collections currently not permitted.")
324 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
325 } else if mnt.PortableDataHash != "" {
327 return fmt.Errorf("Can never write to a collection specified by portable data hash")
329 idx := strings.Index(mnt.PortableDataHash, "/")
331 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
332 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
333 runner.Container.Mounts[bind] = mnt
335 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
336 if mnt.Path != "" && mnt.Path != "." {
337 if strings.HasPrefix(mnt.Path, "./") {
338 mnt.Path = mnt.Path[2:]
339 } else if strings.HasPrefix(mnt.Path, "/") {
340 mnt.Path = mnt.Path[1:]
342 src += "/" + mnt.Path
345 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
346 arvMountCmd = append(arvMountCmd, "--mount-tmp")
347 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
351 if bind == runner.Container.OutputPath {
352 runner.HostOutputDir = src
353 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
354 return fmt.Errorf("Writable mount points are not permitted underneath the output_path: %v", bind)
356 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
358 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
360 collectionPaths = append(collectionPaths, src)
362 case mnt.Kind == "tmp" && bind == runner.Container.OutputPath:
363 runner.HostOutputDir, err = runner.MkTempDir("", "")
365 return fmt.Errorf("While creating mount temp dir: %v", err)
367 st, staterr := os.Stat(runner.HostOutputDir)
369 return fmt.Errorf("While Stat on temp dir: %v", staterr)
371 err = os.Chmod(runner.HostOutputDir, st.Mode()|os.ModeSetgid|0777)
373 return fmt.Errorf("While Chmod temp dir: %v", err)
375 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.HostOutputDir)
376 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", runner.HostOutputDir, bind))
378 case mnt.Kind == "tmp":
379 runner.Binds = append(runner.Binds, bind)
381 case mnt.Kind == "json":
382 jsondata, err := json.Marshal(mnt.Content)
384 return fmt.Errorf("encoding json data: %v", err)
386 // Create a tempdir with a single file
387 // (instead of just a tempfile): this way we
388 // can ensure the file is world-readable
389 // inside the container, without having to
390 // make it world-readable on the docker host.
391 tmpdir, err := runner.MkTempDir("", "")
393 return fmt.Errorf("creating temp dir: %v", err)
395 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
396 tmpfn := filepath.Join(tmpdir, "mountdata.json")
397 err = ioutil.WriteFile(tmpfn, jsondata, 0644)
399 return fmt.Errorf("writing temp file: %v", err)
401 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
405 if runner.HostOutputDir == "" {
406 return fmt.Errorf("Output path does not correspond to a writable mount point")
409 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
410 for _, certfile := range arvadosclient.CertFiles {
411 _, err := os.Stat(certfile)
413 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
420 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
422 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
424 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
426 token, err := runner.ContainerToken()
428 return fmt.Errorf("could not get container token: %s", err)
431 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
433 return fmt.Errorf("While trying to start arv-mount: %v", err)
436 for _, p := range collectionPaths {
439 return fmt.Errorf("While checking that input files exist: %v", err)
446 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
447 // Handle docker log protocol
448 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
450 header := make([]byte, 8)
452 _, readerr := io.ReadAtLeast(containerReader, header, 8)
455 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
458 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
461 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
466 if readerr != io.EOF {
467 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
470 closeerr := runner.Stdout.Close()
472 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
475 closeerr = runner.Stderr.Close()
477 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
480 if runner.statReporter != nil {
481 runner.statReporter.Stop()
482 closeerr = runner.statLogger.Close()
484 runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
488 runner.loggingDone <- true
489 close(runner.loggingDone)
495 func (runner *ContainerRunner) StartCrunchstat() {
496 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
497 runner.statReporter = &crunchstat.Reporter{
498 CID: runner.ContainerID,
499 Logger: log.New(runner.statLogger, "", 0),
500 CgroupParent: runner.expectCgroupParent,
501 CgroupRoot: runner.cgroupRoot,
502 PollPeriod: runner.statInterval,
504 runner.statReporter.Start()
507 // AttachLogs connects the docker container stdout and stderr logs to the
508 // Arvados logger which logs to Keep and the API server logs table.
509 func (runner *ContainerRunner) AttachStreams() (err error) {
511 runner.CrunchLog.Print("Attaching container streams")
513 var containerReader io.Reader
514 containerReader, err = runner.Docker.AttachContainer(runner.ContainerID,
515 &dockerclient.AttachOptions{Stream: true, Stdout: true, Stderr: true})
517 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
520 runner.loggingDone = make(chan bool)
522 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
523 stdoutPath := stdoutMnt.Path[len(runner.Container.OutputPath):]
524 index := strings.LastIndex(stdoutPath, "/")
526 subdirs := stdoutPath[:index]
528 st, err := os.Stat(runner.HostOutputDir)
530 return fmt.Errorf("While Stat on temp dir: %v", err)
532 stdoutPath := path.Join(runner.HostOutputDir, subdirs)
533 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
535 return fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
539 stdoutFile, err := os.Create(path.Join(runner.HostOutputDir, stdoutPath))
541 return fmt.Errorf("While creating stdout file: %v", err)
543 runner.Stdout = stdoutFile
545 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
547 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
549 go runner.ProcessDockerAttach(containerReader)
554 // CreateContainer creates the docker container.
555 func (runner *ContainerRunner) CreateContainer() error {
556 runner.CrunchLog.Print("Creating Docker container")
558 runner.ContainerConfig.Cmd = runner.Container.Command
559 if runner.Container.Cwd != "." {
560 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
563 for k, v := range runner.Container.Environment {
564 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
566 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
567 tok, err := runner.ContainerToken()
571 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
572 "ARVADOS_API_TOKEN="+tok,
573 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
574 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
576 runner.ContainerConfig.NetworkDisabled = false
578 runner.ContainerConfig.NetworkDisabled = true
582 runner.ContainerID, err = runner.Docker.CreateContainer(&runner.ContainerConfig, "", nil)
584 return fmt.Errorf("While creating container: %v", err)
587 runner.HostConfig = dockerclient.HostConfig{
589 CgroupParent: runner.setCgroupParent,
590 LogConfig: dockerclient.LogConfig{
595 return runner.AttachStreams()
598 // StartContainer starts the docker container created by CreateContainer.
599 func (runner *ContainerRunner) StartContainer() error {
600 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
601 err := runner.Docker.StartContainer(runner.ContainerID, &runner.HostConfig)
603 return fmt.Errorf("could not start container: %v", err)
608 // WaitFinish waits for the container to terminate, capture the exit code, and
609 // close the stdout/stderr logging.
610 func (runner *ContainerRunner) WaitFinish() error {
611 runner.CrunchLog.Print("Waiting for container to finish")
613 waitDocker := runner.Docker.Wait(runner.ContainerID)
614 waitMount := runner.ArvMountExit
615 for waitDocker != nil {
617 case err := <-waitMount:
618 runner.CrunchLog.Printf("arv-mount exited before container finished: %v", err)
621 case wr := <-waitDocker:
623 return fmt.Errorf("While waiting for container to finish: %v", wr.Error)
625 runner.ExitCode = &wr.ExitCode
630 // wait for stdout/stderr to complete
636 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
637 func (runner *ContainerRunner) CaptureOutput() error {
638 if runner.finalState != "Complete" {
642 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
643 // Output may have been set directly by the container, so
644 // refresh the container record to check.
645 err := runner.ArvClient.Get("containers", runner.Container.UUID,
646 nil, &runner.Container)
650 if runner.Container.Output != "" {
651 // Container output is already set.
652 runner.OutputPDH = &runner.Container.Output
657 if runner.HostOutputDir == "" {
661 _, err := os.Stat(runner.HostOutputDir)
663 return fmt.Errorf("While checking host output path: %v", err)
666 var manifestText string
668 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
669 _, err = os.Stat(collectionMetafile)
672 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
673 manifestText, err = cw.WriteTree(runner.HostOutputDir, runner.CrunchLog.Logger)
675 return fmt.Errorf("While uploading output files: %v", err)
678 // FUSE mount directory
679 file, openerr := os.Open(collectionMetafile)
681 return fmt.Errorf("While opening FUSE metafile: %v", err)
685 var rec arvados.Collection
686 err = json.NewDecoder(file).Decode(&rec)
688 return fmt.Errorf("While reading FUSE metafile: %v", err)
690 manifestText = rec.ManifestText
693 // Pre-populate output from the configured mount points
695 for bind, _ := range runner.Container.Mounts {
696 binds = append(binds, bind)
700 for _, bind := range binds {
701 mnt := runner.Container.Mounts[bind]
703 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
705 if bindSuffix == bind || len(bindSuffix) <= 0 {
706 // either does not start with OutputPath or is OutputPath itself
710 if mnt.ExcludeFromOutput == true {
714 // append to manifest_text
715 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
720 manifestText = manifestText + m
724 var response arvados.Collection
725 manifest := manifest.Manifest{Text: manifestText}
726 manifestText = manifest.Extract(".", ".").Text
727 err = runner.ArvClient.Create("collections",
729 "ensure_unique_name": true,
730 "collection": arvadosclient.Dict{
732 "name": "output for " + runner.Container.UUID,
733 "manifest_text": manifestText}},
736 return fmt.Errorf("While creating output collection: %v", err)
738 runner.OutputPDH = &response.PortableDataHash
742 var outputCollections = make(map[string]arvados.Collection)
744 // Fetch the collection for the mnt.PortableDataHash
745 // Return the manifest_text fragment corresponding to the specified mnt.Path
746 // after making any required updates.
748 // If mnt.Path is not specified,
749 // return the entire manifest_text after replacing any "." with bindSuffix
750 // If mnt.Path corresponds to one stream,
751 // return the manifest_text for that stream after replacing that stream name with bindSuffix
752 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
753 // for that stream after replacing stream name with bindSuffix minus the last word
754 // and the file name with last word of the bindSuffix
755 // Allowed path examples:
758 // "path":"/subdir1/subdir2"
759 // "path":"/subdir/filename" etc
760 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
761 collection := outputCollections[mnt.PortableDataHash]
762 if collection.PortableDataHash == "" {
763 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
765 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
767 outputCollections[mnt.PortableDataHash] = collection
770 if collection.ManifestText == "" {
771 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
775 mft := manifest.Manifest{Text: collection.ManifestText}
776 extracted := mft.Extract(mnt.Path, bindSuffix)
777 if extracted.Err != nil {
778 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
780 return extracted.Text, nil
783 func (runner *ContainerRunner) CleanupDirs() {
784 if runner.ArvMount != nil {
785 umount := exec.Command("fusermount", "-z", "-u", runner.ArvMountPoint)
786 umnterr := umount.Run()
788 runner.CrunchLog.Printf("While running fusermount: %v", umnterr)
791 mnterr := <-runner.ArvMountExit
793 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
797 for _, tmpdir := range runner.CleanupTempDir {
798 rmerr := os.RemoveAll(tmpdir)
800 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
805 // CommitLogs posts the collection containing the final container logs.
806 func (runner *ContainerRunner) CommitLogs() error {
807 runner.CrunchLog.Print(runner.finalState)
808 runner.CrunchLog.Close()
810 // Closing CrunchLog above allows it to be committed to Keep at this
811 // point, but re-open crunch log with ArvClient in case there are any
812 // other further (such as failing to write the log to Keep!) while
814 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{runner.ArvClient, runner.Container.UUID,
817 if runner.LogsPDH != nil {
818 // If we have already assigned something to LogsPDH,
819 // we must be closing the re-opened log, which won't
820 // end up getting attached to the container record and
821 // therefore doesn't need to be saved as a collection
822 // -- it exists only to send logs to other channels.
826 mt, err := runner.LogCollection.ManifestText()
828 return fmt.Errorf("While creating log manifest: %v", err)
831 var response arvados.Collection
832 err = runner.ArvClient.Create("collections",
834 "ensure_unique_name": true,
835 "collection": arvadosclient.Dict{
837 "name": "logs for " + runner.Container.UUID,
838 "manifest_text": mt}},
841 return fmt.Errorf("While creating log collection: %v", err)
843 runner.LogsPDH = &response.PortableDataHash
847 // UpdateContainerRunning updates the container state to "Running"
848 func (runner *ContainerRunner) UpdateContainerRunning() error {
849 runner.CancelLock.Lock()
850 defer runner.CancelLock.Unlock()
851 if runner.Cancelled {
854 return runner.ArvClient.Update("containers", runner.Container.UUID,
855 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
858 // ContainerToken returns the api_token the container (and any
859 // arv-mount processes) are allowed to use.
860 func (runner *ContainerRunner) ContainerToken() (string, error) {
861 if runner.token != "" {
862 return runner.token, nil
865 var auth arvados.APIClientAuthorization
866 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
870 runner.token = auth.APIToken
871 return runner.token, nil
874 // UpdateContainerComplete updates the container record state on API
875 // server to "Complete" or "Cancelled"
876 func (runner *ContainerRunner) UpdateContainerFinal() error {
877 update := arvadosclient.Dict{}
878 update["state"] = runner.finalState
879 if runner.LogsPDH != nil {
880 update["log"] = *runner.LogsPDH
882 if runner.finalState == "Complete" {
883 if runner.ExitCode != nil {
884 update["exit_code"] = *runner.ExitCode
886 if runner.OutputPDH != nil {
887 update["output"] = *runner.OutputPDH
890 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
893 // IsCancelled returns the value of Cancelled, with goroutine safety.
894 func (runner *ContainerRunner) IsCancelled() bool {
895 runner.CancelLock.Lock()
896 defer runner.CancelLock.Unlock()
897 return runner.Cancelled
900 // NewArvLogWriter creates an ArvLogWriter
901 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
902 return &ArvLogWriter{runner.ArvClient, runner.Container.UUID, name, runner.LogCollection.Open(name + ".txt")}
905 // Run the full container lifecycle.
906 func (runner *ContainerRunner) Run() (err error) {
907 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
909 hostname, hosterr := os.Hostname()
911 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
913 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
916 // Clean up temporary directories _after_ finalizing
917 // everything (if we've made any by then)
918 defer runner.CleanupDirs()
920 runner.finalState = "Queued"
923 // checkErr prints e (unless it's nil) and sets err to
924 // e (unless err is already non-nil). Thus, if err
925 // hasn't already been assigned when Run() returns,
926 // this cleanup func will cause Run() to return the
927 // first non-nil error that is passed to checkErr().
928 checkErr := func(e error) {
932 runner.CrunchLog.Print(e)
938 // Log the error encountered in Run(), if any
941 if runner.finalState == "Queued" {
942 runner.CrunchLog.Close()
943 runner.UpdateContainerFinal()
947 if runner.IsCancelled() {
948 runner.finalState = "Cancelled"
949 // but don't return yet -- we still want to
950 // capture partial output and write logs
953 checkErr(runner.CaptureOutput())
954 checkErr(runner.CommitLogs())
955 checkErr(runner.UpdateContainerFinal())
957 // The real log is already closed, but then we opened
958 // a new one in case we needed to log anything while
960 runner.CrunchLog.Close()
963 err = runner.ArvClient.Get("containers", runner.Container.UUID, nil, &runner.Container)
965 err = fmt.Errorf("While getting container record: %v", err)
969 // setup signal handling
970 runner.SetupSignals()
972 // check for and/or load image
973 err = runner.LoadImage()
975 runner.finalState = "Cancelled"
976 err = fmt.Errorf("While loading container image: %v", err)
980 // set up FUSE mount and binds
981 err = runner.SetupMounts()
983 runner.finalState = "Cancelled"
984 err = fmt.Errorf("While setting up mounts: %v", err)
988 err = runner.CreateContainer()
993 runner.StartCrunchstat()
995 if runner.IsCancelled() {
999 err = runner.UpdateContainerRunning()
1003 runner.finalState = "Cancelled"
1005 err = runner.StartContainer()
1010 err = runner.WaitFinish()
1012 runner.finalState = "Complete"
1017 // NewContainerRunner creates a new container runner.
1018 func NewContainerRunner(api IArvadosClient,
1020 docker ThinDockerClient,
1021 containerUUID string) *ContainerRunner {
1023 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1024 cr.NewLogWriter = cr.NewArvLogWriter
1025 cr.RunArvMount = cr.ArvMountCmd
1026 cr.MkTempDir = ioutil.TempDir
1027 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1028 cr.Container.UUID = containerUUID
1029 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1030 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1035 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1036 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1037 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1038 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1039 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1042 containerId := flag.Arg(0)
1044 if *caCertsPath != "" {
1045 arvadosclient.CertFiles = []string{*caCertsPath}
1048 api, err := arvadosclient.MakeArvadosClient()
1050 log.Fatalf("%s: %v", containerId, err)
1054 var kc *keepclient.KeepClient
1055 kc, err = keepclient.MakeKeepClient(api)
1057 log.Fatalf("%s: %v", containerId, err)
1061 var docker *dockerclient.DockerClient
1062 docker, err = dockerclient.NewDockerClient("unix:///var/run/docker.sock", nil)
1064 log.Fatalf("%s: %v", containerId, err)
1067 cr := NewContainerRunner(api, kc, docker, containerId)
1068 cr.statInterval = *statInterval
1069 cr.cgroupRoot = *cgroupRoot
1070 cr.expectCgroupParent = *cgroupParent
1071 if *cgroupParentSubsystem != "" {
1072 p := findCgroup(*cgroupParentSubsystem)
1073 cr.setCgroupParent = p
1074 cr.expectCgroupParent = p
1079 log.Fatalf("%s: %v", containerId, err)