23 "git.curoverse.com/arvados.git/lib/crunchstat"
24 "git.curoverse.com/arvados.git/sdk/go/arvados"
25 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
26 "git.curoverse.com/arvados.git/sdk/go/keepclient"
27 "git.curoverse.com/arvados.git/sdk/go/manifest"
29 dockertypes "github.com/docker/docker/api/types"
30 dockercontainer "github.com/docker/docker/api/types/container"
31 dockernetwork "github.com/docker/docker/api/types/network"
32 dockerclient "github.com/docker/docker/client"
35 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
36 type IArvadosClient interface {
37 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
38 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
39 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
40 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
41 CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
42 Discovery(key string) (interface{}, error)
45 // ErrCancelled is the error returned when the container is cancelled.
46 var ErrCancelled = errors.New("Cancelled")
48 // IKeepClient is the minimal Keep API methods used by crunch-run.
49 type IKeepClient interface {
50 PutHB(hash string, buf []byte) (string, int, error)
51 ManifestFileReader(m manifest.Manifest, filename string) (keepclient.Reader, error)
54 // NewLogWriter is a factory function to create a new log writer.
55 type NewLogWriter func(name string) io.WriteCloser
57 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
59 type MkTempDir func(string, string) (string, error)
61 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
62 type ThinDockerClient interface {
63 ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error)
64 ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
65 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error)
66 ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error
67 ContainerStop(ctx context.Context, container string, timeout *time.Duration) error
68 ContainerWait(ctx context.Context, container string) (int64, error)
69 ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error)
70 ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error)
71 ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error)
74 // ThinDockerClientProxy is a proxy implementation of ThinDockerClient
75 // that executes the docker requests on dockerclient.Client
76 type ThinDockerClientProxy struct {
77 Docker *dockerclient.Client
80 // ContainerAttach invokes dockerclient.Client.ContainerAttach
81 func (proxy ThinDockerClientProxy) ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error) {
82 return proxy.Docker.ContainerAttach(ctx, container, options)
85 // ContainerCreate invokes dockerclient.Client.ContainerCreate
86 func (proxy ThinDockerClientProxy) ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
87 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error) {
88 return proxy.Docker.ContainerCreate(ctx, config, hostConfig, networkingConfig, containerName)
91 // ContainerStart invokes dockerclient.Client.ContainerStart
92 func (proxy ThinDockerClientProxy) ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error {
93 return proxy.Docker.ContainerStart(ctx, container, options)
96 // ContainerStop invokes dockerclient.Client.ContainerStop
97 func (proxy ThinDockerClientProxy) ContainerStop(ctx context.Context, container string, timeout *time.Duration) error {
98 return proxy.Docker.ContainerStop(ctx, container, timeout)
101 // ContainerWait invokes dockerclient.Client.ContainerWait
102 func (proxy ThinDockerClientProxy) ContainerWait(ctx context.Context, container string) (int64, error) {
103 return proxy.Docker.ContainerWait(ctx, container)
106 // ImageInspectWithRaw invokes dockerclient.Client.ImageInspectWithRaw
107 func (proxy ThinDockerClientProxy) ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error) {
108 return proxy.Docker.ImageInspectWithRaw(ctx, image)
111 // ImageLoad invokes dockerclient.Client.ImageLoad
112 func (proxy ThinDockerClientProxy) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error) {
113 return proxy.Docker.ImageLoad(ctx, input, quiet)
116 // ImageRemove invokes dockerclient.Client.ImageRemove
117 func (proxy ThinDockerClientProxy) ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {
118 return proxy.Docker.ImageRemove(ctx, image, options)
121 // ContainerRunner is the main stateful struct used for a single execution of a
123 type ContainerRunner struct {
124 Docker ThinDockerClient
125 ArvClient IArvadosClient
128 ContainerConfig dockercontainer.Config
129 dockercontainer.HostConfig
134 loggingDone chan bool
135 CrunchLog *ThrottledLogger
136 Stdout io.WriteCloser
137 Stderr *ThrottledLogger
138 LogCollection *CollectionWriter
145 CleanupTempDir []string
148 SigChan chan os.Signal
149 ArvMountExit chan error
152 statLogger io.WriteCloser
153 statReporter *crunchstat.Reporter
154 statInterval time.Duration
156 // What we expect the container's cgroup parent to be.
157 expectCgroupParent string
158 // What we tell docker to use as the container's cgroup
159 // parent. Note: Ideally we would use the same field for both
160 // expectCgroupParent and setCgroupParent, and just make it
161 // default to "docker". However, when using docker < 1.10 with
162 // systemd, specifying a non-empty cgroup parent (even the
163 // default value "docker") hits a docker bug
164 // (https://github.com/docker/docker/issues/17126). Using two
165 // separate fields makes it possible to use the "expect cgroup
166 // parent to be X" feature even on sites where the "specify
167 // cgroup parent" feature breaks.
168 setCgroupParent string
170 cStateLock sync.Mutex
171 cStarted bool // StartContainer() succeeded
172 cCancelled bool // StopContainer() invoked
174 enableNetwork string // one of "default" or "always"
175 networkMode string // passed through to HostConfig.NetworkMode
178 // SetupSignals sets up signal handling to gracefully terminate the underlying
179 // Docker container and update state when receiving a TERM, INT or QUIT signal.
180 func (runner *ContainerRunner) SetupSignals() {
181 runner.SigChan = make(chan os.Signal, 1)
182 signal.Notify(runner.SigChan, syscall.SIGTERM)
183 signal.Notify(runner.SigChan, syscall.SIGINT)
184 signal.Notify(runner.SigChan, syscall.SIGQUIT)
186 go func(sig chan os.Signal) {
193 // stop the underlying Docker container.
194 func (runner *ContainerRunner) stop() {
195 runner.cStateLock.Lock()
196 defer runner.cStateLock.Unlock()
197 if runner.cCancelled {
200 runner.cCancelled = true
202 timeout := time.Duration(10)
203 err := runner.Docker.ContainerStop(context.TODO(), runner.ContainerID, &(timeout))
205 log.Printf("StopContainer failed: %s", err)
210 // LoadImage determines the docker image id from the container record and
211 // checks if it is available in the local Docker image store. If not, it loads
212 // the image from Keep.
213 func (runner *ContainerRunner) LoadImage() (err error) {
215 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
217 var collection arvados.Collection
218 err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
220 return fmt.Errorf("While getting container image collection: %v", err)
222 manifest := manifest.Manifest{Text: collection.ManifestText}
223 var img, imageID string
224 for ms := range manifest.StreamIter() {
225 img = ms.FileStreamSegments[0].Name
226 if !strings.HasSuffix(img, ".tar") {
227 return fmt.Errorf("First file in the container image collection does not end in .tar")
229 imageID = img[:len(img)-4]
232 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
234 _, _, err = runner.Docker.ImageInspectWithRaw(context.TODO(), imageID)
236 runner.CrunchLog.Print("Loading Docker image from keep")
238 var readCloser io.ReadCloser
239 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
241 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
244 response, err := runner.Docker.ImageLoad(context.TODO(), readCloser, false)
246 return fmt.Errorf("While loading container image into Docker: %v", err)
248 response.Body.Close()
250 runner.CrunchLog.Print("Docker image is available")
253 runner.ContainerConfig.Image = imageID
258 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
259 c = exec.Command("arv-mount", arvMountCmd...)
261 // Copy our environment, but override ARVADOS_API_TOKEN with
262 // the container auth token.
264 for _, s := range os.Environ() {
265 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
266 c.Env = append(c.Env, s)
269 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
271 nt := NewThrottledLogger(runner.NewLogWriter("arv-mount"))
280 statReadme := make(chan bool)
281 runner.ArvMountExit = make(chan error)
286 time.Sleep(100 * time.Millisecond)
287 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
297 runner.ArvMountExit <- c.Wait()
298 close(runner.ArvMountExit)
304 case err := <-runner.ArvMountExit:
305 runner.ArvMount = nil
313 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
314 if runner.ArvMountPoint == "" {
315 runner.ArvMountPoint, err = runner.MkTempDir("", prefix)
320 func (runner *ContainerRunner) SetupMounts() (err error) {
321 err = runner.SetupArvMountPoint("keep")
323 return fmt.Errorf("While creating keep mount temp dir: %v", err)
326 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.ArvMountPoint)
330 arvMountCmd := []string{"--foreground", "--allow-other", "--read-write"}
332 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
333 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
336 collectionPaths := []string{}
338 needCertMount := true
341 for bind, _ := range runner.Container.Mounts {
342 binds = append(binds, bind)
346 for _, bind := range binds {
347 mnt := runner.Container.Mounts[bind]
348 if bind == "stdout" {
349 // Is it a "file" mount kind?
350 if mnt.Kind != "file" {
351 return fmt.Errorf("Unsupported mount kind '%s' for stdout. Only 'file' is supported.", mnt.Kind)
354 // Does path start with OutputPath?
355 prefix := runner.Container.OutputPath
356 if !strings.HasSuffix(prefix, "/") {
359 if !strings.HasPrefix(mnt.Path, prefix) {
360 return fmt.Errorf("Stdout path does not start with OutputPath: %s, %s", mnt.Path, prefix)
364 if bind == "/etc/arvados/ca-certificates.crt" {
365 needCertMount = false
368 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
369 if mnt.Kind != "collection" {
370 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
375 case mnt.Kind == "collection":
377 if mnt.UUID != "" && mnt.PortableDataHash != "" {
378 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
382 return fmt.Errorf("Writing to existing collections currently not permitted.")
385 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
386 } else if mnt.PortableDataHash != "" {
388 return fmt.Errorf("Can never write to a collection specified by portable data hash")
390 idx := strings.Index(mnt.PortableDataHash, "/")
392 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
393 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
394 runner.Container.Mounts[bind] = mnt
396 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
397 if mnt.Path != "" && mnt.Path != "." {
398 if strings.HasPrefix(mnt.Path, "./") {
399 mnt.Path = mnt.Path[2:]
400 } else if strings.HasPrefix(mnt.Path, "/") {
401 mnt.Path = mnt.Path[1:]
403 src += "/" + mnt.Path
406 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
407 arvMountCmd = append(arvMountCmd, "--mount-tmp")
408 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
412 if bind == runner.Container.OutputPath {
413 runner.HostOutputDir = src
414 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
415 return fmt.Errorf("Writable mount points are not permitted underneath the output_path: %v", bind)
417 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
419 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
421 collectionPaths = append(collectionPaths, src)
423 case mnt.Kind == "tmp" && bind == runner.Container.OutputPath:
424 runner.HostOutputDir, err = runner.MkTempDir("", "")
426 return fmt.Errorf("While creating mount temp dir: %v", err)
428 st, staterr := os.Stat(runner.HostOutputDir)
430 return fmt.Errorf("While Stat on temp dir: %v", staterr)
432 err = os.Chmod(runner.HostOutputDir, st.Mode()|os.ModeSetgid|0777)
434 return fmt.Errorf("While Chmod temp dir: %v", err)
436 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.HostOutputDir)
437 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", runner.HostOutputDir, bind))
439 case mnt.Kind == "tmp":
440 runner.Binds = append(runner.Binds, bind)
442 case mnt.Kind == "json":
443 jsondata, err := json.Marshal(mnt.Content)
445 return fmt.Errorf("encoding json data: %v", err)
447 // Create a tempdir with a single file
448 // (instead of just a tempfile): this way we
449 // can ensure the file is world-readable
450 // inside the container, without having to
451 // make it world-readable on the docker host.
452 tmpdir, err := runner.MkTempDir("", "")
454 return fmt.Errorf("creating temp dir: %v", err)
456 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
457 tmpfn := filepath.Join(tmpdir, "mountdata.json")
458 err = ioutil.WriteFile(tmpfn, jsondata, 0644)
460 return fmt.Errorf("writing temp file: %v", err)
462 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
466 if runner.HostOutputDir == "" {
467 return fmt.Errorf("Output path does not correspond to a writable mount point")
470 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
471 for _, certfile := range arvadosclient.CertFiles {
472 _, err := os.Stat(certfile)
474 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
481 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
483 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
485 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
487 token, err := runner.ContainerToken()
489 return fmt.Errorf("could not get container token: %s", err)
492 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
494 return fmt.Errorf("While trying to start arv-mount: %v", err)
497 for _, p := range collectionPaths {
500 return fmt.Errorf("While checking that input files exist: %v", err)
507 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
508 // Handle docker log protocol
509 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
511 header := make([]byte, 8)
513 _, readerr := io.ReadAtLeast(containerReader, header, 8)
516 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
519 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
522 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
527 if readerr != io.EOF {
528 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
531 closeerr := runner.Stdout.Close()
533 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
536 closeerr = runner.Stderr.Close()
538 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
541 if runner.statReporter != nil {
542 runner.statReporter.Stop()
543 closeerr = runner.statLogger.Close()
545 runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
549 runner.loggingDone <- true
550 close(runner.loggingDone)
556 func (runner *ContainerRunner) StartCrunchstat() {
557 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
558 runner.statReporter = &crunchstat.Reporter{
559 CID: runner.ContainerID,
560 Logger: log.New(runner.statLogger, "", 0),
561 CgroupParent: runner.expectCgroupParent,
562 CgroupRoot: runner.cgroupRoot,
563 PollPeriod: runner.statInterval,
565 runner.statReporter.Start()
568 type infoCommand struct {
573 // Gather node information and store it on the log for debugging
575 func (runner *ContainerRunner) LogNodeInfo() (err error) {
576 w := runner.NewLogWriter("node-info")
577 logger := log.New(w, "node-info", 0)
579 commands := []infoCommand{
581 label: "Host Information",
582 cmd: []string{"uname", "-a"},
585 label: "CPU Information",
586 cmd: []string{"cat", "/proc/cpuinfo"},
589 label: "Memory Information",
590 cmd: []string{"cat", "/proc/meminfo"},
594 cmd: []string{"df", "-m", "/", os.TempDir()},
597 label: "Disk INodes",
598 cmd: []string{"df", "-i", "/", os.TempDir()},
602 // Run commands with informational output to be logged.
604 for _, command := range commands {
605 out, err = exec.Command(command.cmd[0], command.cmd[1:]...).CombinedOutput()
607 return fmt.Errorf("While running command %q: %v",
610 logger.Println(command.label)
611 for _, line := range strings.Split(string(out), "\n") {
612 logger.Println(" ", line)
618 return fmt.Errorf("While closing node-info logs: %v", err)
623 // Get and save the raw JSON container record from the API server
624 func (runner *ContainerRunner) LogContainerRecord() (err error) {
627 runner.Container.UUID,
629 runner.LogCollection.Open("container.json"),
631 // Get Container record JSON from the API Server
632 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
634 return fmt.Errorf("While retrieving container record from the API server: %v", err)
637 // Read the API server response as []byte
638 json_bytes, err := ioutil.ReadAll(reader)
640 return fmt.Errorf("While reading container record API server response: %v", err)
642 // Decode the JSON []byte
643 var cr map[string]interface{}
644 if err = json.Unmarshal(json_bytes, &cr); err != nil {
645 return fmt.Errorf("While decoding the container record JSON response: %v", err)
647 // Re-encode it using indentation to improve readability
648 enc := json.NewEncoder(w)
649 enc.SetIndent("", " ")
650 if err = enc.Encode(cr); err != nil {
651 return fmt.Errorf("While logging the JSON container record: %v", err)
655 return fmt.Errorf("While closing container.json log: %v", err)
660 // AttachLogs connects the docker container stdout and stderr logs to the
661 // Arvados logger which logs to Keep and the API server logs table.
662 func (runner *ContainerRunner) AttachStreams() (err error) {
664 runner.CrunchLog.Print("Attaching container streams")
666 response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
667 dockertypes.ContainerAttachOptions{Stream: true, Stdout: true, Stderr: true})
669 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
672 runner.loggingDone = make(chan bool)
674 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
675 stdoutPath := stdoutMnt.Path[len(runner.Container.OutputPath):]
676 index := strings.LastIndex(stdoutPath, "/")
678 subdirs := stdoutPath[:index]
680 st, err := os.Stat(runner.HostOutputDir)
682 return fmt.Errorf("While Stat on temp dir: %v", err)
684 stdoutPath := path.Join(runner.HostOutputDir, subdirs)
685 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
687 return fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
691 stdoutFile, err := os.Create(path.Join(runner.HostOutputDir, stdoutPath))
693 return fmt.Errorf("While creating stdout file: %v", err)
695 runner.Stdout = stdoutFile
697 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
699 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
701 go runner.ProcessDockerAttach(response.Reader)
706 // CreateContainer creates the docker container.
707 func (runner *ContainerRunner) CreateContainer() error {
708 runner.CrunchLog.Print("Creating Docker container")
710 runner.ContainerConfig.Cmd = runner.Container.Command
711 if runner.Container.Cwd != "." {
712 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
715 for k, v := range runner.Container.Environment {
716 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
719 runner.HostConfig = dockercontainer.HostConfig{
721 Cgroup: dockercontainer.CgroupSpec(runner.setCgroupParent),
722 LogConfig: dockercontainer.LogConfig{
727 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
728 tok, err := runner.ContainerToken()
732 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
733 "ARVADOS_API_TOKEN="+tok,
734 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
735 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
737 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
739 if runner.enableNetwork == "always" {
740 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
742 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
746 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
748 return fmt.Errorf("While creating container: %v", err)
751 runner.ContainerID = createdBody.ID
753 return runner.AttachStreams()
756 // StartContainer starts the docker container created by CreateContainer.
757 func (runner *ContainerRunner) StartContainer() error {
758 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
759 runner.cStateLock.Lock()
760 defer runner.cStateLock.Unlock()
761 if runner.cCancelled {
764 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
765 dockertypes.ContainerStartOptions{})
767 return fmt.Errorf("could not start container: %v", err)
769 runner.cStarted = true
773 // WaitFinish waits for the container to terminate, capture the exit code, and
774 // close the stdout/stderr logging.
775 func (runner *ContainerRunner) WaitFinish() error {
776 runner.CrunchLog.Print("Waiting for container to finish")
778 waitDocker, err := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID)
780 return fmt.Errorf("container wait: %v", err)
783 runner.CrunchLog.Printf("Container exited with code: %v", waitDocker)
784 code := int(waitDocker)
785 runner.ExitCode = &code
787 waitMount := runner.ArvMountExit
789 case err := <-waitMount:
790 runner.CrunchLog.Printf("arv-mount exited before container finished: %v", err)
796 // wait for stdout/stderr to complete
802 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
803 func (runner *ContainerRunner) CaptureOutput() error {
804 if runner.finalState != "Complete" {
808 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
809 // Output may have been set directly by the container, so
810 // refresh the container record to check.
811 err := runner.ArvClient.Get("containers", runner.Container.UUID,
812 nil, &runner.Container)
816 if runner.Container.Output != "" {
817 // Container output is already set.
818 runner.OutputPDH = &runner.Container.Output
823 if runner.HostOutputDir == "" {
827 _, err := os.Stat(runner.HostOutputDir)
829 return fmt.Errorf("While checking host output path: %v", err)
832 var manifestText string
834 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
835 _, err = os.Stat(collectionMetafile)
838 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
839 manifestText, err = cw.WriteTree(runner.HostOutputDir, runner.CrunchLog.Logger)
841 return fmt.Errorf("While uploading output files: %v", err)
844 // FUSE mount directory
845 file, openerr := os.Open(collectionMetafile)
847 return fmt.Errorf("While opening FUSE metafile: %v", err)
851 var rec arvados.Collection
852 err = json.NewDecoder(file).Decode(&rec)
854 return fmt.Errorf("While reading FUSE metafile: %v", err)
856 manifestText = rec.ManifestText
859 // Pre-populate output from the configured mount points
861 for bind, _ := range runner.Container.Mounts {
862 binds = append(binds, bind)
866 for _, bind := range binds {
867 mnt := runner.Container.Mounts[bind]
869 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
871 if bindSuffix == bind || len(bindSuffix) <= 0 {
872 // either does not start with OutputPath or is OutputPath itself
876 if mnt.ExcludeFromOutput == true {
880 // append to manifest_text
881 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
886 manifestText = manifestText + m
890 var response arvados.Collection
891 manifest := manifest.Manifest{Text: manifestText}
892 manifestText = manifest.Extract(".", ".").Text
893 err = runner.ArvClient.Create("collections",
895 "ensure_unique_name": true,
896 "collection": arvadosclient.Dict{
898 "name": "output for " + runner.Container.UUID,
899 "manifest_text": manifestText}},
902 return fmt.Errorf("While creating output collection: %v", err)
904 runner.OutputPDH = &response.PortableDataHash
908 var outputCollections = make(map[string]arvados.Collection)
910 // Fetch the collection for the mnt.PortableDataHash
911 // Return the manifest_text fragment corresponding to the specified mnt.Path
912 // after making any required updates.
914 // If mnt.Path is not specified,
915 // return the entire manifest_text after replacing any "." with bindSuffix
916 // If mnt.Path corresponds to one stream,
917 // return the manifest_text for that stream after replacing that stream name with bindSuffix
918 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
919 // for that stream after replacing stream name with bindSuffix minus the last word
920 // and the file name with last word of the bindSuffix
921 // Allowed path examples:
924 // "path":"/subdir1/subdir2"
925 // "path":"/subdir/filename" etc
926 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
927 collection := outputCollections[mnt.PortableDataHash]
928 if collection.PortableDataHash == "" {
929 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
931 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
933 outputCollections[mnt.PortableDataHash] = collection
936 if collection.ManifestText == "" {
937 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
941 mft := manifest.Manifest{Text: collection.ManifestText}
942 extracted := mft.Extract(mnt.Path, bindSuffix)
943 if extracted.Err != nil {
944 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
946 return extracted.Text, nil
949 func (runner *ContainerRunner) CleanupDirs() {
950 if runner.ArvMount != nil {
951 umount := exec.Command("fusermount", "-z", "-u", runner.ArvMountPoint)
952 umnterr := umount.Run()
954 runner.CrunchLog.Printf("While running fusermount: %v", umnterr)
957 mnterr := <-runner.ArvMountExit
959 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
963 for _, tmpdir := range runner.CleanupTempDir {
964 rmerr := os.RemoveAll(tmpdir)
966 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
971 // CommitLogs posts the collection containing the final container logs.
972 func (runner *ContainerRunner) CommitLogs() error {
973 runner.CrunchLog.Print(runner.finalState)
974 runner.CrunchLog.Close()
976 // Closing CrunchLog above allows it to be committed to Keep at this
977 // point, but re-open crunch log with ArvClient in case there are any
978 // other further (such as failing to write the log to Keep!) while
980 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{runner.ArvClient, runner.Container.UUID,
983 if runner.LogsPDH != nil {
984 // If we have already assigned something to LogsPDH,
985 // we must be closing the re-opened log, which won't
986 // end up getting attached to the container record and
987 // therefore doesn't need to be saved as a collection
988 // -- it exists only to send logs to other channels.
992 mt, err := runner.LogCollection.ManifestText()
994 return fmt.Errorf("While creating log manifest: %v", err)
997 var response arvados.Collection
998 err = runner.ArvClient.Create("collections",
1000 "ensure_unique_name": true,
1001 "collection": arvadosclient.Dict{
1003 "name": "logs for " + runner.Container.UUID,
1004 "manifest_text": mt}},
1007 return fmt.Errorf("While creating log collection: %v", err)
1009 runner.LogsPDH = &response.PortableDataHash
1013 // UpdateContainerRunning updates the container state to "Running"
1014 func (runner *ContainerRunner) UpdateContainerRunning() error {
1015 runner.cStateLock.Lock()
1016 defer runner.cStateLock.Unlock()
1017 if runner.cCancelled {
1020 return runner.ArvClient.Update("containers", runner.Container.UUID,
1021 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1024 // ContainerToken returns the api_token the container (and any
1025 // arv-mount processes) are allowed to use.
1026 func (runner *ContainerRunner) ContainerToken() (string, error) {
1027 if runner.token != "" {
1028 return runner.token, nil
1031 var auth arvados.APIClientAuthorization
1032 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1036 runner.token = auth.APIToken
1037 return runner.token, nil
1040 // UpdateContainerComplete updates the container record state on API
1041 // server to "Complete" or "Cancelled"
1042 func (runner *ContainerRunner) UpdateContainerFinal() error {
1043 update := arvadosclient.Dict{}
1044 update["state"] = runner.finalState
1045 if runner.LogsPDH != nil {
1046 update["log"] = *runner.LogsPDH
1048 if runner.finalState == "Complete" {
1049 if runner.ExitCode != nil {
1050 update["exit_code"] = *runner.ExitCode
1052 if runner.OutputPDH != nil {
1053 update["output"] = *runner.OutputPDH
1056 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1059 // IsCancelled returns the value of Cancelled, with goroutine safety.
1060 func (runner *ContainerRunner) IsCancelled() bool {
1061 runner.cStateLock.Lock()
1062 defer runner.cStateLock.Unlock()
1063 return runner.cCancelled
1066 // NewArvLogWriter creates an ArvLogWriter
1067 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1068 return &ArvLogWriter{runner.ArvClient, runner.Container.UUID, name, runner.LogCollection.Open(name + ".txt")}
1071 // Run the full container lifecycle.
1072 func (runner *ContainerRunner) Run() (err error) {
1073 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1075 hostname, hosterr := os.Hostname()
1077 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1079 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1082 // Clean up temporary directories _after_ finalizing
1083 // everything (if we've made any by then)
1084 defer runner.CleanupDirs()
1086 runner.finalState = "Queued"
1089 // checkErr prints e (unless it's nil) and sets err to
1090 // e (unless err is already non-nil). Thus, if err
1091 // hasn't already been assigned when Run() returns,
1092 // this cleanup func will cause Run() to return the
1093 // first non-nil error that is passed to checkErr().
1094 checkErr := func(e error) {
1098 runner.CrunchLog.Print(e)
1104 // Log the error encountered in Run(), if any
1107 if runner.finalState == "Queued" {
1108 runner.CrunchLog.Close()
1109 runner.UpdateContainerFinal()
1113 if runner.IsCancelled() {
1114 runner.finalState = "Cancelled"
1115 // but don't return yet -- we still want to
1116 // capture partial output and write logs
1119 checkErr(runner.CaptureOutput())
1120 checkErr(runner.CommitLogs())
1121 checkErr(runner.UpdateContainerFinal())
1123 // The real log is already closed, but then we opened
1124 // a new one in case we needed to log anything while
1126 runner.CrunchLog.Close()
1129 err = runner.ArvClient.Get("containers", runner.Container.UUID, nil, &runner.Container)
1131 err = fmt.Errorf("While getting container record: %v", err)
1135 // setup signal handling
1136 runner.SetupSignals()
1138 // check for and/or load image
1139 err = runner.LoadImage()
1141 runner.finalState = "Cancelled"
1142 err = fmt.Errorf("While loading container image: %v", err)
1146 // set up FUSE mount and binds
1147 err = runner.SetupMounts()
1149 runner.finalState = "Cancelled"
1150 err = fmt.Errorf("While setting up mounts: %v", err)
1154 err = runner.CreateContainer()
1159 // Gather and record node information
1160 err = runner.LogNodeInfo()
1164 // Save container.json record on log collection
1165 err = runner.LogContainerRecord()
1170 runner.StartCrunchstat()
1172 if runner.IsCancelled() {
1176 err = runner.UpdateContainerRunning()
1180 runner.finalState = "Cancelled"
1182 err = runner.StartContainer()
1187 err = runner.WaitFinish()
1189 runner.finalState = "Complete"
1194 // NewContainerRunner creates a new container runner.
1195 func NewContainerRunner(api IArvadosClient,
1197 docker ThinDockerClient,
1198 containerUUID string) *ContainerRunner {
1200 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1201 cr.NewLogWriter = cr.NewArvLogWriter
1202 cr.RunArvMount = cr.ArvMountCmd
1203 cr.MkTempDir = ioutil.TempDir
1204 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1205 cr.Container.UUID = containerUUID
1206 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1207 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1212 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1213 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1214 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1215 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1216 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1217 enableNetwork := flag.String("container-enable-networking", "default",
1218 `Specify if networking should be enabled for container. One of 'default', 'always':
1219 default: only enable networking if container requests it.
1220 always: containers always have networking enabled
1222 networkMode := flag.String("container-network-mode", "default",
1223 `Set networking mode for container. Corresponds to Docker network mode (--net).
1227 containerId := flag.Arg(0)
1229 if *caCertsPath != "" {
1230 arvadosclient.CertFiles = []string{*caCertsPath}
1233 api, err := arvadosclient.MakeArvadosClient()
1235 log.Fatalf("%s: %v", containerId, err)
1239 var kc *keepclient.KeepClient
1240 kc, err = keepclient.MakeKeepClient(api)
1242 log.Fatalf("%s: %v", containerId, err)
1246 var docker *dockerclient.Client
1247 // API version 1.21 corresponds to Docker 1.9, which is currently the
1248 // minimum version we want to support.
1249 docker, err = dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1251 log.Fatalf("%s: %v", containerId, err)
1254 dockerClientProxy := ThinDockerClientProxy{Docker: docker}
1256 cr := NewContainerRunner(api, kc, dockerClientProxy, containerId)
1257 cr.statInterval = *statInterval
1258 cr.cgroupRoot = *cgroupRoot
1259 cr.expectCgroupParent = *cgroupParent
1260 cr.enableNetwork = *enableNetwork
1261 cr.networkMode = *networkMode
1262 if *cgroupParentSubsystem != "" {
1263 p := findCgroup(*cgroupParentSubsystem)
1264 cr.setCgroupParent = p
1265 cr.expectCgroupParent = p
1270 log.Fatalf("%s: %v", containerId, err)