1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
30 "git.curoverse.com/arvados.git/lib/crunchstat"
31 "git.curoverse.com/arvados.git/sdk/go/arvados"
32 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
33 "git.curoverse.com/arvados.git/sdk/go/keepclient"
34 "git.curoverse.com/arvados.git/sdk/go/manifest"
35 "golang.org/x/net/context"
37 dockertypes "github.com/docker/docker/api/types"
38 dockercontainer "github.com/docker/docker/api/types/container"
39 dockernetwork "github.com/docker/docker/api/types/network"
40 dockerclient "github.com/docker/docker/client"
45 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
46 type IArvadosClient interface {
47 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
48 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
49 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
50 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
51 CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
52 Discovery(key string) (interface{}, error)
55 // ErrCancelled is the error returned when the container is cancelled.
56 var ErrCancelled = errors.New("Cancelled")
58 // IKeepClient is the minimal Keep API methods used by crunch-run.
59 type IKeepClient interface {
60 PutHB(hash string, buf []byte) (string, int, error)
61 ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error)
65 // NewLogWriter is a factory function to create a new log writer.
66 type NewLogWriter func(name string) io.WriteCloser
68 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
70 type MkTempDir func(string, string) (string, error)
72 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
73 type ThinDockerClient interface {
74 ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error)
75 ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
76 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error)
77 ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error
78 ContainerRemove(ctx context.Context, container string, options dockertypes.ContainerRemoveOptions) error
79 ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error)
80 ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error)
81 ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error)
82 ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error)
85 // ContainerRunner is the main stateful struct used for a single execution of a
87 type ContainerRunner struct {
88 Docker ThinDockerClient
89 ArvClient IArvadosClient
92 ContainerConfig dockercontainer.Config
93 dockercontainer.HostConfig
99 CrunchLog *ThrottledLogger
100 Stdout io.WriteCloser
101 Stderr io.WriteCloser
102 LogCollection *CollectionWriter
109 CleanupTempDir []string
111 Volumes map[string]struct{}
113 SigChan chan os.Signal
114 ArvMountExit chan error
117 statLogger io.WriteCloser
118 statReporter *crunchstat.Reporter
119 hoststatLogger io.WriteCloser
120 hoststatReporter *crunchstat.Reporter
121 statInterval time.Duration
123 // What we expect the container's cgroup parent to be.
124 expectCgroupParent string
125 // What we tell docker to use as the container's cgroup
126 // parent. Note: Ideally we would use the same field for both
127 // expectCgroupParent and setCgroupParent, and just make it
128 // default to "docker". However, when using docker < 1.10 with
129 // systemd, specifying a non-empty cgroup parent (even the
130 // default value "docker") hits a docker bug
131 // (https://github.com/docker/docker/issues/17126). Using two
132 // separate fields makes it possible to use the "expect cgroup
133 // parent to be X" feature even on sites where the "specify
134 // cgroup parent" feature breaks.
135 setCgroupParent string
137 cStateLock sync.Mutex
138 cCancelled bool // StopContainer() invoked
140 enableNetwork string // one of "default" or "always"
141 networkMode string // passed through to HostConfig.NetworkMode
142 arvMountLog *ThrottledLogger
145 // setupSignals sets up signal handling to gracefully terminate the underlying
146 // Docker container and update state when receiving a TERM, INT or QUIT signal.
147 func (runner *ContainerRunner) setupSignals() {
148 runner.SigChan = make(chan os.Signal, 1)
149 signal.Notify(runner.SigChan, syscall.SIGTERM)
150 signal.Notify(runner.SigChan, syscall.SIGINT)
151 signal.Notify(runner.SigChan, syscall.SIGQUIT)
153 go func(sig chan os.Signal) {
155 runner.CrunchLog.Printf("caught signal: %v", s)
161 // stop the underlying Docker container.
162 func (runner *ContainerRunner) stop() {
163 runner.cStateLock.Lock()
164 defer runner.cStateLock.Unlock()
165 if runner.ContainerID == "" {
168 runner.cCancelled = true
169 runner.CrunchLog.Printf("removing container")
170 err := runner.Docker.ContainerRemove(context.TODO(), runner.ContainerID, dockertypes.ContainerRemoveOptions{Force: true})
172 runner.CrunchLog.Printf("error removing container: %s", err)
176 func (runner *ContainerRunner) stopSignals() {
177 if runner.SigChan != nil {
178 signal.Stop(runner.SigChan)
182 var errorBlacklist = []string{
183 "(?ms).*[Cc]annot connect to the Docker daemon.*",
184 "(?ms).*oci runtime error.*starting container process.*container init.*mounting.*to rootfs.*no such file or directory.*",
186 var brokenNodeHook *string = flag.String("broken-node-hook", "", "Script to run if node is detected to be broken (for example, Docker daemon is not running)")
188 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
189 for _, d := range errorBlacklist {
190 if m, e := regexp.MatchString(d, goterr.Error()); m && e == nil {
191 runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
192 if *brokenNodeHook == "" {
193 runner.CrunchLog.Printf("No broken node hook provided, cannot mark node as broken.")
195 runner.CrunchLog.Printf("Running broken node hook %q", *brokenNodeHook)
197 c := exec.Command(*brokenNodeHook)
198 c.Stdout = runner.CrunchLog
199 c.Stderr = runner.CrunchLog
202 runner.CrunchLog.Printf("Error running broken node hook: %v", err)
211 // LoadImage determines the docker image id from the container record and
212 // checks if it is available in the local Docker image store. If not, it loads
213 // the image from Keep.
214 func (runner *ContainerRunner) LoadImage() (err error) {
216 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
218 var collection arvados.Collection
219 err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
221 return fmt.Errorf("While getting container image collection: %v", err)
223 manifest := manifest.Manifest{Text: collection.ManifestText}
224 var img, imageID string
225 for ms := range manifest.StreamIter() {
226 img = ms.FileStreamSegments[0].Name
227 if !strings.HasSuffix(img, ".tar") {
228 return fmt.Errorf("First file in the container image collection does not end in .tar")
230 imageID = img[:len(img)-4]
233 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
235 _, _, err = runner.Docker.ImageInspectWithRaw(context.TODO(), imageID)
237 runner.CrunchLog.Print("Loading Docker image from keep")
239 var readCloser io.ReadCloser
240 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
242 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
245 response, err := runner.Docker.ImageLoad(context.TODO(), readCloser, true)
247 return fmt.Errorf("While loading container image into Docker: %v", err)
250 defer response.Body.Close()
251 rbody, err := ioutil.ReadAll(response.Body)
253 return fmt.Errorf("Reading response to image load: %v", err)
255 runner.CrunchLog.Printf("Docker response: %s", rbody)
257 runner.CrunchLog.Print("Docker image is available")
260 runner.ContainerConfig.Image = imageID
262 runner.Kc.ClearBlockCache()
267 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
268 c = exec.Command("arv-mount", arvMountCmd...)
270 // Copy our environment, but override ARVADOS_API_TOKEN with
271 // the container auth token.
273 for _, s := range os.Environ() {
274 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
275 c.Env = append(c.Env, s)
278 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
280 runner.arvMountLog = NewThrottledLogger(runner.NewLogWriter("arv-mount"))
281 c.Stdout = runner.arvMountLog
282 c.Stderr = runner.arvMountLog
284 runner.CrunchLog.Printf("Running %v", c.Args)
291 statReadme := make(chan bool)
292 runner.ArvMountExit = make(chan error)
297 time.Sleep(100 * time.Millisecond)
298 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
310 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
312 runner.ArvMountExit <- mnterr
313 close(runner.ArvMountExit)
319 case err := <-runner.ArvMountExit:
320 runner.ArvMount = nil
328 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
329 if runner.ArvMountPoint == "" {
330 runner.ArvMountPoint, err = runner.MkTempDir("", prefix)
335 func (runner *ContainerRunner) SetupMounts() (err error) {
336 err = runner.SetupArvMountPoint("keep")
338 return fmt.Errorf("While creating keep mount temp dir: %v", err)
341 token, err := runner.ContainerToken()
343 return fmt.Errorf("could not get container token: %s", err)
348 arvMountCmd := []string{
352 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
354 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
355 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
358 collectionPaths := []string{}
360 runner.Volumes = make(map[string]struct{})
361 needCertMount := true
364 for bind := range runner.Container.Mounts {
365 binds = append(binds, bind)
369 for _, bind := range binds {
370 mnt := runner.Container.Mounts[bind]
371 if bind == "stdout" || bind == "stderr" {
372 // Is it a "file" mount kind?
373 if mnt.Kind != "file" {
374 return fmt.Errorf("Unsupported mount kind '%s' for %s. Only 'file' is supported.", mnt.Kind, bind)
377 // Does path start with OutputPath?
378 prefix := runner.Container.OutputPath
379 if !strings.HasSuffix(prefix, "/") {
382 if !strings.HasPrefix(mnt.Path, prefix) {
383 return fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
388 // Is it a "collection" mount kind?
389 if mnt.Kind != "collection" && mnt.Kind != "json" {
390 return fmt.Errorf("Unsupported mount kind '%s' for stdin. Only 'collection' or 'json' are supported.", mnt.Kind)
394 if bind == "/etc/arvados/ca-certificates.crt" {
395 needCertMount = false
398 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
399 if mnt.Kind != "collection" {
400 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
405 case mnt.Kind == "collection" && bind != "stdin":
407 if mnt.UUID != "" && mnt.PortableDataHash != "" {
408 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
412 return fmt.Errorf("Writing to existing collections currently not permitted.")
415 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
416 } else if mnt.PortableDataHash != "" {
418 return fmt.Errorf("Can never write to a collection specified by portable data hash")
420 idx := strings.Index(mnt.PortableDataHash, "/")
422 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
423 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
424 runner.Container.Mounts[bind] = mnt
426 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
427 if mnt.Path != "" && mnt.Path != "." {
428 if strings.HasPrefix(mnt.Path, "./") {
429 mnt.Path = mnt.Path[2:]
430 } else if strings.HasPrefix(mnt.Path, "/") {
431 mnt.Path = mnt.Path[1:]
433 src += "/" + mnt.Path
436 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
437 arvMountCmd = append(arvMountCmd, "--mount-tmp")
438 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
442 if bind == runner.Container.OutputPath {
443 runner.HostOutputDir = src
444 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
445 return fmt.Errorf("Writable mount points are not permitted underneath the output_path: %v", bind)
447 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
449 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
451 collectionPaths = append(collectionPaths, src)
453 case mnt.Kind == "tmp":
455 tmpdir, err = runner.MkTempDir("", "")
457 return fmt.Errorf("While creating mount temp dir: %v", err)
459 st, staterr := os.Stat(tmpdir)
461 return fmt.Errorf("While Stat on temp dir: %v", staterr)
463 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
465 return fmt.Errorf("While Chmod temp dir: %v", err)
467 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
468 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", tmpdir, bind))
469 if bind == runner.Container.OutputPath {
470 runner.HostOutputDir = tmpdir
473 case mnt.Kind == "json":
474 jsondata, err := json.Marshal(mnt.Content)
476 return fmt.Errorf("encoding json data: %v", err)
478 // Create a tempdir with a single file
479 // (instead of just a tempfile): this way we
480 // can ensure the file is world-readable
481 // inside the container, without having to
482 // make it world-readable on the docker host.
483 tmpdir, err := runner.MkTempDir("", "")
485 return fmt.Errorf("creating temp dir: %v", err)
487 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
488 tmpfn := filepath.Join(tmpdir, "mountdata.json")
489 err = ioutil.WriteFile(tmpfn, jsondata, 0644)
491 return fmt.Errorf("writing temp file: %v", err)
493 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
495 case mnt.Kind == "git_tree":
496 tmpdir, err := runner.MkTempDir("", "")
498 return fmt.Errorf("creating temp dir: %v", err)
500 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
501 err = gitMount(mnt).extractTree(runner.ArvClient, tmpdir, token)
505 runner.Binds = append(runner.Binds, tmpdir+":"+bind+":ro")
509 if runner.HostOutputDir == "" {
510 return fmt.Errorf("Output path does not correspond to a writable mount point")
513 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
514 for _, certfile := range arvadosclient.CertFiles {
515 _, err := os.Stat(certfile)
517 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
524 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
526 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
528 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
530 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
532 return fmt.Errorf("While trying to start arv-mount: %v", err)
535 for _, p := range collectionPaths {
538 return fmt.Errorf("While checking that input files exist: %v", err)
545 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
546 // Handle docker log protocol
547 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
548 defer close(runner.loggingDone)
550 header := make([]byte, 8)
553 _, err = io.ReadAtLeast(containerReader, header, 8)
560 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
563 _, err = io.CopyN(runner.Stdout, containerReader, readsize)
566 _, err = io.CopyN(runner.Stderr, containerReader, readsize)
571 runner.CrunchLog.Printf("error reading docker logs: %v", err)
574 err = runner.Stdout.Close()
576 runner.CrunchLog.Printf("error closing stdout logs: %v", err)
579 err = runner.Stderr.Close()
581 runner.CrunchLog.Printf("error closing stderr logs: %v", err)
584 if runner.statReporter != nil {
585 runner.statReporter.Stop()
586 err = runner.statLogger.Close()
588 runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
592 if runner.hoststatReporter != nil {
593 runner.hoststatReporter.Stop()
594 err = runner.hoststatLogger.Close()
596 runner.CrunchLog.Printf("error closing hoststat logs: %v", err)
601 func (runner *ContainerRunner) startHoststat() {
602 runner.hoststatLogger = NewThrottledLogger(runner.NewLogWriter("hoststat"))
603 runner.hoststatReporter = &crunchstat.Reporter{
604 Logger: log.New(runner.hoststatLogger, "", 0),
605 CgroupRoot: runner.cgroupRoot,
606 PollPeriod: runner.statInterval,
608 runner.hoststatReporter.Start()
611 func (runner *ContainerRunner) startCrunchstat() {
612 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
613 runner.statReporter = &crunchstat.Reporter{
614 CID: runner.ContainerID,
615 Logger: log.New(runner.statLogger, "", 0),
616 CgroupParent: runner.expectCgroupParent,
617 CgroupRoot: runner.cgroupRoot,
618 PollPeriod: runner.statInterval,
620 runner.statReporter.Start()
623 type infoCommand struct {
628 // LogHostInfo logs info about the current host, for debugging and
629 // accounting purposes. Although it's logged as "node-info", this is
630 // about the environment where crunch-run is actually running, which
631 // might differ from what's described in the node record (see
633 func (runner *ContainerRunner) LogHostInfo() (err error) {
634 w := runner.NewLogWriter("node-info")
636 commands := []infoCommand{
638 label: "Host Information",
639 cmd: []string{"uname", "-a"},
642 label: "CPU Information",
643 cmd: []string{"cat", "/proc/cpuinfo"},
646 label: "Memory Information",
647 cmd: []string{"cat", "/proc/meminfo"},
651 cmd: []string{"df", "-m", "/", os.TempDir()},
654 label: "Disk INodes",
655 cmd: []string{"df", "-i", "/", os.TempDir()},
659 // Run commands with informational output to be logged.
660 for _, command := range commands {
661 fmt.Fprintln(w, command.label)
662 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
665 if err := cmd.Run(); err != nil {
666 err = fmt.Errorf("While running command %q: %v", command.cmd, err)
675 return fmt.Errorf("While closing node-info logs: %v", err)
680 // LogContainerRecord gets and saves the raw JSON container record from the API server
681 func (runner *ContainerRunner) LogContainerRecord() error {
682 logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
683 if !logged && err == nil {
684 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
689 // LogNodeRecord logs arvados#node record corresponding to the current host.
690 func (runner *ContainerRunner) LogNodeRecord() error {
691 hostname := os.Getenv("SLURMD_NODENAME")
693 hostname, _ = os.Hostname()
695 _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
696 // The "info" field has admin-only info when obtained
697 // with a privileged token, and should not be logged.
698 node, ok := resp.(map[string]interface{})
706 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
708 ArvClient: runner.ArvClient,
709 UUID: runner.Container.UUID,
710 loggingStream: label,
711 writeCloser: runner.LogCollection.Open(label + ".json"),
714 reader, err := runner.ArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
716 return false, fmt.Errorf("error getting %s record: %v", label, err)
720 dec := json.NewDecoder(reader)
722 var resp map[string]interface{}
723 if err = dec.Decode(&resp); err != nil {
724 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
726 items, ok := resp["items"].([]interface{})
728 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
729 } else if len(items) < 1 {
735 // Re-encode it using indentation to improve readability
736 enc := json.NewEncoder(w)
737 enc.SetIndent("", " ")
738 if err = enc.Encode(items[0]); err != nil {
739 return false, fmt.Errorf("error logging %s record: %v", label, err)
743 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
748 // AttachStreams connects the docker container stdin, stdout and stderr logs
749 // to the Arvados logger which logs to Keep and the API server logs table.
750 func (runner *ContainerRunner) AttachStreams() (err error) {
752 runner.CrunchLog.Print("Attaching container streams")
754 // If stdin mount is provided, attach it to the docker container
755 var stdinRdr arvados.File
757 if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
758 if stdinMnt.Kind == "collection" {
759 var stdinColl arvados.Collection
760 collId := stdinMnt.UUID
762 collId = stdinMnt.PortableDataHash
764 err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
766 return fmt.Errorf("While getting stding collection: %v", err)
769 stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
770 if os.IsNotExist(err) {
771 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
772 } else if err != nil {
773 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
775 } else if stdinMnt.Kind == "json" {
776 stdinJson, err = json.Marshal(stdinMnt.Content)
778 return fmt.Errorf("While encoding stdin json data: %v", err)
783 stdinUsed := stdinRdr != nil || len(stdinJson) != 0
784 response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
785 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
787 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
790 runner.loggingDone = make(chan bool)
792 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
793 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
797 runner.Stdout = stdoutFile
799 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
802 if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
803 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
807 runner.Stderr = stderrFile
809 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
814 _, err := io.Copy(response.Conn, stdinRdr)
816 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
820 response.CloseWrite()
822 } else if len(stdinJson) != 0 {
824 _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
826 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
829 response.CloseWrite()
833 go runner.ProcessDockerAttach(response.Reader)
838 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
839 stdoutPath := mntPath[len(runner.Container.OutputPath):]
840 index := strings.LastIndex(stdoutPath, "/")
842 subdirs := stdoutPath[:index]
844 st, err := os.Stat(runner.HostOutputDir)
846 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
848 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
849 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
851 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
855 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
857 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
860 return stdoutFile, nil
863 // CreateContainer creates the docker container.
864 func (runner *ContainerRunner) CreateContainer() error {
865 runner.CrunchLog.Print("Creating Docker container")
867 runner.ContainerConfig.Cmd = runner.Container.Command
868 if runner.Container.Cwd != "." {
869 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
872 for k, v := range runner.Container.Environment {
873 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
876 runner.ContainerConfig.Volumes = runner.Volumes
878 runner.HostConfig = dockercontainer.HostConfig{
880 LogConfig: dockercontainer.LogConfig{
883 Resources: dockercontainer.Resources{
884 CgroupParent: runner.setCgroupParent,
888 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
889 tok, err := runner.ContainerToken()
893 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
894 "ARVADOS_API_TOKEN="+tok,
895 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
896 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
898 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
900 if runner.enableNetwork == "always" {
901 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
903 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
907 _, stdinUsed := runner.Container.Mounts["stdin"]
908 runner.ContainerConfig.OpenStdin = stdinUsed
909 runner.ContainerConfig.StdinOnce = stdinUsed
910 runner.ContainerConfig.AttachStdin = stdinUsed
911 runner.ContainerConfig.AttachStdout = true
912 runner.ContainerConfig.AttachStderr = true
914 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
916 return fmt.Errorf("While creating container: %v", err)
919 runner.ContainerID = createdBody.ID
921 return runner.AttachStreams()
924 // StartContainer starts the docker container created by CreateContainer.
925 func (runner *ContainerRunner) StartContainer() error {
926 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
927 runner.cStateLock.Lock()
928 defer runner.cStateLock.Unlock()
929 if runner.cCancelled {
932 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
933 dockertypes.ContainerStartOptions{})
936 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
937 advice = fmt.Sprintf("\nPossible causes: command %q is missing, the interpreter given in #! is missing, or script has Windows line endings.", runner.Container.Command[0])
939 return fmt.Errorf("could not start container: %v%s", err, advice)
944 // WaitFinish waits for the container to terminate, capture the exit code, and
945 // close the stdout/stderr logging.
946 func (runner *ContainerRunner) WaitFinish() error {
947 runner.CrunchLog.Print("Waiting for container to finish")
949 waitOk, waitErr := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID, dockercontainer.WaitConditionNotRunning)
950 arvMountExit := runner.ArvMountExit
953 case waitBody := <-waitOk:
954 runner.CrunchLog.Printf("Container exited with code: %v", waitBody.StatusCode)
955 code := int(waitBody.StatusCode)
956 runner.ExitCode = &code
958 // wait for stdout/stderr to complete
962 case err := <-waitErr:
963 return fmt.Errorf("container wait: %v", err)
966 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
968 // arvMountExit will always be ready now that
969 // it's closed, but that doesn't interest us.
975 var ErrNotInOutputDir = fmt.Errorf("Must point to path within the output directory")
977 func (runner *ContainerRunner) derefOutputSymlink(path string, startinfo os.FileInfo) (tgt string, readlinktgt string, info os.FileInfo, err error) {
978 // Follow symlinks if necessary
983 for followed := 0; info.Mode()&os.ModeSymlink != 0; followed++ {
984 if followed >= limitFollowSymlinks {
985 // Got stuck in a loop or just a pathological number of links, give up.
986 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
990 readlinktgt, err = os.Readlink(nextlink)
996 if !strings.HasPrefix(tgt, "/") {
997 // Relative symlink, resolve it to host path
998 tgt = filepath.Join(filepath.Dir(path), tgt)
1000 if strings.HasPrefix(tgt, runner.Container.OutputPath+"/") && !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
1001 // Absolute symlink to container output path, adjust it to host output path.
1002 tgt = filepath.Join(runner.HostOutputDir, tgt[len(runner.Container.OutputPath):])
1004 if !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
1005 // After dereferencing, symlink target must either be
1006 // within output directory, or must point to a
1007 // collection mount.
1008 err = ErrNotInOutputDir
1012 info, err = os.Lstat(tgt)
1015 err = fmt.Errorf("Symlink in output %q points to invalid location %q: %v",
1016 path[len(runner.HostOutputDir):], readlinktgt, err)
1026 var limitFollowSymlinks = 10
1028 // UploadFile uploads files within the output directory, with special handling
1029 // for symlinks. If the symlink leads to a keep mount, copy the manifest text
1030 // from the keep mount into the output manifestText. Ensure that whether
1031 // symlinks are relative or absolute, every symlink target (even targets that
1032 // are symlinks themselves) must point to a path in either the output directory
1033 // or a collection mount.
1035 // Assumes initial value of "path" is absolute, and located within runner.HostOutputDir.
1036 func (runner *ContainerRunner) UploadOutputFile(
1041 walkUpload *WalkUpload,
1042 relocateFrom string,
1044 followed int) (manifestText string, err error) {
1050 if info.Mode().IsDir() {
1051 // if empty, need to create a .keep file
1052 dir, direrr := os.Open(path)
1057 names, eof := dir.Readdirnames(1)
1058 if len(names) == 0 && eof == io.EOF && path != runner.HostOutputDir {
1059 containerPath := runner.OutputPath + path[len(runner.HostOutputDir):]
1060 for _, bind := range binds {
1061 mnt := runner.Container.Mounts[bind]
1062 // Check if there is a bind for this
1063 // directory, in which case assume we don't need .keep
1064 if (containerPath == bind || strings.HasPrefix(containerPath, bind+"/")) && mnt.PortableDataHash != "d41d8cd98f00b204e9800998ecf8427e+0" {
1068 outputSuffix := path[len(runner.HostOutputDir)+1:]
1069 return fmt.Sprintf("./%v d41d8cd98f00b204e9800998ecf8427e+0 0:0:.keep\n", outputSuffix), nil
1074 if followed >= limitFollowSymlinks {
1075 // Got stuck in a loop or just a pathological number of
1076 // directory links, give up.
1077 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
1081 // "path" is the actual path we are visiting
1082 // "tgt" is the target of "path" (a non-symlink) after following symlinks
1083 // "relocated" is the path in the output manifest where the file should be placed,
1084 // but has HostOutputDir as a prefix.
1086 // The destination path in the output manifest may need to be
1087 // logically relocated to some other path in order to appear
1088 // in the correct location as a result of following a symlink.
1089 // Remove the relocateFrom prefix and replace it with
1091 relocated := relocateTo + path[len(relocateFrom):]
1093 tgt, readlinktgt, info, derefErr := runner.derefOutputSymlink(path, info)
1094 if derefErr != nil && derefErr != ErrNotInOutputDir {
1098 // go through mounts and try reverse map to collection reference
1099 for _, bind := range binds {
1100 mnt := runner.Container.Mounts[bind]
1101 if tgt == bind || strings.HasPrefix(tgt, bind+"/") {
1102 // get path relative to bind
1103 targetSuffix := tgt[len(bind):]
1105 // Copy mount and adjust the path to add path relative to the bind
1106 adjustedMount := mnt
1107 adjustedMount.Path = filepath.Join(adjustedMount.Path, targetSuffix)
1109 // Terminates in this keep mount, so add the
1110 // manifest text at appropriate location.
1111 outputSuffix := relocated[len(runner.HostOutputDir):]
1112 manifestText, err = runner.getCollectionManifestForPath(adjustedMount, outputSuffix)
1117 // If target is not a collection mount, it must be located within the
1118 // output directory, otherwise it is an error.
1119 if derefErr == ErrNotInOutputDir {
1120 err = fmt.Errorf("Symlink in output %q points to invalid location %q, must point to path within the output directory.",
1121 path[len(runner.HostOutputDir):], readlinktgt)
1125 if info.Mode().IsRegular() {
1126 return "", walkUpload.UploadFile(relocated, tgt)
1129 if info.Mode().IsDir() {
1130 // Symlink leads to directory. Walk() doesn't follow
1131 // directory symlinks, so we walk the target directory
1132 // instead. Within the walk, file paths are relocated
1133 // so they appear under the original symlink path.
1134 err = filepath.Walk(tgt, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
1136 m, walkerr = runner.UploadOutputFile(walkpath, walkinfo, walkerr,
1137 binds, walkUpload, tgt, relocated, followed+1)
1139 manifestText = manifestText + m
1149 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
1150 func (runner *ContainerRunner) CaptureOutput() error {
1151 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
1152 // Output may have been set directly by the container, so
1153 // refresh the container record to check.
1154 err := runner.ArvClient.Get("containers", runner.Container.UUID,
1155 nil, &runner.Container)
1159 if runner.Container.Output != "" {
1160 // Container output is already set.
1161 runner.OutputPDH = &runner.Container.Output
1166 if runner.HostOutputDir == "" {
1170 _, err := os.Stat(runner.HostOutputDir)
1172 return fmt.Errorf("While checking host output path: %v", err)
1175 // Pre-populate output from the configured mount points
1177 for bind, mnt := range runner.Container.Mounts {
1178 if mnt.Kind == "collection" {
1179 binds = append(binds, bind)
1184 var manifestText string
1186 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
1187 _, err = os.Stat(collectionMetafile)
1189 // Regular directory
1191 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
1192 walkUpload := cw.BeginUpload(runner.HostOutputDir, runner.CrunchLog.Logger)
1195 err = filepath.Walk(runner.HostOutputDir, func(path string, info os.FileInfo, err error) error {
1196 m, err = runner.UploadOutputFile(path, info, err, binds, walkUpload, "", "", 0)
1198 manifestText = manifestText + m
1203 cw.EndUpload(walkUpload)
1206 return fmt.Errorf("While uploading output files: %v", err)
1209 m, err = cw.ManifestText()
1210 manifestText = manifestText + m
1212 return fmt.Errorf("While uploading output files: %v", err)
1215 // FUSE mount directory
1216 file, openerr := os.Open(collectionMetafile)
1218 return fmt.Errorf("While opening FUSE metafile: %v", err)
1222 var rec arvados.Collection
1223 err = json.NewDecoder(file).Decode(&rec)
1225 return fmt.Errorf("While reading FUSE metafile: %v", err)
1227 manifestText = rec.ManifestText
1230 for _, bind := range binds {
1231 mnt := runner.Container.Mounts[bind]
1233 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
1235 if bindSuffix == bind || len(bindSuffix) <= 0 {
1236 // either does not start with OutputPath or is OutputPath itself
1240 if mnt.ExcludeFromOutput == true {
1244 // append to manifest_text
1245 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
1250 manifestText = manifestText + m
1254 var response arvados.Collection
1255 manifest := manifest.Manifest{Text: manifestText}
1256 manifestText = manifest.Extract(".", ".").Text
1257 err = runner.ArvClient.Create("collections",
1259 "ensure_unique_name": true,
1260 "collection": arvadosclient.Dict{
1262 "name": "output for " + runner.Container.UUID,
1263 "manifest_text": manifestText}},
1266 return fmt.Errorf("While creating output collection: %v", err)
1268 runner.OutputPDH = &response.PortableDataHash
1272 var outputCollections = make(map[string]arvados.Collection)
1274 // Fetch the collection for the mnt.PortableDataHash
1275 // Return the manifest_text fragment corresponding to the specified mnt.Path
1276 // after making any required updates.
1278 // If mnt.Path is not specified,
1279 // return the entire manifest_text after replacing any "." with bindSuffix
1280 // If mnt.Path corresponds to one stream,
1281 // return the manifest_text for that stream after replacing that stream name with bindSuffix
1282 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1283 // for that stream after replacing stream name with bindSuffix minus the last word
1284 // and the file name with last word of the bindSuffix
1285 // Allowed path examples:
1287 // "path":"/subdir1"
1288 // "path":"/subdir1/subdir2"
1289 // "path":"/subdir/filename" etc
1290 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1291 collection := outputCollections[mnt.PortableDataHash]
1292 if collection.PortableDataHash == "" {
1293 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1295 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1297 outputCollections[mnt.PortableDataHash] = collection
1300 if collection.ManifestText == "" {
1301 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1305 mft := manifest.Manifest{Text: collection.ManifestText}
1306 extracted := mft.Extract(mnt.Path, bindSuffix)
1307 if extracted.Err != nil {
1308 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1310 return extracted.Text, nil
1313 func (runner *ContainerRunner) CleanupDirs() {
1314 if runner.ArvMount != nil {
1316 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1317 umount.Stdout = runner.CrunchLog
1318 umount.Stderr = runner.CrunchLog
1319 runner.CrunchLog.Printf("Running %v", umount.Args)
1320 umnterr := umount.Start()
1323 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1325 // If arv-mount --unmount gets stuck for any reason, we
1326 // don't want to wait for it forever. Do Wait() in a goroutine
1327 // so it doesn't block crunch-run.
1328 umountExit := make(chan error)
1330 mnterr := umount.Wait()
1332 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1334 umountExit <- mnterr
1337 for again := true; again; {
1343 case <-runner.ArvMountExit:
1345 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1346 runner.CrunchLog.Printf("Timed out waiting for unmount")
1348 umount.Process.Kill()
1350 runner.ArvMount.Process.Kill()
1356 if runner.ArvMountPoint != "" {
1357 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1358 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1362 for _, tmpdir := range runner.CleanupTempDir {
1363 if rmerr := os.RemoveAll(tmpdir); rmerr != nil {
1364 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1369 // CommitLogs posts the collection containing the final container logs.
1370 func (runner *ContainerRunner) CommitLogs() error {
1371 runner.CrunchLog.Print(runner.finalState)
1373 if runner.arvMountLog != nil {
1374 runner.arvMountLog.Close()
1376 runner.CrunchLog.Close()
1378 // Closing CrunchLog above allows them to be committed to Keep at this
1379 // point, but re-open crunch log with ArvClient in case there are any
1380 // other further errors (such as failing to write the log to Keep!)
1381 // while shutting down
1382 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1383 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1384 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1386 if runner.LogsPDH != nil {
1387 // If we have already assigned something to LogsPDH,
1388 // we must be closing the re-opened log, which won't
1389 // end up getting attached to the container record and
1390 // therefore doesn't need to be saved as a collection
1391 // -- it exists only to send logs to other channels.
1395 mt, err := runner.LogCollection.ManifestText()
1397 return fmt.Errorf("While creating log manifest: %v", err)
1400 var response arvados.Collection
1401 err = runner.ArvClient.Create("collections",
1403 "ensure_unique_name": true,
1404 "collection": arvadosclient.Dict{
1406 "name": "logs for " + runner.Container.UUID,
1407 "manifest_text": mt}},
1410 return fmt.Errorf("While creating log collection: %v", err)
1412 runner.LogsPDH = &response.PortableDataHash
1416 // UpdateContainerRunning updates the container state to "Running"
1417 func (runner *ContainerRunner) UpdateContainerRunning() error {
1418 runner.cStateLock.Lock()
1419 defer runner.cStateLock.Unlock()
1420 if runner.cCancelled {
1423 return runner.ArvClient.Update("containers", runner.Container.UUID,
1424 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1427 // ContainerToken returns the api_token the container (and any
1428 // arv-mount processes) are allowed to use.
1429 func (runner *ContainerRunner) ContainerToken() (string, error) {
1430 if runner.token != "" {
1431 return runner.token, nil
1434 var auth arvados.APIClientAuthorization
1435 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1439 runner.token = auth.APIToken
1440 return runner.token, nil
1443 // UpdateContainerComplete updates the container record state on API
1444 // server to "Complete" or "Cancelled"
1445 func (runner *ContainerRunner) UpdateContainerFinal() error {
1446 update := arvadosclient.Dict{}
1447 update["state"] = runner.finalState
1448 if runner.LogsPDH != nil {
1449 update["log"] = *runner.LogsPDH
1451 if runner.finalState == "Complete" {
1452 if runner.ExitCode != nil {
1453 update["exit_code"] = *runner.ExitCode
1455 if runner.OutputPDH != nil {
1456 update["output"] = *runner.OutputPDH
1459 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1462 // IsCancelled returns the value of Cancelled, with goroutine safety.
1463 func (runner *ContainerRunner) IsCancelled() bool {
1464 runner.cStateLock.Lock()
1465 defer runner.cStateLock.Unlock()
1466 return runner.cCancelled
1469 // NewArvLogWriter creates an ArvLogWriter
1470 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1471 return &ArvLogWriter{
1472 ArvClient: runner.ArvClient,
1473 UUID: runner.Container.UUID,
1474 loggingStream: name,
1475 writeCloser: runner.LogCollection.Open(name + ".txt")}
1478 // Run the full container lifecycle.
1479 func (runner *ContainerRunner) Run() (err error) {
1480 runner.CrunchLog.Printf("crunch-run %s started", version)
1481 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1483 hostname, hosterr := os.Hostname()
1485 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1487 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1490 runner.finalState = "Queued"
1493 runner.stopSignals()
1494 runner.CleanupDirs()
1496 runner.CrunchLog.Printf("crunch-run finished")
1497 runner.CrunchLog.Close()
1501 // checkErr prints e (unless it's nil) and sets err to
1502 // e (unless err is already non-nil). Thus, if err
1503 // hasn't already been assigned when Run() returns,
1504 // this cleanup func will cause Run() to return the
1505 // first non-nil error that is passed to checkErr().
1506 checkErr := func(e error) {
1510 runner.CrunchLog.Print(e)
1514 if runner.finalState == "Complete" {
1515 // There was an error in the finalization.
1516 runner.finalState = "Cancelled"
1520 // Log the error encountered in Run(), if any
1523 if runner.finalState == "Queued" {
1524 runner.UpdateContainerFinal()
1528 if runner.IsCancelled() {
1529 runner.finalState = "Cancelled"
1530 // but don't return yet -- we still want to
1531 // capture partial output and write logs
1534 checkErr(runner.CaptureOutput())
1535 checkErr(runner.CommitLogs())
1536 checkErr(runner.UpdateContainerFinal())
1539 err = runner.fetchContainerRecord()
1543 runner.setupSignals()
1544 runner.startHoststat()
1546 // check for and/or load image
1547 err = runner.LoadImage()
1549 if !runner.checkBrokenNode(err) {
1550 // Failed to load image but not due to a "broken node"
1551 // condition, probably user error.
1552 runner.finalState = "Cancelled"
1554 err = fmt.Errorf("While loading container image: %v", err)
1558 // set up FUSE mount and binds
1559 err = runner.SetupMounts()
1561 runner.finalState = "Cancelled"
1562 err = fmt.Errorf("While setting up mounts: %v", err)
1566 err = runner.CreateContainer()
1570 err = runner.LogHostInfo()
1574 err = runner.LogNodeRecord()
1578 err = runner.LogContainerRecord()
1583 if runner.IsCancelled() {
1587 err = runner.UpdateContainerRunning()
1591 runner.finalState = "Cancelled"
1593 runner.startCrunchstat()
1595 err = runner.StartContainer()
1597 runner.checkBrokenNode(err)
1601 err = runner.WaitFinish()
1602 if err == nil && !runner.IsCancelled() {
1603 runner.finalState = "Complete"
1608 // Fetch the current container record (uuid = runner.Container.UUID)
1609 // into runner.Container.
1610 func (runner *ContainerRunner) fetchContainerRecord() error {
1611 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1613 return fmt.Errorf("error fetching container record: %v", err)
1615 defer reader.Close()
1617 dec := json.NewDecoder(reader)
1619 err = dec.Decode(&runner.Container)
1621 return fmt.Errorf("error decoding container record: %v", err)
1626 // NewContainerRunner creates a new container runner.
1627 func NewContainerRunner(api IArvadosClient,
1629 docker ThinDockerClient,
1630 containerUUID string) *ContainerRunner {
1632 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1633 cr.NewLogWriter = cr.NewArvLogWriter
1634 cr.RunArvMount = cr.ArvMountCmd
1635 cr.MkTempDir = ioutil.TempDir
1636 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1637 cr.Container.UUID = containerUUID
1638 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1639 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1641 loadLogThrottleParams(api)
1647 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1648 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1649 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1650 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1651 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1652 enableNetwork := flag.String("container-enable-networking", "default",
1653 `Specify if networking should be enabled for container. One of 'default', 'always':
1654 default: only enable networking if container requests it.
1655 always: containers always have networking enabled
1657 networkMode := flag.String("container-network-mode", "default",
1658 `Set networking mode for container. Corresponds to Docker network mode (--net).
1660 memprofile := flag.String("memprofile", "", "write memory profile to `file` after running container")
1661 getVersion := flag.Bool("version", false, "Print version information and exit.")
1664 // Print version information if requested
1666 fmt.Printf("crunch-run %s\n", version)
1670 log.Printf("crunch-run %s started", version)
1672 containerId := flag.Arg(0)
1674 if *caCertsPath != "" {
1675 arvadosclient.CertFiles = []string{*caCertsPath}
1678 api, err := arvadosclient.MakeArvadosClient()
1680 log.Fatalf("%s: %v", containerId, err)
1684 kc, kcerr := keepclient.MakeKeepClient(api)
1686 log.Fatalf("%s: %v", containerId, kcerr)
1688 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1691 // API version 1.21 corresponds to Docker 1.9, which is currently the
1692 // minimum version we want to support.
1693 docker, dockererr := dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1695 cr := NewContainerRunner(api, kc, docker, containerId)
1696 if dockererr != nil {
1697 cr.CrunchLog.Printf("%s: %v", containerId, dockererr)
1698 cr.checkBrokenNode(dockererr)
1699 cr.CrunchLog.Close()
1703 cr.statInterval = *statInterval
1704 cr.cgroupRoot = *cgroupRoot
1705 cr.expectCgroupParent = *cgroupParent
1706 cr.enableNetwork = *enableNetwork
1707 cr.networkMode = *networkMode
1708 if *cgroupParentSubsystem != "" {
1709 p := findCgroup(*cgroupParentSubsystem)
1710 cr.setCgroupParent = p
1711 cr.expectCgroupParent = p
1716 if *memprofile != "" {
1717 f, err := os.Create(*memprofile)
1719 log.Printf("could not create memory profile: ", err)
1721 runtime.GC() // get up-to-date statistics
1722 if err := pprof.WriteHeapProfile(f); err != nil {
1723 log.Printf("could not write memory profile: ", err)
1725 closeerr := f.Close()
1726 if closeerr != nil {
1727 log.Printf("closing memprofile file: ", err)
1732 log.Fatalf("%s: %v", containerId, runerr)