8 "git.curoverse.com/arvados.git/sdk/go/arvados"
9 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
10 "git.curoverse.com/arvados.git/sdk/go/keepclient"
11 "git.curoverse.com/arvados.git/sdk/go/manifest"
12 "github.com/curoverse/dockerclient"
26 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
27 type IArvadosClient interface {
28 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
29 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
30 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error)
31 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) (err error)
34 // ErrCancelled is the error returned when the container is cancelled.
35 var ErrCancelled = errors.New("Cancelled")
37 // IKeepClient is the minimal Keep API methods used by crunch-run.
38 type IKeepClient interface {
39 PutHB(hash string, buf []byte) (string, int, error)
40 ManifestFileReader(m manifest.Manifest, filename string) (keepclient.ReadCloserWithLen, error)
43 // NewLogWriter is a factory function to create a new log writer.
44 type NewLogWriter func(name string) io.WriteCloser
46 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
48 type MkTempDir func(string, string) (string, error)
50 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
51 type ThinDockerClient interface {
52 StopContainer(id string, timeout int) error
53 InspectImage(id string) (*dockerclient.ImageInfo, error)
54 LoadImage(reader io.Reader) error
55 CreateContainer(config *dockerclient.ContainerConfig, name string, authConfig *dockerclient.AuthConfig) (string, error)
56 StartContainer(id string, config *dockerclient.HostConfig) error
57 AttachContainer(id string, options *dockerclient.AttachOptions) (io.ReadCloser, error)
58 Wait(id string) <-chan dockerclient.WaitResult
59 RemoveImage(name string, force bool) ([]*dockerclient.ImageDelete, error)
62 // ContainerRunner is the main stateful struct used for a single execution of a
64 type ContainerRunner struct {
65 Docker ThinDockerClient
66 ArvClient IArvadosClient
69 dockerclient.ContainerConfig
70 dockerclient.HostConfig
76 CrunchLog *ThrottledLogger
78 Stderr *ThrottledLogger
79 LogCollection *CollectionWriter
86 CleanupTempDir []string
91 SigChan chan os.Signal
92 ArvMountExit chan error
96 // SetupSignals sets up signal handling to gracefully terminate the underlying
97 // Docker container and update state when receiving a TERM, INT or QUIT signal.
98 func (runner *ContainerRunner) SetupSignals() {
99 runner.SigChan = make(chan os.Signal, 1)
100 signal.Notify(runner.SigChan, syscall.SIGTERM)
101 signal.Notify(runner.SigChan, syscall.SIGINT)
102 signal.Notify(runner.SigChan, syscall.SIGQUIT)
104 go func(sig <-chan os.Signal) {
106 if !runner.Cancelled {
107 runner.CancelLock.Lock()
108 runner.Cancelled = true
109 if runner.ContainerID != "" {
110 runner.Docker.StopContainer(runner.ContainerID, 10)
112 runner.CancelLock.Unlock()
118 // LoadImage determines the docker image id from the container record and
119 // checks if it is available in the local Docker image store. If not, it loads
120 // the image from Keep.
121 func (runner *ContainerRunner) LoadImage() (err error) {
123 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
125 var collection arvados.Collection
126 err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
128 return fmt.Errorf("While getting container image collection: %v", err)
130 manifest := manifest.Manifest{Text: collection.ManifestText}
131 var img, imageID string
132 for ms := range manifest.StreamIter() {
133 img = ms.FileStreamSegments[0].Name
134 if !strings.HasSuffix(img, ".tar") {
135 return fmt.Errorf("First file in the container image collection does not end in .tar")
137 imageID = img[:len(img)-4]
140 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
142 _, err = runner.Docker.InspectImage(imageID)
144 runner.CrunchLog.Print("Loading Docker image from keep")
146 var readCloser io.ReadCloser
147 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
149 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
152 err = runner.Docker.LoadImage(readCloser)
154 return fmt.Errorf("While loading container image into Docker: %v", err)
157 runner.CrunchLog.Print("Docker image is available")
160 runner.ContainerConfig.Image = imageID
165 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
166 c = exec.Command("arv-mount", arvMountCmd...)
168 // Copy our environment, but override ARVADOS_API_TOKEN with
169 // the container auth token.
171 for _, s := range os.Environ() {
172 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
173 c.Env = append(c.Env, s)
176 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
178 nt := NewThrottledLogger(runner.NewLogWriter("arv-mount"))
187 statReadme := make(chan bool)
188 runner.ArvMountExit = make(chan error)
193 time.Sleep(100 * time.Millisecond)
194 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
204 runner.ArvMountExit <- c.Wait()
205 close(runner.ArvMountExit)
211 case err := <-runner.ArvMountExit:
212 runner.ArvMount = nil
220 func (runner *ContainerRunner) SetupMounts() (err error) {
221 runner.ArvMountPoint, err = runner.MkTempDir("", "keep")
223 return fmt.Errorf("While creating keep mount temp dir: %v", err)
226 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.ArvMountPoint)
230 arvMountCmd := []string{"--foreground", "--allow-other", "--read-write"}
231 collectionPaths := []string{}
234 for bind, mnt := range runner.Container.Mounts {
235 if bind == "stdout" {
236 // Is it a "file" mount kind?
237 if mnt.Kind != "file" {
238 return fmt.Errorf("Unsupported mount kind '%s' for stdout. Only 'file' is supported.", mnt.Kind)
241 // Does path start with OutputPath?
242 prefix := runner.Container.OutputPath
243 if !strings.HasSuffix(prefix, "/") {
246 if !strings.HasPrefix(mnt.Path, prefix) {
247 return fmt.Errorf("Stdout path does not start with OutputPath: %s, %s", mnt.Path, prefix)
251 if mnt.Kind == "collection" {
253 if mnt.UUID != "" && mnt.PortableDataHash != "" {
254 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
258 return fmt.Errorf("Writing to existing collections currently not permitted.")
261 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
262 } else if mnt.PortableDataHash != "" {
264 return fmt.Errorf("Can never write to a collection specified by portable data hash")
266 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
268 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
269 arvMountCmd = append(arvMountCmd, "--mount-tmp")
270 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
274 if bind == runner.Container.OutputPath {
275 runner.HostOutputDir = src
277 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
279 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
281 collectionPaths = append(collectionPaths, src)
282 } else if mnt.Kind == "tmp" {
283 if bind == runner.Container.OutputPath {
284 runner.HostOutputDir, err = runner.MkTempDir("", "")
286 return fmt.Errorf("While creating mount temp dir: %v", err)
288 st, staterr := os.Stat(runner.HostOutputDir)
290 return fmt.Errorf("While Stat on temp dir: %v", staterr)
292 err = os.Chmod(runner.HostOutputDir, st.Mode()|os.ModeSetgid|0777)
294 return fmt.Errorf("While Chmod temp dir: %v", err)
296 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.HostOutputDir)
297 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", runner.HostOutputDir, bind))
299 runner.Binds = append(runner.Binds, bind)
304 if runner.HostOutputDir == "" {
305 return fmt.Errorf("Output path does not correspond to a writable mount point")
309 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
311 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
313 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
315 token, err := runner.ContainerToken()
317 return fmt.Errorf("could not get container token: %s", err)
320 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
322 return fmt.Errorf("While trying to start arv-mount: %v", err)
325 for _, p := range collectionPaths {
328 return fmt.Errorf("While checking that input files exist: %v", err)
335 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
336 // Handle docker log protocol
337 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
339 header := make([]byte, 8)
341 _, readerr := io.ReadAtLeast(containerReader, header, 8)
344 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
347 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
350 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
355 if readerr != io.EOF {
356 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
359 closeerr := runner.Stdout.Close()
361 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
364 closeerr = runner.Stderr.Close()
366 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
369 runner.loggingDone <- true
370 close(runner.loggingDone)
376 // AttachLogs connects the docker container stdout and stderr logs to the
377 // Arvados logger which logs to Keep and the API server logs table.
378 func (runner *ContainerRunner) AttachStreams() (err error) {
380 runner.CrunchLog.Print("Attaching container streams")
382 var containerReader io.Reader
383 containerReader, err = runner.Docker.AttachContainer(runner.ContainerID,
384 &dockerclient.AttachOptions{Stream: true, Stdout: true, Stderr: true})
386 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
389 runner.loggingDone = make(chan bool)
391 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
392 stdoutPath := stdoutMnt.Path[len(runner.Container.OutputPath):]
393 index := strings.LastIndex(stdoutPath, "/")
395 subdirs := stdoutPath[:index]
397 st, err := os.Stat(runner.HostOutputDir)
399 return fmt.Errorf("While Stat on temp dir: %v", err)
401 stdoutPath := path.Join(runner.HostOutputDir, subdirs)
402 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
404 return fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
408 stdoutFile, err := os.Create(path.Join(runner.HostOutputDir, stdoutPath))
410 return fmt.Errorf("While creating stdout file: %v", err)
412 runner.Stdout = stdoutFile
414 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
416 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
418 go runner.ProcessDockerAttach(containerReader)
423 // CreateContainer creates the docker container.
424 func (runner *ContainerRunner) CreateContainer() error {
425 runner.CrunchLog.Print("Creating Docker container")
427 runner.ContainerConfig.Cmd = runner.Container.Command
428 if runner.Container.Cwd != "." {
429 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
432 for k, v := range runner.Container.Environment {
433 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
435 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
436 tok, err := runner.ContainerToken()
440 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
441 "ARVADOS_API_TOKEN="+tok,
442 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
443 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
445 runner.ContainerConfig.NetworkDisabled = false
447 runner.ContainerConfig.NetworkDisabled = true
451 runner.ContainerID, err = runner.Docker.CreateContainer(&runner.ContainerConfig, "", nil)
453 return fmt.Errorf("While creating container: %v", err)
456 runner.HostConfig = dockerclient.HostConfig{Binds: runner.Binds,
457 LogConfig: dockerclient.LogConfig{Type: "none"}}
459 return runner.AttachStreams()
462 // StartContainer starts the docker container created by CreateContainer.
463 func (runner *ContainerRunner) StartContainer() error {
464 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
465 err := runner.Docker.StartContainer(runner.ContainerID, &runner.HostConfig)
467 return fmt.Errorf("could not start container: %v", err)
472 // WaitFinish waits for the container to terminate, capture the exit code, and
473 // close the stdout/stderr logging.
474 func (runner *ContainerRunner) WaitFinish() error {
475 runner.CrunchLog.Print("Waiting for container to finish")
477 result := runner.Docker.Wait(runner.ContainerID)
480 return fmt.Errorf("While waiting for container to finish: %v", wr.Error)
482 runner.ExitCode = &wr.ExitCode
484 // wait for stdout/stderr to complete
490 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
491 func (runner *ContainerRunner) CaptureOutput() error {
492 if runner.finalState != "Complete" {
496 if runner.HostOutputDir == "" {
500 _, err := os.Stat(runner.HostOutputDir)
502 return fmt.Errorf("While checking host output path: %v", err)
505 var manifestText string
507 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
508 _, err = os.Stat(collectionMetafile)
511 cw := CollectionWriter{runner.Kc, nil, sync.Mutex{}}
512 manifestText, err = cw.WriteTree(runner.HostOutputDir, runner.CrunchLog.Logger)
514 return fmt.Errorf("While uploading output files: %v", err)
517 // FUSE mount directory
518 file, openerr := os.Open(collectionMetafile)
520 return fmt.Errorf("While opening FUSE metafile: %v", err)
524 var rec arvados.Collection
525 err = json.NewDecoder(file).Decode(&rec)
527 return fmt.Errorf("While reading FUSE metafile: %v", err)
529 manifestText = rec.ManifestText
532 var response arvados.Collection
533 err = runner.ArvClient.Create("collections",
535 "collection": arvadosclient.Dict{
536 "manifest_text": manifestText}},
539 return fmt.Errorf("While creating output collection: %v", err)
542 runner.OutputPDH = new(string)
543 *runner.OutputPDH = response.PortableDataHash
548 func (runner *ContainerRunner) CleanupDirs() {
549 if runner.ArvMount != nil {
550 umount := exec.Command("fusermount", "-z", "-u", runner.ArvMountPoint)
551 umnterr := umount.Run()
553 runner.CrunchLog.Printf("While running fusermount: %v", umnterr)
556 mnterr := <-runner.ArvMountExit
558 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
562 for _, tmpdir := range runner.CleanupTempDir {
563 rmerr := os.RemoveAll(tmpdir)
565 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
570 // CommitLogs posts the collection containing the final container logs.
571 func (runner *ContainerRunner) CommitLogs() error {
572 runner.CrunchLog.Print(runner.finalState)
573 runner.CrunchLog.Close()
575 // Closing CrunchLog above allows it to be committed to Keep at this
576 // point, but re-open crunch log with ArvClient in case there are any
577 // other further (such as failing to write the log to Keep!) while
579 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{runner.ArvClient, runner.Container.UUID,
582 if runner.LogsPDH != nil {
583 // If we have already assigned something to LogsPDH,
584 // we must be closing the re-opened log, which won't
585 // end up getting attached to the container record and
586 // therefore doesn't need to be saved as a collection
587 // -- it exists only to send logs to other channels.
591 mt, err := runner.LogCollection.ManifestText()
593 return fmt.Errorf("While creating log manifest: %v", err)
596 var response arvados.Collection
597 err = runner.ArvClient.Create("collections",
599 "collection": arvadosclient.Dict{
600 "name": "logs for " + runner.Container.UUID,
601 "manifest_text": mt}},
604 return fmt.Errorf("While creating log collection: %v", err)
607 runner.LogsPDH = &response.PortableDataHash
612 // UpdateContainerRunning updates the container state to "Running"
613 func (runner *ContainerRunner) UpdateContainerRunning() error {
614 runner.CancelLock.Lock()
615 defer runner.CancelLock.Unlock()
616 if runner.Cancelled {
619 return runner.ArvClient.Update("containers", runner.Container.UUID,
620 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
623 // ContainerToken returns the api_token the container (and any
624 // arv-mount processes) are allowed to use.
625 func (runner *ContainerRunner) ContainerToken() (string, error) {
626 if runner.token != "" {
627 return runner.token, nil
630 var auth arvados.APIClientAuthorization
631 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
635 runner.token = auth.APIToken
636 return runner.token, nil
639 // UpdateContainerComplete updates the container record state on API
640 // server to "Complete" or "Cancelled"
641 func (runner *ContainerRunner) UpdateContainerFinal() error {
642 update := arvadosclient.Dict{}
643 update["state"] = runner.finalState
644 if runner.finalState == "Complete" {
645 if runner.LogsPDH != nil {
646 update["log"] = *runner.LogsPDH
648 if runner.ExitCode != nil {
649 update["exit_code"] = *runner.ExitCode
651 if runner.OutputPDH != nil {
652 update["output"] = *runner.OutputPDH
655 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
658 // IsCancelled returns the value of Cancelled, with goroutine safety.
659 func (runner *ContainerRunner) IsCancelled() bool {
660 runner.CancelLock.Lock()
661 defer runner.CancelLock.Unlock()
662 return runner.Cancelled
665 // NewArvLogWriter creates an ArvLogWriter
666 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
667 return &ArvLogWriter{runner.ArvClient, runner.Container.UUID, name, runner.LogCollection.Open(name + ".txt")}
670 // Run the full container lifecycle.
671 func (runner *ContainerRunner) Run() (err error) {
672 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
674 hostname, hosterr := os.Hostname()
676 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
678 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
681 // Clean up temporary directories _after_ finalizing
682 // everything (if we've made any by then)
683 defer runner.CleanupDirs()
685 runner.finalState = "Queued"
688 // checkErr prints e (unless it's nil) and sets err to
689 // e (unless err is already non-nil). Thus, if err
690 // hasn't already been assigned when Run() returns,
691 // this cleanup func will cause Run() to return the
692 // first non-nil error that is passed to checkErr().
693 checkErr := func(e error) {
697 runner.CrunchLog.Print(e)
703 // Log the error encountered in Run(), if any
706 if runner.finalState == "Queued" {
707 runner.UpdateContainerFinal()
711 if runner.IsCancelled() {
712 runner.finalState = "Cancelled"
713 // but don't return yet -- we still want to
714 // capture partial output and write logs
717 checkErr(runner.CaptureOutput())
718 checkErr(runner.CommitLogs())
719 checkErr(runner.UpdateContainerFinal())
721 // The real log is already closed, but then we opened
722 // a new one in case we needed to log anything while
724 runner.CrunchLog.Close()
727 err = runner.ArvClient.Get("containers", runner.Container.UUID, nil, &runner.Container)
729 err = fmt.Errorf("While getting container record: %v", err)
733 // setup signal handling
734 runner.SetupSignals()
736 // check for and/or load image
737 err = runner.LoadImage()
739 err = fmt.Errorf("While loading container image: %v", err)
743 // set up FUSE mount and binds
744 err = runner.SetupMounts()
746 err = fmt.Errorf("While setting up mounts: %v", err)
750 err = runner.CreateContainer()
755 if runner.IsCancelled() {
759 err = runner.UpdateContainerRunning()
763 runner.finalState = "Cancelled"
765 err = runner.StartContainer()
770 err = runner.WaitFinish()
772 runner.finalState = "Complete"
777 // NewContainerRunner creates a new container runner.
778 func NewContainerRunner(api IArvadosClient,
780 docker ThinDockerClient,
781 containerUUID string) *ContainerRunner {
783 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
784 cr.NewLogWriter = cr.NewArvLogWriter
785 cr.RunArvMount = cr.ArvMountCmd
786 cr.MkTempDir = ioutil.TempDir
787 cr.LogCollection = &CollectionWriter{kc, nil, sync.Mutex{}}
788 cr.Container.UUID = containerUUID
789 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
790 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
797 containerId := flag.Arg(0)
799 api, err := arvadosclient.MakeArvadosClient()
801 log.Fatalf("%s: %v", containerId, err)
805 var kc *keepclient.KeepClient
806 kc, err = keepclient.MakeKeepClient(&api)
808 log.Fatalf("%s: %v", containerId, err)
812 var docker *dockerclient.DockerClient
813 docker, err = dockerclient.NewDockerClient("unix:///var/run/docker.sock", nil)
815 log.Fatalf("%s: %v", containerId, err)
818 cr := NewContainerRunner(api, kc, docker, containerId)
822 log.Fatalf("%s: %v", containerId, err)