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 "github.com/shirou/gopsutil/process"
36 "golang.org/x/net/context"
38 dockertypes "github.com/docker/docker/api/types"
39 dockercontainer "github.com/docker/docker/api/types/container"
40 dockernetwork "github.com/docker/docker/api/types/network"
41 dockerclient "github.com/docker/docker/client"
46 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
47 type IArvadosClient interface {
48 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
49 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
50 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
51 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
52 CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
53 Discovery(key string) (interface{}, error)
56 // ErrCancelled is the error returned when the container is cancelled.
57 var ErrCancelled = errors.New("Cancelled")
59 // IKeepClient is the minimal Keep API methods used by crunch-run.
60 type IKeepClient interface {
61 PutB(buf []byte) (string, int, error)
62 ReadAt(locator string, p []byte, off int) (int, error)
63 ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error)
64 LocalLocator(locator string) (string, error)
68 // NewLogWriter is a factory function to create a new log writer.
69 type NewLogWriter func(name string) (io.WriteCloser, error)
71 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
73 type MkTempDir func(string, string) (string, error)
75 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
76 type ThinDockerClient interface {
77 ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error)
78 ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
79 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error)
80 ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error
81 ContainerRemove(ctx context.Context, container string, options dockertypes.ContainerRemoveOptions) error
82 ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error)
83 ContainerInspect(ctx context.Context, id string) (dockertypes.ContainerJSON, error)
84 ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error)
85 ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error)
86 ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error)
89 type PsProcess interface {
90 CmdlineSlice() ([]string, error)
93 // ContainerRunner is the main stateful struct used for a single execution of a
95 type ContainerRunner struct {
96 Docker ThinDockerClient
97 client *arvados.Client
98 ArvClient IArvadosClient
100 Container arvados.Container
101 ContainerConfig dockercontainer.Config
102 HostConfig dockercontainer.HostConfig
106 NewLogWriter NewLogWriter
107 loggingDone chan bool
108 CrunchLog *ThrottledLogger
109 Stdout io.WriteCloser
110 Stderr io.WriteCloser
113 LogCollection arvados.CollectionFileSystem
115 RunArvMount RunArvMount
121 Volumes map[string]struct{}
123 SigChan chan os.Signal
124 ArvMountExit chan error
125 SecretMounts map[string]arvados.Mount
126 MkArvClient func(token string) (IArvadosClient, IKeepClient, error)
130 ListProcesses func() ([]PsProcess, error)
132 statLogger io.WriteCloser
133 statReporter *crunchstat.Reporter
134 hoststatLogger io.WriteCloser
135 hoststatReporter *crunchstat.Reporter
136 statInterval time.Duration
138 // What we expect the container's cgroup parent to be.
139 expectCgroupParent string
140 // What we tell docker to use as the container's cgroup
141 // parent. Note: Ideally we would use the same field for both
142 // expectCgroupParent and setCgroupParent, and just make it
143 // default to "docker". However, when using docker < 1.10 with
144 // systemd, specifying a non-empty cgroup parent (even the
145 // default value "docker") hits a docker bug
146 // (https://github.com/docker/docker/issues/17126). Using two
147 // separate fields makes it possible to use the "expect cgroup
148 // parent to be X" feature even on sites where the "specify
149 // cgroup parent" feature breaks.
150 setCgroupParent string
152 cStateLock sync.Mutex
153 cCancelled bool // StopContainer() invoked
154 cRemoved bool // docker confirmed the container no longer exists
156 enableNetwork string // one of "default" or "always"
157 networkMode string // passed through to HostConfig.NetworkMode
158 arvMountLog *ThrottledLogger
159 checkContainerd time.Duration
161 containerWatchdogInterval time.Duration
164 // setupSignals sets up signal handling to gracefully terminate the underlying
165 // Docker container and update state when receiving a TERM, INT or QUIT signal.
166 func (runner *ContainerRunner) setupSignals() {
167 runner.SigChan = make(chan os.Signal, 1)
168 signal.Notify(runner.SigChan, syscall.SIGTERM)
169 signal.Notify(runner.SigChan, syscall.SIGINT)
170 signal.Notify(runner.SigChan, syscall.SIGQUIT)
172 go func(sig chan os.Signal) {
179 // stop the underlying Docker container.
180 func (runner *ContainerRunner) stop(sig os.Signal) {
181 runner.cStateLock.Lock()
182 defer runner.cStateLock.Unlock()
184 runner.CrunchLog.Printf("caught signal: %v", sig)
186 if runner.ContainerID == "" {
189 runner.cCancelled = true
190 runner.CrunchLog.Printf("removing container")
191 err := runner.Docker.ContainerRemove(context.TODO(), runner.ContainerID, dockertypes.ContainerRemoveOptions{Force: true})
193 runner.CrunchLog.Printf("error removing container: %s", err)
195 if err == nil || strings.Contains(err.Error(), "No such container: "+runner.ContainerID) {
196 runner.cRemoved = true
200 var errorBlacklist = []string{
201 "(?ms).*[Cc]annot connect to the Docker daemon.*",
202 "(?ms).*oci runtime error.*starting container process.*container init.*mounting.*to rootfs.*no such file or directory.*",
203 "(?ms).*grpc: the connection is unavailable.*",
205 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)")
207 func (runner *ContainerRunner) runBrokenNodeHook() {
208 if *brokenNodeHook == "" {
209 runner.CrunchLog.Printf("No broken node hook provided, cannot mark node as broken.")
211 runner.CrunchLog.Printf("Running broken node hook %q", *brokenNodeHook)
213 c := exec.Command(*brokenNodeHook)
214 c.Stdout = runner.CrunchLog
215 c.Stderr = runner.CrunchLog
218 runner.CrunchLog.Printf("Error running broken node hook: %v", err)
223 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
224 for _, d := range errorBlacklist {
225 if m, e := regexp.MatchString(d, goterr.Error()); m && e == nil {
226 runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
227 runner.runBrokenNodeHook()
234 // LoadImage determines the docker image id from the container record and
235 // checks if it is available in the local Docker image store. If not, it loads
236 // the image from Keep.
237 func (runner *ContainerRunner) LoadImage() (err error) {
239 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
241 tok, err := runner.ContainerToken()
243 return fmt.Errorf("While getting container token (LoadImage): %v", err)
245 arvClient, kc, err := runner.MkArvClient(tok)
247 return fmt.Errorf("While creating arv client (LoadImage): %v", err)
250 var collection arvados.Collection
251 err = arvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
253 return fmt.Errorf("While getting container image collection: %v", err)
255 manifest := manifest.Manifest{Text: collection.ManifestText}
256 var img, imageID string
257 for ms := range manifest.StreamIter() {
258 img = ms.FileStreamSegments[0].Name
259 if !strings.HasSuffix(img, ".tar") {
260 return fmt.Errorf("First file in the container image collection does not end in .tar")
262 imageID = img[:len(img)-4]
265 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
267 _, _, err = runner.Docker.ImageInspectWithRaw(context.TODO(), imageID)
269 runner.CrunchLog.Print("Loading Docker image from keep")
271 var readCloser io.ReadCloser
272 readCloser, err = kc.ManifestFileReader(manifest, img)
274 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
277 response, err := runner.Docker.ImageLoad(context.TODO(), readCloser, true)
279 return fmt.Errorf("While loading container image into Docker: %v", err)
282 defer response.Body.Close()
283 rbody, err := ioutil.ReadAll(response.Body)
285 return fmt.Errorf("Reading response to image load: %v", err)
287 runner.CrunchLog.Printf("Docker response: %s", rbody)
289 runner.CrunchLog.Print("Docker image is available")
292 runner.ContainerConfig.Image = imageID
299 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
300 c = exec.Command("arv-mount", arvMountCmd...)
302 // Copy our environment, but override ARVADOS_API_TOKEN with
303 // the container auth token.
305 for _, s := range os.Environ() {
306 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
307 c.Env = append(c.Env, s)
310 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
312 w, err := runner.NewLogWriter("arv-mount")
316 runner.arvMountLog = NewThrottledLogger(w)
317 c.Stdout = runner.arvMountLog
318 c.Stderr = runner.arvMountLog
320 runner.CrunchLog.Printf("Running %v", c.Args)
327 statReadme := make(chan bool)
328 runner.ArvMountExit = make(chan error)
333 time.Sleep(100 * time.Millisecond)
334 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
346 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
348 runner.ArvMountExit <- mnterr
349 close(runner.ArvMountExit)
355 case err := <-runner.ArvMountExit:
356 runner.ArvMount = nil
364 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
365 if runner.ArvMountPoint == "" {
366 runner.ArvMountPoint, err = runner.MkTempDir(runner.parentTemp, prefix)
371 func copyfile(src string, dst string) (err error) {
372 srcfile, err := os.Open(src)
377 os.MkdirAll(path.Dir(dst), 0777)
379 dstfile, err := os.Create(dst)
383 _, err = io.Copy(dstfile, srcfile)
388 err = srcfile.Close()
389 err2 := dstfile.Close()
402 func (runner *ContainerRunner) SetupMounts() (err error) {
403 err = runner.SetupArvMountPoint("keep")
405 return fmt.Errorf("While creating keep mount temp dir: %v", err)
408 token, err := runner.ContainerToken()
410 return fmt.Errorf("could not get container token: %s", err)
415 arvMountCmd := []string{
419 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
421 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
422 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
425 collectionPaths := []string{}
427 runner.Volumes = make(map[string]struct{})
428 needCertMount := true
429 type copyFile struct {
433 var copyFiles []copyFile
436 for bind := range runner.Container.Mounts {
437 binds = append(binds, bind)
439 for bind := range runner.SecretMounts {
440 if _, ok := runner.Container.Mounts[bind]; ok {
441 return fmt.Errorf("Secret mount %q conflicts with regular mount", bind)
443 if runner.SecretMounts[bind].Kind != "json" &&
444 runner.SecretMounts[bind].Kind != "text" {
445 return fmt.Errorf("Secret mount %q type is %q but only 'json' and 'text' are permitted.",
446 bind, runner.SecretMounts[bind].Kind)
448 binds = append(binds, bind)
452 for _, bind := range binds {
453 mnt, ok := runner.Container.Mounts[bind]
455 mnt = runner.SecretMounts[bind]
457 if bind == "stdout" || bind == "stderr" {
458 // Is it a "file" mount kind?
459 if mnt.Kind != "file" {
460 return fmt.Errorf("Unsupported mount kind '%s' for %s. Only 'file' is supported.", mnt.Kind, bind)
463 // Does path start with OutputPath?
464 prefix := runner.Container.OutputPath
465 if !strings.HasSuffix(prefix, "/") {
468 if !strings.HasPrefix(mnt.Path, prefix) {
469 return fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
474 // Is it a "collection" mount kind?
475 if mnt.Kind != "collection" && mnt.Kind != "json" {
476 return fmt.Errorf("Unsupported mount kind '%s' for stdin. Only 'collection' or 'json' are supported.", mnt.Kind)
480 if bind == "/etc/arvados/ca-certificates.crt" {
481 needCertMount = false
484 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
485 if mnt.Kind != "collection" && mnt.Kind != "text" && mnt.Kind != "json" {
486 return fmt.Errorf("Only mount points of kind 'collection', 'text' or 'json' are supported underneath the output_path for %q, was %q", bind, mnt.Kind)
491 case mnt.Kind == "collection" && bind != "stdin":
493 if mnt.UUID != "" && mnt.PortableDataHash != "" {
494 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
498 return fmt.Errorf("Writing to existing collections currently not permitted.")
501 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
502 } else if mnt.PortableDataHash != "" {
503 if mnt.Writable && !strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
504 return fmt.Errorf("Can never write to a collection specified by portable data hash")
506 idx := strings.Index(mnt.PortableDataHash, "/")
508 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
509 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
510 runner.Container.Mounts[bind] = mnt
512 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
513 if mnt.Path != "" && mnt.Path != "." {
514 if strings.HasPrefix(mnt.Path, "./") {
515 mnt.Path = mnt.Path[2:]
516 } else if strings.HasPrefix(mnt.Path, "/") {
517 mnt.Path = mnt.Path[1:]
519 src += "/" + mnt.Path
522 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
523 arvMountCmd = append(arvMountCmd, "--mount-tmp")
524 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
528 if bind == runner.Container.OutputPath {
529 runner.HostOutputDir = src
530 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
531 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
532 copyFiles = append(copyFiles, copyFile{src, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
534 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
537 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
539 collectionPaths = append(collectionPaths, src)
541 case mnt.Kind == "tmp":
543 tmpdir, err = runner.MkTempDir(runner.parentTemp, "tmp")
545 return fmt.Errorf("While creating mount temp dir: %v", err)
547 st, staterr := os.Stat(tmpdir)
549 return fmt.Errorf("While Stat on temp dir: %v", staterr)
551 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
553 return fmt.Errorf("While Chmod temp dir: %v", err)
555 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", tmpdir, bind))
556 if bind == runner.Container.OutputPath {
557 runner.HostOutputDir = tmpdir
560 case mnt.Kind == "json" || mnt.Kind == "text":
562 if mnt.Kind == "json" {
563 filedata, err = json.Marshal(mnt.Content)
565 return fmt.Errorf("encoding json data: %v", err)
568 text, ok := mnt.Content.(string)
570 return fmt.Errorf("content for mount %q must be a string", bind)
572 filedata = []byte(text)
575 tmpdir, err := runner.MkTempDir(runner.parentTemp, mnt.Kind)
577 return fmt.Errorf("creating temp dir: %v", err)
579 tmpfn := filepath.Join(tmpdir, "mountdata."+mnt.Kind)
580 err = ioutil.WriteFile(tmpfn, filedata, 0444)
582 return fmt.Errorf("writing temp file: %v", err)
584 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
585 copyFiles = append(copyFiles, copyFile{tmpfn, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
587 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
590 case mnt.Kind == "git_tree":
591 tmpdir, err := runner.MkTempDir(runner.parentTemp, "git_tree")
593 return fmt.Errorf("creating temp dir: %v", err)
595 err = gitMount(mnt).extractTree(runner.ArvClient, tmpdir, token)
599 runner.Binds = append(runner.Binds, tmpdir+":"+bind+":ro")
603 if runner.HostOutputDir == "" {
604 return fmt.Errorf("Output path does not correspond to a writable mount point")
607 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
608 for _, certfile := range arvadosclient.CertFiles {
609 _, err := os.Stat(certfile)
611 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
618 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
620 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
622 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
624 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
626 return fmt.Errorf("While trying to start arv-mount: %v", err)
629 for _, p := range collectionPaths {
632 return fmt.Errorf("While checking that input files exist: %v", err)
636 for _, cp := range copyFiles {
637 st, err := os.Stat(cp.src)
639 return fmt.Errorf("While staging writable file from %q to %q: %v", cp.src, cp.bind, err)
642 err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
646 target := path.Join(cp.bind, walkpath[len(cp.src):])
647 if walkinfo.Mode().IsRegular() {
648 copyerr := copyfile(walkpath, target)
652 return os.Chmod(target, walkinfo.Mode()|0777)
653 } else if walkinfo.Mode().IsDir() {
654 mkerr := os.MkdirAll(target, 0777)
658 return os.Chmod(target, walkinfo.Mode()|os.ModeSetgid|0777)
660 return fmt.Errorf("Source %q is not a regular file or directory", cp.src)
663 } else if st.Mode().IsRegular() {
664 err = copyfile(cp.src, cp.bind)
666 err = os.Chmod(cp.bind, st.Mode()|0777)
670 return fmt.Errorf("While staging writable file from %q to %q: %v", cp.src, cp.bind, err)
677 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
678 // Handle docker log protocol
679 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
680 defer close(runner.loggingDone)
682 header := make([]byte, 8)
685 _, err = io.ReadAtLeast(containerReader, header, 8)
692 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
695 _, err = io.CopyN(runner.Stdout, containerReader, readsize)
698 _, err = io.CopyN(runner.Stderr, containerReader, readsize)
703 runner.CrunchLog.Printf("error reading docker logs: %v", err)
706 err = runner.Stdout.Close()
708 runner.CrunchLog.Printf("error closing stdout logs: %v", err)
711 err = runner.Stderr.Close()
713 runner.CrunchLog.Printf("error closing stderr logs: %v", err)
716 if runner.statReporter != nil {
717 runner.statReporter.Stop()
718 err = runner.statLogger.Close()
720 runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
725 func (runner *ContainerRunner) stopHoststat() error {
726 if runner.hoststatReporter == nil {
729 runner.hoststatReporter.Stop()
730 err := runner.hoststatLogger.Close()
732 return fmt.Errorf("error closing hoststat logs: %v", err)
737 func (runner *ContainerRunner) startHoststat() error {
738 w, err := runner.NewLogWriter("hoststat")
742 runner.hoststatLogger = NewThrottledLogger(w)
743 runner.hoststatReporter = &crunchstat.Reporter{
744 Logger: log.New(runner.hoststatLogger, "", 0),
745 CgroupRoot: runner.cgroupRoot,
746 PollPeriod: runner.statInterval,
748 runner.hoststatReporter.Start()
752 func (runner *ContainerRunner) startCrunchstat() error {
753 w, err := runner.NewLogWriter("crunchstat")
757 runner.statLogger = NewThrottledLogger(w)
758 runner.statReporter = &crunchstat.Reporter{
759 CID: runner.ContainerID,
760 Logger: log.New(runner.statLogger, "", 0),
761 CgroupParent: runner.expectCgroupParent,
762 CgroupRoot: runner.cgroupRoot,
763 PollPeriod: runner.statInterval,
764 TempDir: runner.parentTemp,
766 runner.statReporter.Start()
770 type infoCommand struct {
775 // LogHostInfo logs info about the current host, for debugging and
776 // accounting purposes. Although it's logged as "node-info", this is
777 // about the environment where crunch-run is actually running, which
778 // might differ from what's described in the node record (see
780 func (runner *ContainerRunner) LogHostInfo() (err error) {
781 w, err := runner.NewLogWriter("node-info")
786 commands := []infoCommand{
788 label: "Host Information",
789 cmd: []string{"uname", "-a"},
792 label: "CPU Information",
793 cmd: []string{"cat", "/proc/cpuinfo"},
796 label: "Memory Information",
797 cmd: []string{"cat", "/proc/meminfo"},
801 cmd: []string{"df", "-m", "/", os.TempDir()},
804 label: "Disk INodes",
805 cmd: []string{"df", "-i", "/", os.TempDir()},
809 // Run commands with informational output to be logged.
810 for _, command := range commands {
811 fmt.Fprintln(w, command.label)
812 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
815 if err := cmd.Run(); err != nil {
816 err = fmt.Errorf("While running command %q: %v", command.cmd, err)
825 return fmt.Errorf("While closing node-info logs: %v", err)
830 // LogContainerRecord gets and saves the raw JSON container record from the API server
831 func (runner *ContainerRunner) LogContainerRecord() error {
832 logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
833 if !logged && err == nil {
834 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
839 // LogNodeRecord logs arvados#node record corresponding to the current host.
840 func (runner *ContainerRunner) LogNodeRecord() error {
841 hostname := os.Getenv("SLURMD_NODENAME")
843 hostname, _ = os.Hostname()
845 _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
846 // The "info" field has admin-only info when obtained
847 // with a privileged token, and should not be logged.
848 node, ok := resp.(map[string]interface{})
856 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
857 writer, err := runner.LogCollection.OpenFile(label+".json", os.O_CREATE|os.O_WRONLY, 0666)
862 ArvClient: runner.ArvClient,
863 UUID: runner.Container.UUID,
864 loggingStream: label,
868 reader, err := runner.ArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
870 return false, fmt.Errorf("error getting %s record: %v", label, err)
874 dec := json.NewDecoder(reader)
876 var resp map[string]interface{}
877 if err = dec.Decode(&resp); err != nil {
878 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
880 items, ok := resp["items"].([]interface{})
882 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
883 } else if len(items) < 1 {
889 // Re-encode it using indentation to improve readability
890 enc := json.NewEncoder(w)
891 enc.SetIndent("", " ")
892 if err = enc.Encode(items[0]); err != nil {
893 return false, fmt.Errorf("error logging %s record: %v", label, err)
897 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
902 // AttachStreams connects the docker container stdin, stdout and stderr logs
903 // to the Arvados logger which logs to Keep and the API server logs table.
904 func (runner *ContainerRunner) AttachStreams() (err error) {
906 runner.CrunchLog.Print("Attaching container streams")
908 // If stdin mount is provided, attach it to the docker container
909 var stdinRdr arvados.File
911 if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
912 if stdinMnt.Kind == "collection" {
913 var stdinColl arvados.Collection
914 collId := stdinMnt.UUID
916 collId = stdinMnt.PortableDataHash
918 err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
920 return fmt.Errorf("While getting stding collection: %v", err)
923 stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
924 if os.IsNotExist(err) {
925 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
926 } else if err != nil {
927 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
929 } else if stdinMnt.Kind == "json" {
930 stdinJson, err = json.Marshal(stdinMnt.Content)
932 return fmt.Errorf("While encoding stdin json data: %v", err)
937 stdinUsed := stdinRdr != nil || len(stdinJson) != 0
938 response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
939 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
941 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
944 runner.loggingDone = make(chan bool)
946 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
947 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
951 runner.Stdout = stdoutFile
952 } else if w, err := runner.NewLogWriter("stdout"); err != nil {
955 runner.Stdout = NewThrottledLogger(w)
958 if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
959 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
963 runner.Stderr = stderrFile
964 } else if w, err := runner.NewLogWriter("stderr"); err != nil {
967 runner.Stderr = NewThrottledLogger(w)
972 _, err := io.Copy(response.Conn, stdinRdr)
974 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
978 response.CloseWrite()
980 } else if len(stdinJson) != 0 {
982 _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
984 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
987 response.CloseWrite()
991 go runner.ProcessDockerAttach(response.Reader)
996 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
997 stdoutPath := mntPath[len(runner.Container.OutputPath):]
998 index := strings.LastIndex(stdoutPath, "/")
1000 subdirs := stdoutPath[:index]
1002 st, err := os.Stat(runner.HostOutputDir)
1004 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
1006 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
1007 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
1009 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
1013 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
1015 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
1018 return stdoutFile, nil
1021 // CreateContainer creates the docker container.
1022 func (runner *ContainerRunner) CreateContainer() error {
1023 runner.CrunchLog.Print("Creating Docker container")
1025 runner.ContainerConfig.Cmd = runner.Container.Command
1026 if runner.Container.Cwd != "." {
1027 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
1030 for k, v := range runner.Container.Environment {
1031 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
1034 runner.ContainerConfig.Volumes = runner.Volumes
1036 maxRAM := int64(runner.Container.RuntimeConstraints.RAM)
1037 if maxRAM < 4*1024*1024 {
1038 // Docker daemon won't let you set a limit less than 4 MiB
1039 maxRAM = 4 * 1024 * 1024
1041 runner.HostConfig = dockercontainer.HostConfig{
1042 Binds: runner.Binds,
1043 LogConfig: dockercontainer.LogConfig{
1046 Resources: dockercontainer.Resources{
1047 CgroupParent: runner.setCgroupParent,
1048 NanoCPUs: int64(runner.Container.RuntimeConstraints.VCPUs) * 1000000000,
1049 Memory: maxRAM, // RAM
1050 MemorySwap: maxRAM, // RAM+swap
1051 KernelMemory: maxRAM, // kernel portion
1055 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
1056 tok, err := runner.ContainerToken()
1060 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
1061 "ARVADOS_API_TOKEN="+tok,
1062 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
1063 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
1065 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
1067 if runner.enableNetwork == "always" {
1068 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
1070 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
1074 _, stdinUsed := runner.Container.Mounts["stdin"]
1075 runner.ContainerConfig.OpenStdin = stdinUsed
1076 runner.ContainerConfig.StdinOnce = stdinUsed
1077 runner.ContainerConfig.AttachStdin = stdinUsed
1078 runner.ContainerConfig.AttachStdout = true
1079 runner.ContainerConfig.AttachStderr = true
1081 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
1083 return fmt.Errorf("While creating container: %v", err)
1086 runner.ContainerID = createdBody.ID
1088 return runner.AttachStreams()
1091 // StartContainer starts the docker container created by CreateContainer.
1092 func (runner *ContainerRunner) StartContainer() error {
1093 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
1094 runner.cStateLock.Lock()
1095 defer runner.cStateLock.Unlock()
1096 if runner.cCancelled {
1099 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
1100 dockertypes.ContainerStartOptions{})
1103 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
1104 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])
1106 return fmt.Errorf("could not start container: %v%s", err, advice)
1111 // checkContainerd checks if "containerd" is present in the process list.
1112 func (runner *ContainerRunner) CheckContainerd() error {
1113 if runner.checkContainerd == 0 {
1116 p, _ := runner.ListProcesses()
1117 for _, i := range p {
1118 e, _ := i.CmdlineSlice()
1120 if strings.Index(e[0], "containerd") > -1 {
1127 runner.runBrokenNodeHook()
1129 return fmt.Errorf("'containerd' not found in process list.")
1132 // WaitFinish waits for the container to terminate, capture the exit code, and
1133 // close the stdout/stderr logging.
1134 func (runner *ContainerRunner) WaitFinish() error {
1135 var runTimeExceeded <-chan time.Time
1136 runner.CrunchLog.Print("Waiting for container to finish")
1138 waitOk, waitErr := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID, dockercontainer.WaitConditionNotRunning)
1139 arvMountExit := runner.ArvMountExit
1140 if timeout := runner.Container.SchedulingParameters.MaxRunTime; timeout > 0 {
1141 runTimeExceeded = time.After(time.Duration(timeout) * time.Second)
1144 containerGone := make(chan struct{})
1146 defer close(containerGone)
1147 if runner.containerWatchdogInterval < 1 {
1148 runner.containerWatchdogInterval = time.Minute
1150 for range time.NewTicker(runner.containerWatchdogInterval).C {
1151 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(runner.containerWatchdogInterval))
1152 ctr, err := runner.Docker.ContainerInspect(ctx, runner.ContainerID)
1154 runner.cStateLock.Lock()
1155 done := runner.cRemoved || runner.ExitCode != nil
1156 runner.cStateLock.Unlock()
1159 } else if err != nil {
1160 runner.CrunchLog.Printf("Error inspecting container: %s", err)
1161 runner.checkBrokenNode(err)
1163 } else if ctr.State == nil || !(ctr.State.Running || ctr.State.Status == "created") {
1164 runner.CrunchLog.Printf("Container is not running: State=%v", ctr.State)
1170 containerdGone := make(chan error)
1171 defer close(containerdGone)
1172 if runner.checkContainerd > 0 {
1174 ticker := time.NewTicker(time.Duration(runner.checkContainerd))
1179 if ck := runner.CheckContainerd(); ck != nil {
1180 containerdGone <- ck
1183 case <-containerdGone:
1184 // Channel closed, quit goroutine
1193 case waitBody := <-waitOk:
1194 runner.CrunchLog.Printf("Container exited with code: %v", waitBody.StatusCode)
1195 code := int(waitBody.StatusCode)
1196 runner.ExitCode = &code
1198 // wait for stdout/stderr to complete
1199 <-runner.loggingDone
1202 case err := <-waitErr:
1203 return fmt.Errorf("container wait: %v", err)
1205 case <-arvMountExit:
1206 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
1208 // arvMountExit will always be ready now that
1209 // it's closed, but that doesn't interest us.
1212 case <-runTimeExceeded:
1213 runner.CrunchLog.Printf("maximum run time exceeded. Stopping container.")
1215 runTimeExceeded = nil
1217 case <-containerGone:
1218 return errors.New("docker client never returned status")
1220 case err := <-containerdGone:
1226 func (runner *ContainerRunner) updateLogs() {
1227 ticker := time.NewTicker(crunchLogUpdatePeriod / 360)
1230 sigusr1 := make(chan os.Signal, 1)
1231 signal.Notify(sigusr1, syscall.SIGUSR1)
1232 defer signal.Stop(sigusr1)
1234 saveAtTime := time.Now().Add(crunchLogUpdatePeriod)
1235 saveAtSize := crunchLogUpdateSize
1241 saveAtTime = time.Now()
1243 runner.logMtx.Lock()
1244 done := runner.LogsPDH != nil
1245 runner.logMtx.Unlock()
1249 size := runner.LogCollection.Size()
1250 if size == savedSize || (time.Now().Before(saveAtTime) && size < saveAtSize) {
1253 saveAtTime = time.Now().Add(crunchLogUpdatePeriod)
1254 saveAtSize = runner.LogCollection.Size() + crunchLogUpdateSize
1255 saved, err := runner.saveLogCollection(false)
1257 runner.CrunchLog.Printf("error updating log collection: %s", err)
1261 var updated arvados.Container
1262 err = runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1263 "container": arvadosclient.Dict{"log": saved.PortableDataHash},
1266 runner.CrunchLog.Printf("error updating container log to %s: %s", saved.PortableDataHash, err)
1274 // CaptureOutput saves data from the container's output directory if
1275 // needed, and updates the container output accordingly.
1276 func (runner *ContainerRunner) CaptureOutput() error {
1277 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
1278 // Output may have been set directly by the container, so
1279 // refresh the container record to check.
1280 err := runner.ArvClient.Get("containers", runner.Container.UUID,
1281 nil, &runner.Container)
1285 if runner.Container.Output != "" {
1286 // Container output is already set.
1287 runner.OutputPDH = &runner.Container.Output
1292 txt, err := (&copier{
1293 client: runner.client,
1294 arvClient: runner.ArvClient,
1295 keepClient: runner.Kc,
1296 hostOutputDir: runner.HostOutputDir,
1297 ctrOutputDir: runner.Container.OutputPath,
1298 binds: runner.Binds,
1299 mounts: runner.Container.Mounts,
1300 secretMounts: runner.SecretMounts,
1301 logger: runner.CrunchLog,
1306 if n := len(regexp.MustCompile(` [0-9a-f]+\+\S*\+R`).FindAllStringIndex(txt, -1)); n > 0 {
1307 runner.CrunchLog.Printf("Copying %d data blocks from remote input collections...", n)
1308 fs, err := (&arvados.Collection{ManifestText: txt}).FileSystem(runner.client, runner.Kc)
1312 txt, err = fs.MarshalManifest(".")
1317 var resp arvados.Collection
1318 err = runner.ArvClient.Create("collections", arvadosclient.Dict{
1319 "ensure_unique_name": true,
1320 "collection": arvadosclient.Dict{
1322 "name": "output for " + runner.Container.UUID,
1323 "manifest_text": txt,
1327 return fmt.Errorf("error creating output collection: %v", err)
1329 runner.OutputPDH = &resp.PortableDataHash
1333 func (runner *ContainerRunner) CleanupDirs() {
1334 if runner.ArvMount != nil {
1336 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1337 umount.Stdout = runner.CrunchLog
1338 umount.Stderr = runner.CrunchLog
1339 runner.CrunchLog.Printf("Running %v", umount.Args)
1340 umnterr := umount.Start()
1343 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1345 // If arv-mount --unmount gets stuck for any reason, we
1346 // don't want to wait for it forever. Do Wait() in a goroutine
1347 // so it doesn't block crunch-run.
1348 umountExit := make(chan error)
1350 mnterr := umount.Wait()
1352 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1354 umountExit <- mnterr
1357 for again := true; again; {
1363 case <-runner.ArvMountExit:
1365 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1366 runner.CrunchLog.Printf("Timed out waiting for unmount")
1368 umount.Process.Kill()
1370 runner.ArvMount.Process.Kill()
1376 if runner.ArvMountPoint != "" {
1377 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1378 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1382 if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1383 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1387 // CommitLogs posts the collection containing the final container logs.
1388 func (runner *ContainerRunner) CommitLogs() error {
1390 // Hold cStateLock to prevent races on CrunchLog (e.g., stop()).
1391 runner.cStateLock.Lock()
1392 defer runner.cStateLock.Unlock()
1394 runner.CrunchLog.Print(runner.finalState)
1396 if runner.arvMountLog != nil {
1397 runner.arvMountLog.Close()
1399 runner.CrunchLog.Close()
1401 // Closing CrunchLog above allows them to be committed to Keep at this
1402 // point, but re-open crunch log with ArvClient in case there are any
1403 // other further errors (such as failing to write the log to Keep!)
1404 // while shutting down
1405 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{
1406 ArvClient: runner.ArvClient,
1407 UUID: runner.Container.UUID,
1408 loggingStream: "crunch-run",
1411 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1414 if runner.LogsPDH != nil {
1415 // If we have already assigned something to LogsPDH,
1416 // we must be closing the re-opened log, which won't
1417 // end up getting attached to the container record and
1418 // therefore doesn't need to be saved as a collection
1419 // -- it exists only to send logs to other channels.
1422 saved, err := runner.saveLogCollection(true)
1424 return fmt.Errorf("error saving log collection: %s", err)
1426 runner.logMtx.Lock()
1427 defer runner.logMtx.Unlock()
1428 runner.LogsPDH = &saved.PortableDataHash
1432 func (runner *ContainerRunner) saveLogCollection(final bool) (response arvados.Collection, err error) {
1433 runner.logMtx.Lock()
1434 defer runner.logMtx.Unlock()
1435 if runner.LogsPDH != nil {
1436 // Already finalized.
1439 mt, err := runner.LogCollection.MarshalManifest(".")
1441 err = fmt.Errorf("error creating log manifest: %v", err)
1444 updates := arvadosclient.Dict{
1445 "name": "logs for " + runner.Container.UUID,
1446 "manifest_text": mt,
1449 updates["is_trashed"] = true
1451 exp := time.Now().Add(crunchLogUpdatePeriod * 24)
1452 updates["trash_at"] = exp
1453 updates["delete_at"] = exp
1455 reqBody := arvadosclient.Dict{"collection": updates}
1456 if runner.logUUID == "" {
1457 reqBody["ensure_unique_name"] = true
1458 err = runner.ArvClient.Create("collections", reqBody, &response)
1460 err = runner.ArvClient.Update("collections", runner.logUUID, reqBody, &response)
1465 runner.logUUID = response.UUID
1469 // UpdateContainerRunning updates the container state to "Running"
1470 func (runner *ContainerRunner) UpdateContainerRunning() error {
1471 runner.cStateLock.Lock()
1472 defer runner.cStateLock.Unlock()
1473 if runner.cCancelled {
1476 return runner.ArvClient.Update("containers", runner.Container.UUID,
1477 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1480 // ContainerToken returns the api_token the container (and any
1481 // arv-mount processes) are allowed to use.
1482 func (runner *ContainerRunner) ContainerToken() (string, error) {
1483 if runner.token != "" {
1484 return runner.token, nil
1487 var auth arvados.APIClientAuthorization
1488 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1492 runner.token = fmt.Sprintf("v2/%s/%s/%s", auth.UUID, auth.APIToken, runner.Container.UUID)
1493 return runner.token, nil
1496 // UpdateContainerComplete updates the container record state on API
1497 // server to "Complete" or "Cancelled"
1498 func (runner *ContainerRunner) UpdateContainerFinal() error {
1499 update := arvadosclient.Dict{}
1500 update["state"] = runner.finalState
1501 if runner.LogsPDH != nil {
1502 update["log"] = *runner.LogsPDH
1504 if runner.finalState == "Complete" {
1505 if runner.ExitCode != nil {
1506 update["exit_code"] = *runner.ExitCode
1508 if runner.OutputPDH != nil {
1509 update["output"] = *runner.OutputPDH
1512 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1515 // IsCancelled returns the value of Cancelled, with goroutine safety.
1516 func (runner *ContainerRunner) IsCancelled() bool {
1517 runner.cStateLock.Lock()
1518 defer runner.cStateLock.Unlock()
1519 return runner.cCancelled
1522 // NewArvLogWriter creates an ArvLogWriter
1523 func (runner *ContainerRunner) NewArvLogWriter(name string) (io.WriteCloser, error) {
1524 writer, err := runner.LogCollection.OpenFile(name+".txt", os.O_CREATE|os.O_WRONLY, 0666)
1528 return &ArvLogWriter{
1529 ArvClient: runner.ArvClient,
1530 UUID: runner.Container.UUID,
1531 loggingStream: name,
1532 writeCloser: writer,
1536 // Run the full container lifecycle.
1537 func (runner *ContainerRunner) Run() (err error) {
1538 runner.CrunchLog.Printf("crunch-run %s started", version)
1539 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1541 hostname, hosterr := os.Hostname()
1543 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1545 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1548 runner.finalState = "Queued"
1551 runner.CleanupDirs()
1553 runner.CrunchLog.Printf("crunch-run finished")
1554 runner.CrunchLog.Close()
1558 // checkErr prints e (unless it's nil) and sets err to
1559 // e (unless err is already non-nil). Thus, if err
1560 // hasn't already been assigned when Run() returns,
1561 // this cleanup func will cause Run() to return the
1562 // first non-nil error that is passed to checkErr().
1563 checkErr := func(errorIn string, e error) {
1567 runner.CrunchLog.Printf("error in %s: %v", errorIn, e)
1571 if runner.finalState == "Complete" {
1572 // There was an error in the finalization.
1573 runner.finalState = "Cancelled"
1577 // Log the error encountered in Run(), if any
1578 checkErr("Run", err)
1580 if runner.finalState == "Queued" {
1581 runner.UpdateContainerFinal()
1585 if runner.IsCancelled() {
1586 runner.finalState = "Cancelled"
1587 // but don't return yet -- we still want to
1588 // capture partial output and write logs
1591 checkErr("CaptureOutput", runner.CaptureOutput())
1592 checkErr("stopHoststat", runner.stopHoststat())
1593 checkErr("CommitLogs", runner.CommitLogs())
1594 checkErr("UpdateContainerFinal", runner.UpdateContainerFinal())
1597 err = runner.fetchContainerRecord()
1601 runner.setupSignals()
1602 err = runner.startHoststat()
1607 // Sanity check that containerd is running.
1608 err = runner.CheckContainerd()
1613 // check for and/or load image
1614 err = runner.LoadImage()
1616 if !runner.checkBrokenNode(err) {
1617 // Failed to load image but not due to a "broken node"
1618 // condition, probably user error.
1619 runner.finalState = "Cancelled"
1621 err = fmt.Errorf("While loading container image: %v", err)
1625 // set up FUSE mount and binds
1626 err = runner.SetupMounts()
1628 runner.finalState = "Cancelled"
1629 err = fmt.Errorf("While setting up mounts: %v", err)
1633 err = runner.CreateContainer()
1637 err = runner.LogHostInfo()
1641 err = runner.LogNodeRecord()
1645 err = runner.LogContainerRecord()
1650 if runner.IsCancelled() {
1654 err = runner.UpdateContainerRunning()
1658 runner.finalState = "Cancelled"
1660 err = runner.startCrunchstat()
1665 err = runner.StartContainer()
1667 runner.checkBrokenNode(err)
1671 err = runner.WaitFinish()
1672 if err == nil && !runner.IsCancelled() {
1673 runner.finalState = "Complete"
1678 // Fetch the current container record (uuid = runner.Container.UUID)
1679 // into runner.Container.
1680 func (runner *ContainerRunner) fetchContainerRecord() error {
1681 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1683 return fmt.Errorf("error fetching container record: %v", err)
1685 defer reader.Close()
1687 dec := json.NewDecoder(reader)
1689 err = dec.Decode(&runner.Container)
1691 return fmt.Errorf("error decoding container record: %v", err)
1695 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
1698 containerToken, err := runner.ContainerToken()
1700 return fmt.Errorf("error getting container token: %v", err)
1703 containerClient, _, err := runner.MkArvClient(containerToken)
1705 return fmt.Errorf("error creating container API client: %v", err)
1708 err = containerClient.Call("GET", "containers", runner.Container.UUID, "secret_mounts", nil, &sm)
1710 if apierr, ok := err.(arvadosclient.APIServerError); !ok || apierr.HttpStatusCode != 404 {
1711 return fmt.Errorf("error fetching secret_mounts: %v", err)
1713 // ok && apierr.HttpStatusCode == 404, which means
1714 // secret_mounts isn't supported by this API server.
1716 runner.SecretMounts = sm.SecretMounts
1721 // NewContainerRunner creates a new container runner.
1722 func NewContainerRunner(client *arvados.Client, api IArvadosClient, kc IKeepClient, docker ThinDockerClient, containerUUID string) (*ContainerRunner, error) {
1723 cr := &ContainerRunner{
1729 cr.NewLogWriter = cr.NewArvLogWriter
1730 cr.RunArvMount = cr.ArvMountCmd
1731 cr.MkTempDir = ioutil.TempDir
1732 cr.ListProcesses = func() ([]PsProcess, error) {
1733 pr, err := process.Processes()
1737 ps := make([]PsProcess, len(pr))
1738 for i, j := range pr {
1743 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, error) {
1744 cl, err := arvadosclient.MakeArvadosClient()
1746 return nil, nil, err
1749 kc, err := keepclient.MakeKeepClient(cl)
1751 return nil, nil, err
1756 cr.LogCollection, err = (&arvados.Collection{}).FileSystem(cr.client, cr.Kc)
1760 cr.Container.UUID = containerUUID
1761 w, err := cr.NewLogWriter("crunch-run")
1765 cr.CrunchLog = NewThrottledLogger(w)
1766 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1768 loadLogThrottleParams(api)
1775 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1776 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1777 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1778 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1779 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1780 enableNetwork := flag.String("container-enable-networking", "default",
1781 `Specify if networking should be enabled for container. One of 'default', 'always':
1782 default: only enable networking if container requests it.
1783 always: containers always have networking enabled
1785 networkMode := flag.String("container-network-mode", "default",
1786 `Set networking mode for container. Corresponds to Docker network mode (--net).
1788 memprofile := flag.String("memprofile", "", "write memory profile to `file` after running container")
1789 getVersion := flag.Bool("version", false, "Print version information and exit.")
1790 checkContainerd := flag.Duration("check-containerd", 60*time.Second, "Periodic check if (docker-)containerd is running (use 0s to disable).")
1793 // Print version information if requested
1795 fmt.Printf("crunch-run %s\n", version)
1799 log.Printf("crunch-run %s started", version)
1801 containerId := flag.Arg(0)
1803 if *caCertsPath != "" {
1804 arvadosclient.CertFiles = []string{*caCertsPath}
1807 api, err := arvadosclient.MakeArvadosClient()
1809 log.Fatalf("%s: %v", containerId, err)
1813 kc, kcerr := keepclient.MakeKeepClient(api)
1815 log.Fatalf("%s: %v", containerId, kcerr)
1817 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1820 // API version 1.21 corresponds to Docker 1.9, which is currently the
1821 // minimum version we want to support.
1822 docker, dockererr := dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1824 cr, err := NewContainerRunner(arvados.NewClientFromEnv(), api, kc, docker, containerId)
1828 if dockererr != nil {
1829 cr.CrunchLog.Printf("%s: %v", containerId, dockererr)
1830 cr.checkBrokenNode(dockererr)
1831 cr.CrunchLog.Close()
1835 parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerId+".")
1837 log.Fatalf("%s: %v", containerId, tmperr)
1840 cr.parentTemp = parentTemp
1841 cr.statInterval = *statInterval
1842 cr.cgroupRoot = *cgroupRoot
1843 cr.expectCgroupParent = *cgroupParent
1844 cr.enableNetwork = *enableNetwork
1845 cr.networkMode = *networkMode
1846 cr.checkContainerd = *checkContainerd
1847 if *cgroupParentSubsystem != "" {
1848 p := findCgroup(*cgroupParentSubsystem)
1849 cr.setCgroupParent = p
1850 cr.expectCgroupParent = p
1855 if *memprofile != "" {
1856 f, err := os.Create(*memprofile)
1858 log.Printf("could not create memory profile: %s", err)
1860 runtime.GC() // get up-to-date statistics
1861 if err := pprof.WriteHeapProfile(f); err != nil {
1862 log.Printf("could not write memory profile: %s", err)
1864 closeerr := f.Close()
1865 if closeerr != nil {
1866 log.Printf("closing memprofile file: %s", err)
1871 log.Fatalf("%s: %v", containerId, runerr)