1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
30 "git.arvados.org/arvados.git/lib/cmd"
31 "git.arvados.org/arvados.git/lib/crunchstat"
32 "git.arvados.org/arvados.git/sdk/go/arvados"
33 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
34 "git.arvados.org/arvados.git/sdk/go/keepclient"
35 "git.arvados.org/arvados.git/sdk/go/manifest"
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 var Command = command{}
48 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
49 type IArvadosClient interface {
50 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
51 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
52 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
53 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
54 CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
55 Discovery(key string) (interface{}, error)
58 // ErrCancelled is the error returned when the container is cancelled.
59 var ErrCancelled = errors.New("Cancelled")
61 // IKeepClient is the minimal Keep API methods used by crunch-run.
62 type IKeepClient interface {
63 PutB(buf []byte) (string, int, error)
64 ReadAt(locator string, p []byte, off int) (int, error)
65 ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error)
66 LocalLocator(locator string) (string, error)
70 // NewLogWriter is a factory function to create a new log writer.
71 type NewLogWriter func(name string) (io.WriteCloser, error)
73 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
75 type MkTempDir func(string, string) (string, error)
77 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
78 type ThinDockerClient interface {
79 ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error)
80 ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
81 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error)
82 ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error
83 ContainerRemove(ctx context.Context, container string, options dockertypes.ContainerRemoveOptions) error
84 ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error)
85 ContainerInspect(ctx context.Context, id string) (dockertypes.ContainerJSON, error)
86 ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error)
87 ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error)
88 ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error)
91 type PsProcess interface {
92 CmdlineSlice() ([]string, error)
95 // ContainerRunner is the main stateful struct used for a single execution of a
97 type ContainerRunner struct {
98 Docker ThinDockerClient
100 // Dispatcher client is initialized with the Dispatcher token.
101 // This is a privileged token used to manage container status
104 // We have both dispatcherClient and DispatcherArvClient
105 // because there are two different incompatible Arvados Go
106 // SDKs and we have to use both (hopefully this gets fixed in
108 dispatcherClient *arvados.Client
109 DispatcherArvClient IArvadosClient
110 DispatcherKeepClient IKeepClient
112 // Container client is initialized with the Container token
113 // This token controls the permissions of the container, and
114 // must be used for operations such as reading collections.
116 // Same comment as above applies to
117 // containerClient/ContainerArvClient.
118 containerClient *arvados.Client
119 ContainerArvClient IArvadosClient
120 ContainerKeepClient IKeepClient
122 Container arvados.Container
123 ContainerConfig dockercontainer.Config
124 HostConfig dockercontainer.HostConfig
128 NewLogWriter NewLogWriter
129 loggingDone chan bool
130 CrunchLog *ThrottledLogger
131 Stdout io.WriteCloser
132 Stderr io.WriteCloser
135 LogCollection arvados.CollectionFileSystem
137 RunArvMount RunArvMount
143 Volumes map[string]struct{}
145 SigChan chan os.Signal
146 ArvMountExit chan error
147 SecretMounts map[string]arvados.Mount
148 MkArvClient func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error)
152 statLogger io.WriteCloser
153 statReporter *crunchstat.Reporter
154 hoststatLogger io.WriteCloser
155 hoststatReporter *crunchstat.Reporter
156 statInterval time.Duration
158 // What we expect the container's cgroup parent to be.
159 expectCgroupParent string
160 // What we tell docker to use as the container's cgroup
161 // parent. Note: Ideally we would use the same field for both
162 // expectCgroupParent and setCgroupParent, and just make it
163 // default to "docker". However, when using docker < 1.10 with
164 // systemd, specifying a non-empty cgroup parent (even the
165 // default value "docker") hits a docker bug
166 // (https://github.com/docker/docker/issues/17126). Using two
167 // separate fields makes it possible to use the "expect cgroup
168 // parent to be X" feature even on sites where the "specify
169 // cgroup parent" feature breaks.
170 setCgroupParent string
172 cStateLock sync.Mutex
173 cCancelled bool // StopContainer() invoked
174 cRemoved bool // docker confirmed the container no longer exists
176 enableNetwork string // one of "default" or "always"
177 networkMode string // passed through to HostConfig.NetworkMode
178 arvMountLog *ThrottledLogger
180 containerWatchdogInterval time.Duration
185 // setupSignals sets up signal handling to gracefully terminate the underlying
186 // Docker container and update state when receiving a TERM, INT or QUIT signal.
187 func (runner *ContainerRunner) setupSignals() {
188 runner.SigChan = make(chan os.Signal, 1)
189 signal.Notify(runner.SigChan, syscall.SIGTERM)
190 signal.Notify(runner.SigChan, syscall.SIGINT)
191 signal.Notify(runner.SigChan, syscall.SIGQUIT)
193 go func(sig chan os.Signal) {
200 // stop the underlying Docker container.
201 func (runner *ContainerRunner) stop(sig os.Signal) {
202 runner.cStateLock.Lock()
203 defer runner.cStateLock.Unlock()
205 runner.CrunchLog.Printf("caught signal: %v", sig)
207 if runner.ContainerID == "" {
210 runner.cCancelled = true
211 runner.CrunchLog.Printf("removing container")
212 err := runner.Docker.ContainerRemove(context.TODO(), runner.ContainerID, dockertypes.ContainerRemoveOptions{Force: true})
214 runner.CrunchLog.Printf("error removing container: %s", err)
216 if err == nil || strings.Contains(err.Error(), "No such container: "+runner.ContainerID) {
217 runner.cRemoved = true
221 var errorBlacklist = []string{
222 "(?ms).*[Cc]annot connect to the Docker daemon.*",
223 "(?ms).*oci runtime error.*starting container process.*container init.*mounting.*to rootfs.*no such file or directory.*",
224 "(?ms).*grpc: the connection is unavailable.*",
226 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)")
228 func (runner *ContainerRunner) runBrokenNodeHook() {
229 if *brokenNodeHook == "" {
230 path := filepath.Join(lockdir, brokenfile)
231 runner.CrunchLog.Printf("Writing %s to mark node as broken", path)
232 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0700)
234 runner.CrunchLog.Printf("Error writing %s: %s", path, err)
239 runner.CrunchLog.Printf("Running broken node hook %q", *brokenNodeHook)
241 c := exec.Command(*brokenNodeHook)
242 c.Stdout = runner.CrunchLog
243 c.Stderr = runner.CrunchLog
246 runner.CrunchLog.Printf("Error running broken node hook: %v", err)
251 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
252 for _, d := range errorBlacklist {
253 if m, e := regexp.MatchString(d, goterr.Error()); m && e == nil {
254 runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
255 runner.runBrokenNodeHook()
262 // LoadImage determines the docker image id from the container record and
263 // checks if it is available in the local Docker image store. If not, it loads
264 // the image from Keep.
265 func (runner *ContainerRunner) LoadImage() (err error) {
267 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
269 var collection arvados.Collection
270 err = runner.ContainerArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
272 return fmt.Errorf("While getting container image collection: %v", err)
274 manifest := manifest.Manifest{Text: collection.ManifestText}
275 var img, imageID string
276 for ms := range manifest.StreamIter() {
277 img = ms.FileStreamSegments[0].Name
278 if !strings.HasSuffix(img, ".tar") {
279 return fmt.Errorf("First file in the container image collection does not end in .tar")
281 imageID = img[:len(img)-4]
284 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
286 _, _, err = runner.Docker.ImageInspectWithRaw(context.TODO(), imageID)
288 runner.CrunchLog.Print("Loading Docker image from keep")
290 var readCloser io.ReadCloser
291 readCloser, err = runner.ContainerKeepClient.ManifestFileReader(manifest, img)
293 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
296 response, err := runner.Docker.ImageLoad(context.TODO(), readCloser, true)
298 return fmt.Errorf("While loading container image into Docker: %v", err)
301 defer response.Body.Close()
302 rbody, err := ioutil.ReadAll(response.Body)
304 return fmt.Errorf("Reading response to image load: %v", err)
306 runner.CrunchLog.Printf("Docker response: %s", rbody)
308 runner.CrunchLog.Print("Docker image is available")
311 runner.ContainerConfig.Image = imageID
313 runner.ContainerKeepClient.ClearBlockCache()
318 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
319 c = exec.Command("arv-mount", arvMountCmd...)
321 // Copy our environment, but override ARVADOS_API_TOKEN with
322 // the container auth token.
324 for _, s := range os.Environ() {
325 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
326 c.Env = append(c.Env, s)
329 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
331 w, err := runner.NewLogWriter("arv-mount")
335 runner.arvMountLog = NewThrottledLogger(w)
336 c.Stdout = runner.arvMountLog
337 c.Stderr = runner.arvMountLog
339 runner.CrunchLog.Printf("Running %v", c.Args)
346 statReadme := make(chan bool)
347 runner.ArvMountExit = make(chan error)
352 time.Sleep(100 * time.Millisecond)
353 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
365 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
367 runner.ArvMountExit <- mnterr
368 close(runner.ArvMountExit)
374 case err := <-runner.ArvMountExit:
375 runner.ArvMount = nil
383 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
384 if runner.ArvMountPoint == "" {
385 runner.ArvMountPoint, err = runner.MkTempDir(runner.parentTemp, prefix)
390 func copyfile(src string, dst string) (err error) {
391 srcfile, err := os.Open(src)
396 os.MkdirAll(path.Dir(dst), 0777)
398 dstfile, err := os.Create(dst)
402 _, err = io.Copy(dstfile, srcfile)
407 err = srcfile.Close()
408 err2 := dstfile.Close()
421 func (runner *ContainerRunner) SetupMounts() (err error) {
422 err = runner.SetupArvMountPoint("keep")
424 return fmt.Errorf("While creating keep mount temp dir: %v", err)
427 token, err := runner.ContainerToken()
429 return fmt.Errorf("could not get container token: %s", err)
434 arvMountCmd := []string{
438 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
440 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
441 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
444 collectionPaths := []string{}
446 runner.Volumes = make(map[string]struct{})
447 needCertMount := true
448 type copyFile struct {
452 var copyFiles []copyFile
455 for bind := range runner.Container.Mounts {
456 binds = append(binds, bind)
458 for bind := range runner.SecretMounts {
459 if _, ok := runner.Container.Mounts[bind]; ok {
460 return fmt.Errorf("secret mount %q conflicts with regular mount", bind)
462 if runner.SecretMounts[bind].Kind != "json" &&
463 runner.SecretMounts[bind].Kind != "text" {
464 return fmt.Errorf("secret mount %q type is %q but only 'json' and 'text' are permitted",
465 bind, runner.SecretMounts[bind].Kind)
467 binds = append(binds, bind)
471 for _, bind := range binds {
472 mnt, ok := runner.Container.Mounts[bind]
474 mnt = runner.SecretMounts[bind]
476 if bind == "stdout" || bind == "stderr" {
477 // Is it a "file" mount kind?
478 if mnt.Kind != "file" {
479 return fmt.Errorf("unsupported mount kind '%s' for %s: only 'file' is supported", mnt.Kind, bind)
482 // Does path start with OutputPath?
483 prefix := runner.Container.OutputPath
484 if !strings.HasSuffix(prefix, "/") {
487 if !strings.HasPrefix(mnt.Path, prefix) {
488 return fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
493 // Is it a "collection" mount kind?
494 if mnt.Kind != "collection" && mnt.Kind != "json" {
495 return fmt.Errorf("unsupported mount kind '%s' for stdin: only 'collection' and 'json' are supported", mnt.Kind)
499 if bind == "/etc/arvados/ca-certificates.crt" {
500 needCertMount = false
503 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
504 if mnt.Kind != "collection" && mnt.Kind != "text" && mnt.Kind != "json" {
505 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)
510 case mnt.Kind == "collection" && bind != "stdin":
512 if mnt.UUID != "" && mnt.PortableDataHash != "" {
513 return fmt.Errorf("cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
517 return fmt.Errorf("writing to existing collections currently not permitted")
520 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
521 } else if mnt.PortableDataHash != "" {
522 if mnt.Writable && !strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
523 return fmt.Errorf("can never write to a collection specified by portable data hash")
525 idx := strings.Index(mnt.PortableDataHash, "/")
527 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
528 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
529 runner.Container.Mounts[bind] = mnt
531 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
532 if mnt.Path != "" && mnt.Path != "." {
533 if strings.HasPrefix(mnt.Path, "./") {
534 mnt.Path = mnt.Path[2:]
535 } else if strings.HasPrefix(mnt.Path, "/") {
536 mnt.Path = mnt.Path[1:]
538 src += "/" + mnt.Path
541 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
542 arvMountCmd = append(arvMountCmd, "--mount-tmp")
543 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
547 if bind == runner.Container.OutputPath {
548 runner.HostOutputDir = src
549 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
550 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
551 copyFiles = append(copyFiles, copyFile{src, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
553 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
556 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
558 collectionPaths = append(collectionPaths, src)
560 case mnt.Kind == "tmp":
562 tmpdir, err = runner.MkTempDir(runner.parentTemp, "tmp")
564 return fmt.Errorf("while creating mount temp dir: %v", err)
566 st, staterr := os.Stat(tmpdir)
568 return fmt.Errorf("while Stat on temp dir: %v", staterr)
570 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
572 return fmt.Errorf("while Chmod temp dir: %v", err)
574 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", tmpdir, bind))
575 if bind == runner.Container.OutputPath {
576 runner.HostOutputDir = tmpdir
579 case mnt.Kind == "json" || mnt.Kind == "text":
581 if mnt.Kind == "json" {
582 filedata, err = json.Marshal(mnt.Content)
584 return fmt.Errorf("encoding json data: %v", err)
587 text, ok := mnt.Content.(string)
589 return fmt.Errorf("content for mount %q must be a string", bind)
591 filedata = []byte(text)
594 tmpdir, err := runner.MkTempDir(runner.parentTemp, mnt.Kind)
596 return fmt.Errorf("creating temp dir: %v", err)
598 tmpfn := filepath.Join(tmpdir, "mountdata."+mnt.Kind)
599 err = ioutil.WriteFile(tmpfn, filedata, 0444)
601 return fmt.Errorf("writing temp file: %v", err)
603 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
604 copyFiles = append(copyFiles, copyFile{tmpfn, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
606 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
609 case mnt.Kind == "git_tree":
610 tmpdir, err := runner.MkTempDir(runner.parentTemp, "git_tree")
612 return fmt.Errorf("creating temp dir: %v", err)
614 err = gitMount(mnt).extractTree(runner.ContainerArvClient, tmpdir, token)
618 runner.Binds = append(runner.Binds, tmpdir+":"+bind+":ro")
622 if runner.HostOutputDir == "" {
623 return fmt.Errorf("output path does not correspond to a writable mount point")
626 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
627 for _, certfile := range arvadosclient.CertFiles {
628 _, err := os.Stat(certfile)
630 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
637 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
639 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
641 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
643 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
645 return fmt.Errorf("while trying to start arv-mount: %v", err)
648 for _, p := range collectionPaths {
651 return fmt.Errorf("while checking that input files exist: %v", err)
655 for _, cp := range copyFiles {
656 st, err := os.Stat(cp.src)
658 return fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
661 err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
665 target := path.Join(cp.bind, walkpath[len(cp.src):])
666 if walkinfo.Mode().IsRegular() {
667 copyerr := copyfile(walkpath, target)
671 return os.Chmod(target, walkinfo.Mode()|0777)
672 } else if walkinfo.Mode().IsDir() {
673 mkerr := os.MkdirAll(target, 0777)
677 return os.Chmod(target, walkinfo.Mode()|os.ModeSetgid|0777)
679 return fmt.Errorf("source %q is not a regular file or directory", cp.src)
682 } else if st.Mode().IsRegular() {
683 err = copyfile(cp.src, cp.bind)
685 err = os.Chmod(cp.bind, st.Mode()|0777)
689 return fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
696 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
697 // Handle docker log protocol
698 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
699 defer close(runner.loggingDone)
701 header := make([]byte, 8)
704 _, err = io.ReadAtLeast(containerReader, header, 8)
711 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
714 _, err = io.CopyN(runner.Stdout, containerReader, readsize)
717 _, err = io.CopyN(runner.Stderr, containerReader, readsize)
722 runner.CrunchLog.Printf("error reading docker logs: %v", err)
725 err = runner.Stdout.Close()
727 runner.CrunchLog.Printf("error closing stdout logs: %v", err)
730 err = runner.Stderr.Close()
732 runner.CrunchLog.Printf("error closing stderr logs: %v", err)
735 if runner.statReporter != nil {
736 runner.statReporter.Stop()
737 err = runner.statLogger.Close()
739 runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
744 func (runner *ContainerRunner) stopHoststat() error {
745 if runner.hoststatReporter == nil {
748 runner.hoststatReporter.Stop()
749 err := runner.hoststatLogger.Close()
751 return fmt.Errorf("error closing hoststat logs: %v", err)
756 func (runner *ContainerRunner) startHoststat() error {
757 w, err := runner.NewLogWriter("hoststat")
761 runner.hoststatLogger = NewThrottledLogger(w)
762 runner.hoststatReporter = &crunchstat.Reporter{
763 Logger: log.New(runner.hoststatLogger, "", 0),
764 CgroupRoot: runner.cgroupRoot,
765 PollPeriod: runner.statInterval,
767 runner.hoststatReporter.Start()
771 func (runner *ContainerRunner) startCrunchstat() error {
772 w, err := runner.NewLogWriter("crunchstat")
776 runner.statLogger = NewThrottledLogger(w)
777 runner.statReporter = &crunchstat.Reporter{
778 CID: runner.ContainerID,
779 Logger: log.New(runner.statLogger, "", 0),
780 CgroupParent: runner.expectCgroupParent,
781 CgroupRoot: runner.cgroupRoot,
782 PollPeriod: runner.statInterval,
783 TempDir: runner.parentTemp,
785 runner.statReporter.Start()
789 type infoCommand struct {
794 // LogHostInfo logs info about the current host, for debugging and
795 // accounting purposes. Although it's logged as "node-info", this is
796 // about the environment where crunch-run is actually running, which
797 // might differ from what's described in the node record (see
799 func (runner *ContainerRunner) LogHostInfo() (err error) {
800 w, err := runner.NewLogWriter("node-info")
805 commands := []infoCommand{
807 label: "Host Information",
808 cmd: []string{"uname", "-a"},
811 label: "CPU Information",
812 cmd: []string{"cat", "/proc/cpuinfo"},
815 label: "Memory Information",
816 cmd: []string{"cat", "/proc/meminfo"},
820 cmd: []string{"df", "-m", "/", os.TempDir()},
823 label: "Disk INodes",
824 cmd: []string{"df", "-i", "/", os.TempDir()},
828 // Run commands with informational output to be logged.
829 for _, command := range commands {
830 fmt.Fprintln(w, command.label)
831 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
834 if err := cmd.Run(); err != nil {
835 err = fmt.Errorf("While running command %q: %v", command.cmd, err)
844 return fmt.Errorf("While closing node-info logs: %v", err)
849 // LogContainerRecord gets and saves the raw JSON container record from the API server
850 func (runner *ContainerRunner) LogContainerRecord() error {
851 logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
852 if !logged && err == nil {
853 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
858 // LogNodeRecord logs the current host's InstanceType config entry (or
859 // the arvados#node record, if running via crunch-dispatch-slurm).
860 func (runner *ContainerRunner) LogNodeRecord() error {
861 if it := os.Getenv("InstanceType"); it != "" {
862 // Dispatched via arvados-dispatch-cloud. Save
863 // InstanceType config fragment received from
864 // dispatcher on stdin.
865 w, err := runner.LogCollection.OpenFile("node.json", os.O_CREATE|os.O_WRONLY, 0666)
870 _, err = io.WriteString(w, it)
876 // Dispatched via crunch-dispatch-slurm. Look up
877 // apiserver's node record corresponding to
879 hostname := os.Getenv("SLURMD_NODENAME")
881 hostname, _ = os.Hostname()
883 _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
884 // The "info" field has admin-only info when
885 // obtained with a privileged token, and
886 // should not be logged.
887 node, ok := resp.(map[string]interface{})
895 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
896 writer, err := runner.LogCollection.OpenFile(label+".json", os.O_CREATE|os.O_WRONLY, 0666)
901 ArvClient: runner.DispatcherArvClient,
902 UUID: runner.Container.UUID,
903 loggingStream: label,
907 reader, err := runner.DispatcherArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
909 return false, fmt.Errorf("error getting %s record: %v", label, err)
913 dec := json.NewDecoder(reader)
915 var resp map[string]interface{}
916 if err = dec.Decode(&resp); err != nil {
917 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
919 items, ok := resp["items"].([]interface{})
921 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
922 } else if len(items) < 1 {
928 // Re-encode it using indentation to improve readability
929 enc := json.NewEncoder(w)
930 enc.SetIndent("", " ")
931 if err = enc.Encode(items[0]); err != nil {
932 return false, fmt.Errorf("error logging %s record: %v", label, err)
936 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
941 // AttachStreams connects the docker container stdin, stdout and stderr logs
942 // to the Arvados logger which logs to Keep and the API server logs table.
943 func (runner *ContainerRunner) AttachStreams() (err error) {
945 runner.CrunchLog.Print("Attaching container streams")
947 // If stdin mount is provided, attach it to the docker container
948 var stdinRdr arvados.File
950 if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
951 if stdinMnt.Kind == "collection" {
952 var stdinColl arvados.Collection
953 collID := stdinMnt.UUID
955 collID = stdinMnt.PortableDataHash
957 err = runner.ContainerArvClient.Get("collections", collID, nil, &stdinColl)
959 return fmt.Errorf("While getting stdin collection: %v", err)
962 stdinRdr, err = runner.ContainerKeepClient.ManifestFileReader(
963 manifest.Manifest{Text: stdinColl.ManifestText},
965 if os.IsNotExist(err) {
966 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
967 } else if err != nil {
968 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
970 } else if stdinMnt.Kind == "json" {
971 stdinJSON, err = json.Marshal(stdinMnt.Content)
973 return fmt.Errorf("While encoding stdin json data: %v", err)
978 stdinUsed := stdinRdr != nil || len(stdinJSON) != 0
979 response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
980 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
982 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
985 runner.loggingDone = make(chan bool)
987 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
988 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
992 runner.Stdout = stdoutFile
993 } else if w, err := runner.NewLogWriter("stdout"); err != nil {
996 runner.Stdout = NewThrottledLogger(w)
999 if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
1000 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
1004 runner.Stderr = stderrFile
1005 } else if w, err := runner.NewLogWriter("stderr"); err != nil {
1008 runner.Stderr = NewThrottledLogger(w)
1011 if stdinRdr != nil {
1013 _, err := io.Copy(response.Conn, stdinRdr)
1015 runner.CrunchLog.Printf("While writing stdin collection to docker container: %v", err)
1019 response.CloseWrite()
1021 } else if len(stdinJSON) != 0 {
1023 _, err := io.Copy(response.Conn, bytes.NewReader(stdinJSON))
1025 runner.CrunchLog.Printf("While writing stdin json to docker container: %v", err)
1028 response.CloseWrite()
1032 go runner.ProcessDockerAttach(response.Reader)
1037 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
1038 stdoutPath := mntPath[len(runner.Container.OutputPath):]
1039 index := strings.LastIndex(stdoutPath, "/")
1041 subdirs := stdoutPath[:index]
1043 st, err := os.Stat(runner.HostOutputDir)
1045 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
1047 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
1048 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
1050 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
1054 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
1056 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
1059 return stdoutFile, nil
1062 // CreateContainer creates the docker container.
1063 func (runner *ContainerRunner) CreateContainer() error {
1064 runner.CrunchLog.Print("Creating Docker container")
1066 runner.ContainerConfig.Cmd = runner.Container.Command
1067 if runner.Container.Cwd != "." {
1068 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
1071 for k, v := range runner.Container.Environment {
1072 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
1075 runner.ContainerConfig.Volumes = runner.Volumes
1077 maxRAM := int64(runner.Container.RuntimeConstraints.RAM)
1078 minDockerRAM := int64(16)
1079 if maxRAM < minDockerRAM*1024*1024 {
1080 // Docker daemon won't let you set a limit less than ~10 MiB
1081 maxRAM = minDockerRAM * 1024 * 1024
1083 runner.HostConfig = dockercontainer.HostConfig{
1084 Binds: runner.Binds,
1085 LogConfig: dockercontainer.LogConfig{
1088 Resources: dockercontainer.Resources{
1089 CgroupParent: runner.setCgroupParent,
1090 NanoCPUs: int64(runner.Container.RuntimeConstraints.VCPUs) * 1000000000,
1091 Memory: maxRAM, // RAM
1092 MemorySwap: maxRAM, // RAM+swap
1093 KernelMemory: maxRAM, // kernel portion
1097 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
1098 tok, err := runner.ContainerToken()
1102 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
1103 "ARVADOS_API_TOKEN="+tok,
1104 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
1105 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
1107 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
1109 if runner.enableNetwork == "always" {
1110 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
1112 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
1116 _, stdinUsed := runner.Container.Mounts["stdin"]
1117 runner.ContainerConfig.OpenStdin = stdinUsed
1118 runner.ContainerConfig.StdinOnce = stdinUsed
1119 runner.ContainerConfig.AttachStdin = stdinUsed
1120 runner.ContainerConfig.AttachStdout = true
1121 runner.ContainerConfig.AttachStderr = true
1123 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
1125 return fmt.Errorf("While creating container: %v", err)
1128 runner.ContainerID = createdBody.ID
1130 return runner.AttachStreams()
1133 // StartContainer starts the docker container created by CreateContainer.
1134 func (runner *ContainerRunner) StartContainer() error {
1135 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
1136 runner.cStateLock.Lock()
1137 defer runner.cStateLock.Unlock()
1138 if runner.cCancelled {
1141 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
1142 dockertypes.ContainerStartOptions{})
1145 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
1146 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])
1148 return fmt.Errorf("could not start container: %v%s", err, advice)
1153 // WaitFinish waits for the container to terminate, capture the exit code, and
1154 // close the stdout/stderr logging.
1155 func (runner *ContainerRunner) WaitFinish() error {
1156 var runTimeExceeded <-chan time.Time
1157 runner.CrunchLog.Print("Waiting for container to finish")
1159 waitOk, waitErr := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID, dockercontainer.WaitConditionNotRunning)
1160 arvMountExit := runner.ArvMountExit
1161 if timeout := runner.Container.SchedulingParameters.MaxRunTime; timeout > 0 {
1162 runTimeExceeded = time.After(time.Duration(timeout) * time.Second)
1165 containerGone := make(chan struct{})
1167 defer close(containerGone)
1168 if runner.containerWatchdogInterval < 1 {
1169 runner.containerWatchdogInterval = time.Minute
1171 for range time.NewTicker(runner.containerWatchdogInterval).C {
1172 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(runner.containerWatchdogInterval))
1173 ctr, err := runner.Docker.ContainerInspect(ctx, runner.ContainerID)
1175 runner.cStateLock.Lock()
1176 done := runner.cRemoved || runner.ExitCode != nil
1177 runner.cStateLock.Unlock()
1180 } else if err != nil {
1181 runner.CrunchLog.Printf("Error inspecting container: %s", err)
1182 runner.checkBrokenNode(err)
1184 } else if ctr.State == nil || !(ctr.State.Running || ctr.State.Status == "created") {
1185 runner.CrunchLog.Printf("Container is not running: State=%v", ctr.State)
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")
1223 func (runner *ContainerRunner) updateLogs() {
1224 ticker := time.NewTicker(crunchLogUpdatePeriod / 360)
1227 sigusr1 := make(chan os.Signal, 1)
1228 signal.Notify(sigusr1, syscall.SIGUSR1)
1229 defer signal.Stop(sigusr1)
1231 saveAtTime := time.Now().Add(crunchLogUpdatePeriod)
1232 saveAtSize := crunchLogUpdateSize
1238 saveAtTime = time.Now()
1240 runner.logMtx.Lock()
1241 done := runner.LogsPDH != nil
1242 runner.logMtx.Unlock()
1246 size := runner.LogCollection.Size()
1247 if size == savedSize || (time.Now().Before(saveAtTime) && size < saveAtSize) {
1250 saveAtTime = time.Now().Add(crunchLogUpdatePeriod)
1251 saveAtSize = runner.LogCollection.Size() + crunchLogUpdateSize
1252 saved, err := runner.saveLogCollection(false)
1254 runner.CrunchLog.Printf("error updating log collection: %s", err)
1258 var updated arvados.Container
1259 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1260 "container": arvadosclient.Dict{"log": saved.PortableDataHash},
1263 runner.CrunchLog.Printf("error updating container log to %s: %s", saved.PortableDataHash, err)
1271 // CaptureOutput saves data from the container's output directory if
1272 // needed, and updates the container output accordingly.
1273 func (runner *ContainerRunner) CaptureOutput() error {
1274 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
1275 // Output may have been set directly by the container, so
1276 // refresh the container record to check.
1277 err := runner.DispatcherArvClient.Get("containers", runner.Container.UUID,
1278 nil, &runner.Container)
1282 if runner.Container.Output != "" {
1283 // Container output is already set.
1284 runner.OutputPDH = &runner.Container.Output
1289 txt, err := (&copier{
1290 client: runner.containerClient,
1291 arvClient: runner.ContainerArvClient,
1292 keepClient: runner.ContainerKeepClient,
1293 hostOutputDir: runner.HostOutputDir,
1294 ctrOutputDir: runner.Container.OutputPath,
1295 binds: runner.Binds,
1296 mounts: runner.Container.Mounts,
1297 secretMounts: runner.SecretMounts,
1298 logger: runner.CrunchLog,
1303 if n := len(regexp.MustCompile(` [0-9a-f]+\+\S*\+R`).FindAllStringIndex(txt, -1)); n > 0 {
1304 runner.CrunchLog.Printf("Copying %d data blocks from remote input collections...", n)
1305 fs, err := (&arvados.Collection{ManifestText: txt}).FileSystem(runner.containerClient, runner.ContainerKeepClient)
1309 txt, err = fs.MarshalManifest(".")
1314 var resp arvados.Collection
1315 err = runner.ContainerArvClient.Create("collections", arvadosclient.Dict{
1316 "ensure_unique_name": true,
1317 "collection": arvadosclient.Dict{
1319 "name": "output for " + runner.Container.UUID,
1320 "manifest_text": txt,
1324 return fmt.Errorf("error creating output collection: %v", err)
1326 runner.OutputPDH = &resp.PortableDataHash
1330 func (runner *ContainerRunner) CleanupDirs() {
1331 if runner.ArvMount != nil {
1333 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1334 umount.Stdout = runner.CrunchLog
1335 umount.Stderr = runner.CrunchLog
1336 runner.CrunchLog.Printf("Running %v", umount.Args)
1337 umnterr := umount.Start()
1340 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1342 // If arv-mount --unmount gets stuck for any reason, we
1343 // don't want to wait for it forever. Do Wait() in a goroutine
1344 // so it doesn't block crunch-run.
1345 umountExit := make(chan error)
1347 mnterr := umount.Wait()
1349 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1351 umountExit <- mnterr
1354 for again := true; again; {
1360 case <-runner.ArvMountExit:
1362 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1363 runner.CrunchLog.Printf("Timed out waiting for unmount")
1365 umount.Process.Kill()
1367 runner.ArvMount.Process.Kill()
1373 if runner.ArvMountPoint != "" {
1374 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1375 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1379 if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1380 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1384 // CommitLogs posts the collection containing the final container logs.
1385 func (runner *ContainerRunner) CommitLogs() error {
1387 // Hold cStateLock to prevent races on CrunchLog (e.g., stop()).
1388 runner.cStateLock.Lock()
1389 defer runner.cStateLock.Unlock()
1391 runner.CrunchLog.Print(runner.finalState)
1393 if runner.arvMountLog != nil {
1394 runner.arvMountLog.Close()
1396 runner.CrunchLog.Close()
1398 // Closing CrunchLog above allows them to be committed to Keep at this
1399 // point, but re-open crunch log with ArvClient in case there are any
1400 // other further errors (such as failing to write the log to Keep!)
1401 // while shutting down
1402 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{
1403 ArvClient: runner.DispatcherArvClient,
1404 UUID: runner.Container.UUID,
1405 loggingStream: "crunch-run",
1408 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1411 if runner.LogsPDH != nil {
1412 // If we have already assigned something to LogsPDH,
1413 // we must be closing the re-opened log, which won't
1414 // end up getting attached to the container record and
1415 // therefore doesn't need to be saved as a collection
1416 // -- it exists only to send logs to other channels.
1419 saved, err := runner.saveLogCollection(true)
1421 return fmt.Errorf("error saving log collection: %s", err)
1423 runner.logMtx.Lock()
1424 defer runner.logMtx.Unlock()
1425 runner.LogsPDH = &saved.PortableDataHash
1429 func (runner *ContainerRunner) saveLogCollection(final bool) (response arvados.Collection, err error) {
1430 runner.logMtx.Lock()
1431 defer runner.logMtx.Unlock()
1432 if runner.LogsPDH != nil {
1433 // Already finalized.
1436 mt, err := runner.LogCollection.MarshalManifest(".")
1438 err = fmt.Errorf("error creating log manifest: %v", err)
1441 updates := arvadosclient.Dict{
1442 "name": "logs for " + runner.Container.UUID,
1443 "manifest_text": mt,
1446 updates["is_trashed"] = true
1448 exp := time.Now().Add(crunchLogUpdatePeriod * 24)
1449 updates["trash_at"] = exp
1450 updates["delete_at"] = exp
1452 reqBody := arvadosclient.Dict{"collection": updates}
1453 if runner.logUUID == "" {
1454 reqBody["ensure_unique_name"] = true
1455 err = runner.DispatcherArvClient.Create("collections", reqBody, &response)
1457 err = runner.DispatcherArvClient.Update("collections", runner.logUUID, reqBody, &response)
1462 runner.logUUID = response.UUID
1466 // UpdateContainerRunning updates the container state to "Running"
1467 func (runner *ContainerRunner) UpdateContainerRunning() error {
1468 runner.cStateLock.Lock()
1469 defer runner.cStateLock.Unlock()
1470 if runner.cCancelled {
1473 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID,
1474 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running", "gateway_address": runner.gateway.Address}}, nil)
1477 // ContainerToken returns the api_token the container (and any
1478 // arv-mount processes) are allowed to use.
1479 func (runner *ContainerRunner) ContainerToken() (string, error) {
1480 if runner.token != "" {
1481 return runner.token, nil
1484 var auth arvados.APIClientAuthorization
1485 err := runner.DispatcherArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1489 runner.token = fmt.Sprintf("v2/%s/%s/%s", auth.UUID, auth.APIToken, runner.Container.UUID)
1490 return runner.token, nil
1493 // UpdateContainerFinal updates the container record state on API
1494 // server to "Complete" or "Cancelled"
1495 func (runner *ContainerRunner) UpdateContainerFinal() error {
1496 update := arvadosclient.Dict{}
1497 update["state"] = runner.finalState
1498 if runner.LogsPDH != nil {
1499 update["log"] = *runner.LogsPDH
1501 if runner.finalState == "Complete" {
1502 if runner.ExitCode != nil {
1503 update["exit_code"] = *runner.ExitCode
1505 if runner.OutputPDH != nil {
1506 update["output"] = *runner.OutputPDH
1509 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1512 // IsCancelled returns the value of Cancelled, with goroutine safety.
1513 func (runner *ContainerRunner) IsCancelled() bool {
1514 runner.cStateLock.Lock()
1515 defer runner.cStateLock.Unlock()
1516 return runner.cCancelled
1519 // NewArvLogWriter creates an ArvLogWriter
1520 func (runner *ContainerRunner) NewArvLogWriter(name string) (io.WriteCloser, error) {
1521 writer, err := runner.LogCollection.OpenFile(name+".txt", os.O_CREATE|os.O_WRONLY, 0666)
1525 return &ArvLogWriter{
1526 ArvClient: runner.DispatcherArvClient,
1527 UUID: runner.Container.UUID,
1528 loggingStream: name,
1529 writeCloser: writer,
1533 // Run the full container lifecycle.
1534 func (runner *ContainerRunner) Run() (err error) {
1535 runner.CrunchLog.Printf("crunch-run %s started", cmd.Version.String())
1536 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1538 hostname, hosterr := os.Hostname()
1540 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1542 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1545 runner.finalState = "Queued"
1548 runner.CleanupDirs()
1550 runner.CrunchLog.Printf("crunch-run finished")
1551 runner.CrunchLog.Close()
1554 err = runner.fetchContainerRecord()
1558 if runner.Container.State != "Locked" {
1559 return fmt.Errorf("dispatch error detected: container %q has state %q", runner.Container.UUID, runner.Container.State)
1563 // checkErr prints e (unless it's nil) and sets err to
1564 // e (unless err is already non-nil). Thus, if err
1565 // hasn't already been assigned when Run() returns,
1566 // this cleanup func will cause Run() to return the
1567 // first non-nil error that is passed to checkErr().
1568 checkErr := func(errorIn string, e error) {
1572 runner.CrunchLog.Printf("error in %s: %v", errorIn, e)
1576 if runner.finalState == "Complete" {
1577 // There was an error in the finalization.
1578 runner.finalState = "Cancelled"
1582 // Log the error encountered in Run(), if any
1583 checkErr("Run", err)
1585 if runner.finalState == "Queued" {
1586 runner.UpdateContainerFinal()
1590 if runner.IsCancelled() {
1591 runner.finalState = "Cancelled"
1592 // but don't return yet -- we still want to
1593 // capture partial output and write logs
1596 checkErr("CaptureOutput", runner.CaptureOutput())
1597 checkErr("stopHoststat", runner.stopHoststat())
1598 checkErr("CommitLogs", runner.CommitLogs())
1599 checkErr("UpdateContainerFinal", runner.UpdateContainerFinal())
1602 runner.setupSignals()
1603 err = runner.startHoststat()
1608 // check for and/or load image
1609 err = runner.LoadImage()
1611 if !runner.checkBrokenNode(err) {
1612 // Failed to load image but not due to a "broken node"
1613 // condition, probably user error.
1614 runner.finalState = "Cancelled"
1616 err = fmt.Errorf("While loading container image: %v", err)
1620 // set up FUSE mount and binds
1621 err = runner.SetupMounts()
1623 runner.finalState = "Cancelled"
1624 err = fmt.Errorf("While setting up mounts: %v", err)
1628 err = runner.CreateContainer()
1632 err = runner.LogHostInfo()
1636 err = runner.LogNodeRecord()
1640 err = runner.LogContainerRecord()
1645 if runner.IsCancelled() {
1649 err = runner.UpdateContainerRunning()
1653 runner.finalState = "Cancelled"
1655 err = runner.startCrunchstat()
1660 err = runner.StartContainer()
1662 runner.checkBrokenNode(err)
1666 err = runner.WaitFinish()
1667 if err == nil && !runner.IsCancelled() {
1668 runner.finalState = "Complete"
1673 // Fetch the current container record (uuid = runner.Container.UUID)
1674 // into runner.Container.
1675 func (runner *ContainerRunner) fetchContainerRecord() error {
1676 reader, err := runner.DispatcherArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1678 return fmt.Errorf("error fetching container record: %v", err)
1680 defer reader.Close()
1682 dec := json.NewDecoder(reader)
1684 err = dec.Decode(&runner.Container)
1686 return fmt.Errorf("error decoding container record: %v", err)
1690 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
1693 containerToken, err := runner.ContainerToken()
1695 return fmt.Errorf("error getting container token: %v", err)
1698 runner.ContainerArvClient, runner.ContainerKeepClient,
1699 runner.containerClient, err = runner.MkArvClient(containerToken)
1701 return fmt.Errorf("error creating container API client: %v", err)
1704 err = runner.ContainerArvClient.Call("GET", "containers", runner.Container.UUID, "secret_mounts", nil, &sm)
1706 if apierr, ok := err.(arvadosclient.APIServerError); !ok || apierr.HttpStatusCode != 404 {
1707 return fmt.Errorf("error fetching secret_mounts: %v", err)
1709 // ok && apierr.HttpStatusCode == 404, which means
1710 // secret_mounts isn't supported by this API server.
1712 runner.SecretMounts = sm.SecretMounts
1717 // NewContainerRunner creates a new container runner.
1718 func NewContainerRunner(dispatcherClient *arvados.Client,
1719 dispatcherArvClient IArvadosClient,
1720 dispatcherKeepClient IKeepClient,
1721 docker ThinDockerClient,
1722 containerUUID string) (*ContainerRunner, error) {
1724 cr := &ContainerRunner{
1725 dispatcherClient: dispatcherClient,
1726 DispatcherArvClient: dispatcherArvClient,
1727 DispatcherKeepClient: dispatcherKeepClient,
1730 cr.NewLogWriter = cr.NewArvLogWriter
1731 cr.RunArvMount = cr.ArvMountCmd
1732 cr.MkTempDir = ioutil.TempDir
1733 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1734 cl, err := arvadosclient.MakeArvadosClient()
1736 return nil, nil, nil, err
1739 kc, err := keepclient.MakeKeepClient(cl)
1741 return nil, nil, nil, err
1743 c2 := arvados.NewClientFromEnv()
1744 c2.AuthToken = token
1745 return cl, kc, c2, nil
1748 cr.LogCollection, err = (&arvados.Collection{}).FileSystem(cr.dispatcherClient, cr.DispatcherKeepClient)
1752 cr.Container.UUID = containerUUID
1753 w, err := cr.NewLogWriter("crunch-run")
1757 cr.CrunchLog = NewThrottledLogger(w)
1758 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1760 loadLogThrottleParams(dispatcherArvClient)
1766 func (command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
1767 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
1768 statInterval := flags.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1769 cgroupRoot := flags.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1770 cgroupParent := flags.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1771 cgroupParentSubsystem := flags.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1772 caCertsPath := flags.String("ca-certs", "", "Path to TLS root certificates")
1773 detach := flags.Bool("detach", false, "Detach from parent process and run in the background")
1774 stdinEnv := flags.Bool("stdin-env", false, "Load environment variables from JSON message on stdin")
1775 sleep := flags.Duration("sleep", 0, "Delay before starting (testing use only)")
1776 kill := flags.Int("kill", -1, "Send signal to an existing crunch-run process for given UUID")
1777 list := flags.Bool("list", false, "List UUIDs of existing crunch-run processes")
1778 enableNetwork := flags.String("container-enable-networking", "default",
1779 `Specify if networking should be enabled for container. One of 'default', 'always':
1780 default: only enable networking if container requests it.
1781 always: containers always have networking enabled
1783 networkMode := flags.String("container-network-mode", "default",
1784 `Set networking mode for container. Corresponds to Docker network mode (--net).
1786 memprofile := flags.String("memprofile", "", "write memory profile to `file` after running container")
1787 flags.Duration("check-containerd", 0, "Ignored. Exists for compatibility with older versions.")
1789 ignoreDetachFlag := false
1790 if len(args) > 0 && args[0] == "-no-detach" {
1791 // This process was invoked by a parent process, which
1792 // has passed along its own arguments, including
1793 // -detach, after the leading -no-detach flag. Strip
1794 // the leading -no-detach flag (it's not recognized by
1795 // flags.Parse()) and ignore the -detach flag that
1798 ignoreDetachFlag = true
1801 if err := flags.Parse(args); err == flag.ErrHelp {
1803 } else if err != nil {
1808 if *stdinEnv && !ignoreDetachFlag {
1809 // Load env vars on stdin if asked (but not in a
1810 // detached child process, in which case stdin is
1812 err := loadEnv(os.Stdin)
1819 containerID := flags.Arg(0)
1822 case *detach && !ignoreDetachFlag:
1823 return Detach(containerID, prog, args, os.Stdout, os.Stderr)
1825 return KillProcess(containerID, syscall.Signal(*kill), os.Stdout, os.Stderr)
1827 return ListProcesses(os.Stdout, os.Stderr)
1830 if containerID == "" {
1831 log.Printf("usage: %s [options] UUID", prog)
1835 log.Printf("crunch-run %s started", cmd.Version.String())
1838 if *caCertsPath != "" {
1839 arvadosclient.CertFiles = []string{*caCertsPath}
1842 api, err := arvadosclient.MakeArvadosClient()
1844 log.Printf("%s: %v", containerID, err)
1849 kc, kcerr := keepclient.MakeKeepClient(api)
1851 log.Printf("%s: %v", containerID, kcerr)
1854 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1857 // API version 1.21 corresponds to Docker 1.9, which is currently the
1858 // minimum version we want to support.
1859 docker, dockererr := dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1861 cr, err := NewContainerRunner(arvados.NewClientFromEnv(), api, kc, docker, containerID)
1866 if dockererr != nil {
1867 cr.CrunchLog.Printf("%s: %v", containerID, dockererr)
1868 cr.checkBrokenNode(dockererr)
1869 cr.CrunchLog.Close()
1873 cr.gateway = Gateway{
1874 Address: os.Getenv("GatewayAddress"),
1875 AuthSecret: os.Getenv("GatewayAuthSecret"),
1876 ContainerUUID: containerID,
1877 DockerContainerID: &cr.ContainerID,
1880 os.Unsetenv("GatewayAuthSecret")
1881 err = cr.gateway.Start()
1883 log.Printf("error starting gateway server: %s", err)
1887 parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerID+".")
1889 log.Printf("%s: %v", containerID, tmperr)
1893 cr.parentTemp = parentTemp
1894 cr.statInterval = *statInterval
1895 cr.cgroupRoot = *cgroupRoot
1896 cr.expectCgroupParent = *cgroupParent
1897 cr.enableNetwork = *enableNetwork
1898 cr.networkMode = *networkMode
1899 if *cgroupParentSubsystem != "" {
1900 p := findCgroup(*cgroupParentSubsystem)
1901 cr.setCgroupParent = p
1902 cr.expectCgroupParent = p
1907 if *memprofile != "" {
1908 f, err := os.Create(*memprofile)
1910 log.Printf("could not create memory profile: %s", err)
1912 runtime.GC() // get up-to-date statistics
1913 if err := pprof.WriteHeapProfile(f); err != nil {
1914 log.Printf("could not write memory profile: %s", err)
1916 closeerr := f.Close()
1917 if closeerr != nil {
1918 log.Printf("closing memprofile file: %s", err)
1923 log.Printf("%s: %v", containerID, runerr)
1929 func loadEnv(rdr io.Reader) error {
1930 buf, err := ioutil.ReadAll(rdr)
1932 return fmt.Errorf("read stdin: %s", err)
1934 var env map[string]string
1935 err = json.Unmarshal(buf, &env)
1937 return fmt.Errorf("decode stdin: %s", err)
1939 for k, v := range env {
1940 err = os.Setenv(k, v)
1942 return fmt.Errorf("setenv(%q): %s", k, err)