8 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
9 "git.curoverse.com/arvados.git/sdk/go/keepclient"
10 "git.curoverse.com/arvados.git/sdk/go/manifest"
11 "github.com/curoverse/dockerclient"
24 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
25 type IArvadosClient interface {
26 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
27 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
28 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error)
31 // ErrCancelled is the error returned when the container is cancelled.
32 var ErrCancelled = errors.New("Cancelled")
34 // IKeepClient is the minimal Keep API methods used by crunch-run.
35 type IKeepClient interface {
36 PutHB(hash string, buf []byte) (string, int, error)
37 ManifestFileReader(m manifest.Manifest, filename string) (keepclient.ReadCloserWithLen, error)
40 // Mount describes the mount points to create inside the container.
42 Kind string `json:"kind"`
43 Writable bool `json:"writable"`
44 PortableDataHash string `json:"portable_data_hash"`
45 UUID string `json:"uuid"`
46 DeviceType string `json:"device_type"`
49 // Collection record returned by the API server.
50 type CollectionRecord struct {
51 ManifestText string `json:"manifest_text"`
52 PortableDataHash string `json:"portable_data_hash"`
55 // ContainerRecord is the container record returned by the API server.
56 type ContainerRecord struct {
57 UUID string `json:"uuid"`
58 Command []string `json:"command"`
59 ContainerImage string `json:"container_image"`
60 Cwd string `json:"cwd"`
61 Environment map[string]string `json:"environment"`
62 Mounts map[string]Mount `json:"mounts"`
63 OutputPath string `json:"output_path"`
64 Priority int `json:"priority"`
65 RuntimeConstraints map[string]interface{} `json:"runtime_constraints"`
66 State string `json:"state"`
67 Output string `json:"output"`
70 // NewLogWriter is a factory function to create a new log writer.
71 type NewLogWriter func(name string) io.WriteCloser
73 type RunArvMount func([]string) (*exec.Cmd, error)
75 type MkTempDir func(string, string) (string, error)
77 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
78 type ThinDockerClient interface {
79 StopContainer(id string, timeout int) error
80 InspectImage(id string) (*dockerclient.ImageInfo, error)
81 LoadImage(reader io.Reader) error
82 CreateContainer(config *dockerclient.ContainerConfig, name string, authConfig *dockerclient.AuthConfig) (string, error)
83 StartContainer(id string, config *dockerclient.HostConfig) error
84 ContainerLogs(id string, options *dockerclient.LogOptions) (io.ReadCloser, error)
85 Wait(id string) <-chan dockerclient.WaitResult
86 RemoveImage(name string, force bool) ([]*dockerclient.ImageDelete, error)
89 // ContainerRunner is the main stateful struct used for a single execution of a
91 type ContainerRunner struct {
92 Docker ThinDockerClient
93 ArvClient IArvadosClient
96 dockerclient.ContainerConfig
100 loggingDone chan bool
101 CrunchLog *ThrottledLogger
102 Stdout *ThrottledLogger
103 Stderr *ThrottledLogger
104 LogCollection *CollectionWriter
111 CleanupTempDir []string
114 CancelLock sync.Mutex
116 SigChan chan os.Signal
117 ArvMountExit chan error
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() error {
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 if !runner.Cancelled {
132 runner.CancelLock.Lock()
133 runner.Cancelled = true
134 if runner.ContainerID != "" {
135 runner.Docker.StopContainer(runner.ContainerID, 10)
137 runner.CancelLock.Unlock()
145 // LoadImage determines the docker image id from the container record and
146 // checks if it is available in the local Docker image store. If not, it loads
147 // the image from Keep.
148 func (runner *ContainerRunner) LoadImage() (err error) {
150 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.ContainerRecord.ContainerImage)
152 var collection CollectionRecord
153 err = runner.ArvClient.Get("collections", runner.ContainerRecord.ContainerImage, nil, &collection)
155 return fmt.Errorf("While getting container image collection: %v", err)
157 manifest := manifest.Manifest{Text: collection.ManifestText}
158 var img, imageID string
159 for ms := range manifest.StreamIter() {
160 img = ms.FileStreamSegments[0].Name
161 if !strings.HasSuffix(img, ".tar") {
162 return fmt.Errorf("First file in the container image collection does not end in .tar")
164 imageID = img[:len(img)-4]
167 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
169 _, err = runner.Docker.InspectImage(imageID)
171 runner.CrunchLog.Print("Loading Docker image from keep")
173 var readCloser io.ReadCloser
174 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
176 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
179 err = runner.Docker.LoadImage(readCloser)
181 return fmt.Errorf("While loading container image into Docker: %v", err)
184 runner.CrunchLog.Print("Docker image is available")
187 runner.ContainerConfig.Image = imageID
192 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string) (c *exec.Cmd, err error) {
193 c = exec.Command("arv-mount", arvMountCmd...)
194 nt := NewThrottledLogger(runner.NewLogWriter("arv-mount"))
203 statReadme := make(chan bool)
204 runner.ArvMountExit = make(chan error)
209 time.Sleep(100 * time.Millisecond)
210 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
220 runner.ArvMountExit <- c.Wait()
221 close(runner.ArvMountExit)
227 case err := <-runner.ArvMountExit:
228 runner.ArvMount = nil
236 func (runner *ContainerRunner) SetupMounts() (err error) {
237 runner.ArvMountPoint, err = runner.MkTempDir("", "keep")
239 return fmt.Errorf("While creating keep mount temp dir: %v", err)
242 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.ArvMountPoint)
246 arvMountCmd := []string{"--foreground", "--allow-other"}
247 collectionPaths := []string{}
250 for bind, mnt := range runner.ContainerRecord.Mounts {
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.ContainerRecord.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.ContainerRecord.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)
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)
302 return fmt.Errorf("Unknown mount kind '%s'", mnt.Kind)
306 if runner.HostOutputDir == "" {
307 return fmt.Errorf("Output path does not correspond to a writable mount point")
311 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
313 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
315 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
317 runner.ArvMount, err = runner.RunArvMount(arvMountCmd)
319 return fmt.Errorf("While trying to start arv-mount: %v", err)
322 for _, p := range collectionPaths {
325 return fmt.Errorf("While checking that input files exist: %v", err)
332 // StartContainer creates the container and runs it.
333 func (runner *ContainerRunner) StartContainer() (err error) {
334 runner.CrunchLog.Print("Creating Docker container")
336 runner.CancelLock.Lock()
337 defer runner.CancelLock.Unlock()
339 if runner.Cancelled {
343 runner.ContainerConfig.Cmd = runner.ContainerRecord.Command
344 if runner.ContainerRecord.Cwd != "." {
345 runner.ContainerConfig.WorkingDir = runner.ContainerRecord.Cwd
347 for k, v := range runner.ContainerRecord.Environment {
348 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
350 runner.ContainerConfig.NetworkDisabled = true
351 runner.ContainerID, err = runner.Docker.CreateContainer(&runner.ContainerConfig, "", nil)
353 return fmt.Errorf("While creating container: %v", err)
355 hostConfig := &dockerclient.HostConfig{Binds: runner.Binds}
357 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
358 err = runner.Docker.StartContainer(runner.ContainerID, hostConfig)
360 return fmt.Errorf("While starting container: %v", err)
366 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
367 // Handle docker log protocol
368 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
370 header := make([]byte, 8)
372 _, readerr := io.ReadAtLeast(containerReader, header, 8)
375 readsize := int64(header[4]) | (int64(header[5]) << 8) | (int64(header[6]) << 16) | (int64(header[7]) << 24)
378 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
381 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
386 if readerr != io.EOF {
387 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
390 closeerr := runner.Stdout.Close()
392 runner.CrunchLog.Printf("While closing stdout logs: %v", readerr)
395 closeerr = runner.Stderr.Close()
397 runner.CrunchLog.Printf("While closing stderr logs: %v", readerr)
400 runner.loggingDone <- true
401 close(runner.loggingDone)
407 // AttachLogs connects the docker container stdout and stderr logs to the
408 // Arvados logger which logs to Keep and the API server logs table.
409 func (runner *ContainerRunner) AttachLogs() (err error) {
411 runner.CrunchLog.Print("Attaching container logs")
413 var containerReader io.Reader
414 containerReader, err = runner.Docker.ContainerLogs(runner.ContainerID, &dockerclient.LogOptions{Follow: true, Stdout: true, Stderr: true})
416 return fmt.Errorf("While attaching container logs: %v", err)
419 runner.loggingDone = make(chan bool)
421 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
422 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
424 go runner.ProcessDockerAttach(containerReader)
429 // WaitFinish waits for the container to terminate, capture the exit code, and
430 // close the stdout/stderr logging.
431 func (runner *ContainerRunner) WaitFinish() error {
432 result := runner.Docker.Wait(runner.ContainerID)
435 return fmt.Errorf("While waiting for container to finish: %v", wr.Error)
437 runner.ExitCode = &wr.ExitCode
439 // wait for stdout/stderr to complete
445 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
446 func (runner *ContainerRunner) CaptureOutput() error {
447 if runner.finalState != "Complete" {
451 if runner.HostOutputDir == "" {
455 _, err := os.Stat(runner.HostOutputDir)
457 return fmt.Errorf("While checking host output path: %v", err)
460 var manifestText string
462 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
463 _, err = os.Stat(collectionMetafile)
466 cw := CollectionWriter{runner.Kc, nil, sync.Mutex{}}
467 manifestText, err = cw.WriteTree(runner.HostOutputDir, runner.CrunchLog.Logger)
469 return fmt.Errorf("While uploading output files: %v", err)
472 // FUSE mount directory
473 file, openerr := os.Open(collectionMetafile)
475 return fmt.Errorf("While opening FUSE metafile: %v", err)
479 rec := CollectionRecord{}
480 err = json.NewDecoder(file).Decode(&rec)
482 return fmt.Errorf("While reading FUSE metafile: %v", err)
484 manifestText = rec.ManifestText
487 var response CollectionRecord
488 err = runner.ArvClient.Create("collections",
490 "collection": arvadosclient.Dict{
491 "manifest_text": manifestText}},
494 return fmt.Errorf("While creating output collection: %v", err)
497 runner.OutputPDH = new(string)
498 *runner.OutputPDH = response.PortableDataHash
503 func (runner *ContainerRunner) CleanupDirs() {
504 if runner.ArvMount != nil {
505 umount := exec.Command("fusermount", "-z", "-u", runner.ArvMountPoint)
506 umnterr := umount.Run()
508 runner.CrunchLog.Printf("While running fusermount: %v", umnterr)
511 mnterr := <-runner.ArvMountExit
513 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
517 for _, tmpdir := range runner.CleanupTempDir {
518 rmerr := os.RemoveAll(tmpdir)
519 runner.CrunchLog.Printf("While cleaning up temporary directories: %v", rmerr)
523 // CommitLogs posts the collection containing the final container logs.
524 func (runner *ContainerRunner) CommitLogs() error {
525 runner.CrunchLog.Print(runner.finalState)
526 runner.CrunchLog.Close()
528 // Closing CrunchLog above allows it to be committed to Keep at this
529 // point, but re-open crunch log with ArvClient in case there are any
530 // other further (such as failing to write the log to Keep!) while
532 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{runner.ArvClient, runner.ContainerRecord.UUID,
535 mt, err := runner.LogCollection.ManifestText()
537 return fmt.Errorf("While creating log manifest: %v", err)
540 var response CollectionRecord
541 err = runner.ArvClient.Create("collections",
543 "collection": arvadosclient.Dict{
544 "name": "logs for " + runner.ContainerRecord.UUID,
545 "manifest_text": mt}},
548 return fmt.Errorf("While creating log collection: %v", err)
551 runner.LogsPDH = new(string)
552 *runner.LogsPDH = response.PortableDataHash
557 // UpdateContainerRecordRunning updates the container state to "Running"
558 func (runner *ContainerRunner) UpdateContainerRecordRunning() error {
559 return runner.ArvClient.Update("containers", runner.ContainerRecord.UUID,
560 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
563 // UpdateContainerRecordComplete updates the container record state on API
564 // server to "Complete" or "Cancelled"
565 func (runner *ContainerRunner) UpdateContainerRecordComplete() error {
566 update := arvadosclient.Dict{}
567 if runner.LogsPDH != nil {
568 update["log"] = *runner.LogsPDH
570 if runner.ExitCode != nil {
571 update["exit_code"] = *runner.ExitCode
573 if runner.OutputPDH != nil {
574 update["output"] = runner.OutputPDH
577 update["state"] = runner.finalState
579 return runner.ArvClient.Update("containers", runner.ContainerRecord.UUID, arvadosclient.Dict{"container": update}, nil)
582 // NewArvLogWriter creates an ArvLogWriter
583 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
584 return &ArvLogWriter{runner.ArvClient, runner.ContainerRecord.UUID, name, runner.LogCollection.Open(name + ".txt")}
587 // Run the full container lifecycle.
588 func (runner *ContainerRunner) Run() (err error) {
589 runner.CrunchLog.Printf("Executing container '%s'", runner.ContainerRecord.UUID)
591 var runerr, waiterr error
595 runner.CrunchLog.Print(err)
598 if runner.Cancelled {
599 runner.finalState = "Cancelled"
601 runner.finalState = "Complete"
604 // (7) capture output
605 outputerr := runner.CaptureOutput()
606 if outputerr != nil {
607 runner.CrunchLog.Print(outputerr)
610 // (8) clean up temporary directories
614 logerr := runner.CommitLogs()
616 runner.CrunchLog.Print(logerr)
619 // (10) update container record with results
620 updateerr := runner.UpdateContainerRecordComplete()
621 if updateerr != nil {
622 runner.CrunchLog.Print(updateerr)
625 runner.CrunchLog.Close()
630 } else if waiterr != nil {
632 } else if logerr != nil {
634 } else if updateerr != nil {
640 err = runner.ArvClient.Get("containers", runner.ContainerRecord.UUID, nil, &runner.ContainerRecord)
642 return fmt.Errorf("While getting container record: %v", err)
645 // (1) setup signal handling
646 err = runner.SetupSignals()
648 return fmt.Errorf("While setting up signal handling: %v", err)
651 // (2) check for and/or load image
652 err = runner.LoadImage()
654 return fmt.Errorf("While loading container image: %v", err)
657 // (3) set up FUSE mount and binds
658 err = runner.SetupMounts()
660 return fmt.Errorf("While setting up mounts: %v", err)
663 // (3) create and start container
664 err = runner.StartContainer()
666 if err == ErrCancelled {
672 // (4) update container record state
673 err = runner.UpdateContainerRecordRunning()
675 runner.CrunchLog.Print(err)
678 // (5) attach container logs
679 runerr = runner.AttachLogs()
681 runner.CrunchLog.Print(runerr)
684 // (6) wait for container to finish
685 waiterr = runner.WaitFinish()
690 // NewContainerRunner creates a new container runner.
691 func NewContainerRunner(api IArvadosClient,
693 docker ThinDockerClient,
694 containerUUID string) *ContainerRunner {
696 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
697 cr.NewLogWriter = cr.NewArvLogWriter
698 cr.RunArvMount = cr.ArvMountCmd
699 cr.MkTempDir = ioutil.TempDir
700 cr.LogCollection = &CollectionWriter{kc, nil, sync.Mutex{}}
701 cr.ContainerRecord.UUID = containerUUID
702 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
709 api, err := arvadosclient.MakeArvadosClient()
711 log.Fatalf("%s: %v", flag.Arg(0), err)
715 var kc *keepclient.KeepClient
716 kc, err = keepclient.MakeKeepClient(&api)
718 log.Fatalf("%s: %v", flag.Arg(0), err)
722 var docker *dockerclient.DockerClient
723 docker, err = dockerclient.NewDockerClient("unix:///var/run/docker.sock", nil)
725 log.Fatalf("%s: %v", flag.Arg(0), err)
728 cr := NewContainerRunner(api, kc, docker, flag.Arg(0))
732 log.Fatalf("%s: %v", flag.Arg(0), err)