1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
34 "git.arvados.org/arvados.git/lib/cloud"
35 "git.arvados.org/arvados.git/lib/cmd"
36 "git.arvados.org/arvados.git/lib/config"
37 "git.arvados.org/arvados.git/lib/crunchstat"
38 "git.arvados.org/arvados.git/sdk/go/arvados"
39 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
40 "git.arvados.org/arvados.git/sdk/go/ctxlog"
41 "git.arvados.org/arvados.git/sdk/go/keepclient"
42 "git.arvados.org/arvados.git/sdk/go/manifest"
43 "golang.org/x/sys/unix"
48 var Command = command{}
50 // ConfigData contains environment variables and (when needed) cluster
51 // configuration, passed from dispatchcloud to crunch-run on stdin.
52 type ConfigData struct {
56 Cluster *arvados.Cluster
59 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
60 type IArvadosClient interface {
61 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
62 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
63 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
64 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
65 CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
66 Discovery(key string) (interface{}, error)
69 // ErrCancelled is the error returned when the container is cancelled.
70 var ErrCancelled = errors.New("Cancelled")
72 // IKeepClient is the minimal Keep API methods used by crunch-run.
73 type IKeepClient interface {
74 BlockWrite(context.Context, arvados.BlockWriteOptions) (arvados.BlockWriteResponse, error)
75 ReadAt(locator string, p []byte, off int) (int, error)
76 ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error)
77 LocalLocator(locator string) (string, error)
79 SetStorageClasses(sc []string)
82 // NewLogWriter is a factory function to create a new log writer.
83 type NewLogWriter func(name string) (io.WriteCloser, error)
85 type RunArvMount func(cmdline []string, tok string) (*exec.Cmd, error)
87 type MkTempDir func(string, string) (string, 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 executor containerExecutor
97 executorStdin io.Closer
98 executorStdout io.Closer
99 executorStderr io.Closer
101 // Dispatcher client is initialized with the Dispatcher token.
102 // This is a privileged token used to manage container status
105 // We have both dispatcherClient and DispatcherArvClient
106 // because there are two different incompatible Arvados Go
107 // SDKs and we have to use both (hopefully this gets fixed in
109 dispatcherClient *arvados.Client
110 DispatcherArvClient IArvadosClient
111 DispatcherKeepClient IKeepClient
113 // Container client is initialized with the Container token
114 // This token controls the permissions of the container, and
115 // must be used for operations such as reading collections.
117 // Same comment as above applies to
118 // containerClient/ContainerArvClient.
119 containerClient *arvados.Client
120 ContainerArvClient IArvadosClient
121 ContainerKeepClient IKeepClient
123 Container arvados.Container
126 NewLogWriter NewLogWriter
127 CrunchLog *ThrottledLogger
130 LogCollection arvados.CollectionFileSystem
132 RunArvMount RunArvMount
137 Volumes map[string]struct{}
139 SigChan chan os.Signal
140 ArvMountExit chan error
141 SecretMounts map[string]arvados.Mount
142 MkArvClient func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error)
145 costStartTime time.Time
148 keepstoreLogger io.WriteCloser
149 keepstoreLogbuf *bufThenWrite
150 statLogger io.WriteCloser
151 statReporter *crunchstat.Reporter
152 hoststatLogger io.WriteCloser
153 hoststatReporter *crunchstat.Reporter
154 statInterval time.Duration
156 // What we expect the container's cgroup parent to be.
157 expectCgroupParent string
158 // What we tell docker to use as the container's cgroup
159 // parent. Note: Ideally we would use the same field for both
160 // expectCgroupParent and setCgroupParent, and just make it
161 // default to "docker". However, when using docker < 1.10 with
162 // systemd, specifying a non-empty cgroup parent (even the
163 // default value "docker") hits a docker bug
164 // (https://github.com/docker/docker/issues/17126). Using two
165 // separate fields makes it possible to use the "expect cgroup
166 // parent to be X" feature even on sites where the "specify
167 // cgroup parent" feature breaks.
168 setCgroupParent string
170 cStateLock sync.Mutex
171 cCancelled bool // StopContainer() invoked
173 enableMemoryLimit bool
174 enableNetwork string // one of "default" or "always"
175 networkMode string // "none", "host", or "" -- passed through to executor
176 brokenNodeHook string // script to run if node appears to be broken
177 arvMountLog *ThrottledLogger
179 containerWatchdogInterval time.Duration
183 prices []cloud.InstancePrice
184 pricesLock sync.Mutex
187 // setupSignals sets up signal handling to gracefully terminate the
188 // underlying container and update state when receiving a TERM, INT or
190 func (runner *ContainerRunner) setupSignals() {
191 runner.SigChan = make(chan os.Signal, 1)
192 signal.Notify(runner.SigChan, syscall.SIGTERM)
193 signal.Notify(runner.SigChan, syscall.SIGINT)
194 signal.Notify(runner.SigChan, syscall.SIGQUIT)
196 go func(sig chan os.Signal) {
203 // stop the underlying container.
204 func (runner *ContainerRunner) stop(sig os.Signal) {
205 runner.cStateLock.Lock()
206 defer runner.cStateLock.Unlock()
208 runner.CrunchLog.Printf("caught signal: %v", sig)
210 runner.cCancelled = true
211 runner.CrunchLog.Printf("stopping container")
212 err := runner.executor.Stop()
214 runner.CrunchLog.Printf("error stopping container: %s", err)
218 var errorBlacklist = []string{
219 "(?ms).*[Cc]annot connect to the Docker daemon.*",
220 "(?ms).*oci runtime error.*starting container process.*container init.*mounting.*to rootfs.*no such file or directory.*",
221 "(?ms).*grpc: the connection is unavailable.*",
224 func (runner *ContainerRunner) runBrokenNodeHook() {
225 if runner.brokenNodeHook == "" {
226 path := filepath.Join(lockdir, brokenfile)
227 runner.CrunchLog.Printf("Writing %s to mark node as broken", path)
228 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0700)
230 runner.CrunchLog.Printf("Error writing %s: %s", path, err)
235 runner.CrunchLog.Printf("Running broken node hook %q", runner.brokenNodeHook)
237 c := exec.Command(runner.brokenNodeHook)
238 c.Stdout = runner.CrunchLog
239 c.Stderr = runner.CrunchLog
242 runner.CrunchLog.Printf("Error running broken node hook: %v", err)
247 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
248 for _, d := range errorBlacklist {
249 if m, e := regexp.MatchString(d, goterr.Error()); m && e == nil {
250 runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
251 runner.runBrokenNodeHook()
258 // LoadImage determines the docker image id from the container record and
259 // checks if it is available in the local Docker image store. If not, it loads
260 // the image from Keep.
261 func (runner *ContainerRunner) LoadImage() (string, error) {
262 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
264 d, err := os.Open(runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage)
269 allfiles, err := d.Readdirnames(-1)
273 var tarfiles []string
274 for _, fnm := range allfiles {
275 if strings.HasSuffix(fnm, ".tar") {
276 tarfiles = append(tarfiles, fnm)
279 if len(tarfiles) == 0 {
280 return "", fmt.Errorf("image collection does not include a .tar image file")
282 if len(tarfiles) > 1 {
283 return "", fmt.Errorf("cannot choose from multiple tar files in image collection: %v", tarfiles)
285 imageID := tarfiles[0][:len(tarfiles[0])-4]
286 imageTarballPath := runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage + "/" + imageID + ".tar"
287 runner.CrunchLog.Printf("Using Docker image id %q", imageID)
289 runner.CrunchLog.Print("Loading Docker image from keep")
290 err = runner.executor.LoadImage(imageID, imageTarballPath, runner.Container, runner.ArvMountPoint,
291 runner.containerClient)
299 func (runner *ContainerRunner) ArvMountCmd(cmdline []string, token string) (c *exec.Cmd, err error) {
300 c = exec.Command(cmdline[0], cmdline[1:]...)
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 scanner := logScanner{
320 "Block not found error",
321 "Unhandled exception during FUSE operation",
323 ReportFunc: func(pattern, text string) {
324 runner.updateRuntimeStatus(arvadosclient.Dict{
325 "warning": "arv-mount: " + pattern,
326 "warningDetail": text,
330 c.Stdout = runner.arvMountLog
331 c.Stderr = io.MultiWriter(runner.arvMountLog, os.Stderr, &scanner)
333 runner.CrunchLog.Printf("Running %v", c.Args)
340 statReadme := make(chan bool)
341 runner.ArvMountExit = make(chan error)
346 time.Sleep(100 * time.Millisecond)
347 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
359 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
361 runner.ArvMountExit <- mnterr
362 close(runner.ArvMountExit)
368 case err := <-runner.ArvMountExit:
369 runner.ArvMount = nil
377 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
378 if runner.ArvMountPoint == "" {
379 runner.ArvMountPoint, err = runner.MkTempDir(runner.parentTemp, prefix)
384 func copyfile(src string, dst string) (err error) {
385 srcfile, err := os.Open(src)
390 os.MkdirAll(path.Dir(dst), 0777)
392 dstfile, err := os.Create(dst)
396 _, err = io.Copy(dstfile, srcfile)
401 err = srcfile.Close()
402 err2 := dstfile.Close()
415 func (runner *ContainerRunner) SetupMounts() (map[string]bindmount, error) {
416 bindmounts := map[string]bindmount{}
417 err := runner.SetupArvMountPoint("keep")
419 return nil, fmt.Errorf("While creating keep mount temp dir: %v", err)
422 token, err := runner.ContainerToken()
424 return nil, fmt.Errorf("could not get container token: %s", err)
426 runner.CrunchLog.Printf("container token %q", token)
430 arvMountCmd := []string{
434 "--storage-classes", strings.Join(runner.Container.OutputStorageClasses, ","),
435 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
437 if _, isdocker := runner.executor.(*dockerExecutor); isdocker {
438 arvMountCmd = append(arvMountCmd, "--allow-other")
441 if runner.Container.RuntimeConstraints.KeepCacheDisk > 0 {
442 keepcachedir, err := runner.MkTempDir(runner.parentTemp, "keepcache")
444 return nil, fmt.Errorf("while creating keep cache temp dir: %v", err)
446 arvMountCmd = append(arvMountCmd, "--disk-cache", "--disk-cache-dir", keepcachedir, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheDisk))
447 } else if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
448 arvMountCmd = append(arvMountCmd, "--ram-cache", "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
451 collectionPaths := []string{}
452 needCertMount := true
453 type copyFile struct {
457 var copyFiles []copyFile
460 for bind := range runner.Container.Mounts {
461 binds = append(binds, bind)
463 for bind := range runner.SecretMounts {
464 if _, ok := runner.Container.Mounts[bind]; ok {
465 return nil, fmt.Errorf("secret mount %q conflicts with regular mount", bind)
467 if runner.SecretMounts[bind].Kind != "json" &&
468 runner.SecretMounts[bind].Kind != "text" {
469 return nil, fmt.Errorf("secret mount %q type is %q but only 'json' and 'text' are permitted",
470 bind, runner.SecretMounts[bind].Kind)
472 binds = append(binds, bind)
476 for _, bind := range binds {
477 mnt, notSecret := runner.Container.Mounts[bind]
479 mnt = runner.SecretMounts[bind]
481 if bind == "stdout" || bind == "stderr" {
482 // Is it a "file" mount kind?
483 if mnt.Kind != "file" {
484 return nil, fmt.Errorf("unsupported mount kind '%s' for %s: only 'file' is supported", mnt.Kind, bind)
487 // Does path start with OutputPath?
488 prefix := runner.Container.OutputPath
489 if !strings.HasSuffix(prefix, "/") {
492 if !strings.HasPrefix(mnt.Path, prefix) {
493 return nil, fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
498 // Is it a "collection" mount kind?
499 if mnt.Kind != "collection" && mnt.Kind != "json" {
500 return nil, fmt.Errorf("unsupported mount kind '%s' for stdin: only 'collection' and 'json' are supported", mnt.Kind)
504 if bind == "/etc/arvados/ca-certificates.crt" {
505 needCertMount = false
508 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
509 if mnt.Kind != "collection" && mnt.Kind != "text" && mnt.Kind != "json" {
510 return nil, fmt.Errorf("only mount points of kind 'collection', 'text' or 'json' are supported underneath the output_path for %q, was %q", bind, mnt.Kind)
515 case mnt.Kind == "collection" && bind != "stdin":
517 if mnt.UUID != "" && mnt.PortableDataHash != "" {
518 return nil, fmt.Errorf("cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
522 return nil, fmt.Errorf("writing to existing collections currently not permitted")
525 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
526 } else if mnt.PortableDataHash != "" {
527 if mnt.Writable && !strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
528 return nil, fmt.Errorf("can never write to a collection specified by portable data hash")
530 idx := strings.Index(mnt.PortableDataHash, "/")
532 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
533 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
534 runner.Container.Mounts[bind] = mnt
536 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
537 if mnt.Path != "" && mnt.Path != "." {
538 if strings.HasPrefix(mnt.Path, "./") {
539 mnt.Path = mnt.Path[2:]
540 } else if strings.HasPrefix(mnt.Path, "/") {
541 mnt.Path = mnt.Path[1:]
543 src += "/" + mnt.Path
546 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
547 arvMountCmd = append(arvMountCmd, "--mount-tmp", fmt.Sprintf("tmp%d", tmpcount))
551 if bind == runner.Container.OutputPath {
552 runner.HostOutputDir = src
553 bindmounts[bind] = bindmount{HostPath: src}
554 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
555 copyFiles = append(copyFiles, copyFile{src, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
557 bindmounts[bind] = bindmount{HostPath: src}
560 bindmounts[bind] = bindmount{HostPath: src, ReadOnly: true}
562 collectionPaths = append(collectionPaths, src)
564 case mnt.Kind == "tmp":
566 tmpdir, err = runner.MkTempDir(runner.parentTemp, "tmp")
568 return nil, fmt.Errorf("while creating mount temp dir: %v", err)
570 st, staterr := os.Stat(tmpdir)
572 return nil, fmt.Errorf("while Stat on temp dir: %v", staterr)
574 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
576 return nil, fmt.Errorf("while Chmod temp dir: %v", err)
578 bindmounts[bind] = bindmount{HostPath: tmpdir}
579 if bind == runner.Container.OutputPath {
580 runner.HostOutputDir = tmpdir
583 case mnt.Kind == "json" || mnt.Kind == "text":
585 if mnt.Kind == "json" {
586 filedata, err = json.Marshal(mnt.Content)
588 return nil, fmt.Errorf("encoding json data: %v", err)
591 text, ok := mnt.Content.(string)
593 return nil, fmt.Errorf("content for mount %q must be a string", bind)
595 filedata = []byte(text)
598 tmpdir, err := runner.MkTempDir(runner.parentTemp, mnt.Kind)
600 return nil, fmt.Errorf("creating temp dir: %v", err)
602 tmpfn := filepath.Join(tmpdir, "mountdata."+mnt.Kind)
603 err = ioutil.WriteFile(tmpfn, filedata, 0444)
605 return nil, fmt.Errorf("writing temp file: %v", err)
607 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && (notSecret || runner.Container.Mounts[runner.Container.OutputPath].Kind != "collection") {
608 // In most cases, if the container
609 // specifies a literal file inside the
610 // output path, we copy it into the
611 // output directory (either a mounted
612 // collection or a staging area on the
613 // host fs). If it's a secret, it will
614 // be skipped when copying output from
615 // staging to Keep later.
616 copyFiles = append(copyFiles, copyFile{tmpfn, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
618 // If a secret is outside OutputPath,
619 // we bind mount the secret file
620 // directly just like other mounts. We
621 // also use this strategy when a
622 // secret is inside OutputPath but
623 // OutputPath is a live collection, to
624 // avoid writing the secret to
625 // Keep. Attempting to remove a
626 // bind-mounted secret file from
627 // inside the container will return a
628 // "Device or resource busy" error
629 // that might not be handled well by
630 // the container, which is why we
631 // don't use this strategy when
632 // OutputPath is a staging directory.
633 bindmounts[bind] = bindmount{HostPath: tmpfn, ReadOnly: true}
636 case mnt.Kind == "git_tree":
637 tmpdir, err := runner.MkTempDir(runner.parentTemp, "git_tree")
639 return nil, fmt.Errorf("creating temp dir: %v", err)
641 err = gitMount(mnt).extractTree(runner.ContainerArvClient, tmpdir, token)
645 bindmounts[bind] = bindmount{HostPath: tmpdir, ReadOnly: true}
649 if runner.HostOutputDir == "" {
650 return nil, fmt.Errorf("output path does not correspond to a writable mount point")
653 if needCertMount && runner.Container.RuntimeConstraints.API {
654 for _, certfile := range arvadosclient.CertFiles {
655 _, err := os.Stat(certfile)
657 bindmounts["/etc/arvados/ca-certificates.crt"] = bindmount{HostPath: certfile, ReadOnly: true}
664 // If we are only mounting collections by pdh, make
665 // sure we don't subscribe to websocket events to
666 // avoid putting undesired load on the API server
667 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id", "--disable-event-listening")
669 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
671 // the by_uuid mount point is used by singularity when writing
672 // out docker images converted to SIF
673 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_uuid")
674 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
676 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
678 return nil, fmt.Errorf("while trying to start arv-mount: %v", err)
680 if runner.hoststatReporter != nil && runner.ArvMount != nil {
681 runner.hoststatReporter.ReportPID("arv-mount", runner.ArvMount.Process.Pid)
684 for _, p := range collectionPaths {
687 return nil, fmt.Errorf("while checking that input files exist: %v", err)
691 for _, cp := range copyFiles {
692 st, err := os.Stat(cp.src)
694 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
697 err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
701 target := path.Join(cp.bind, walkpath[len(cp.src):])
702 if walkinfo.Mode().IsRegular() {
703 copyerr := copyfile(walkpath, target)
707 return os.Chmod(target, walkinfo.Mode()|0777)
708 } else if walkinfo.Mode().IsDir() {
709 mkerr := os.MkdirAll(target, 0777)
713 return os.Chmod(target, walkinfo.Mode()|os.ModeSetgid|0777)
715 return fmt.Errorf("source %q is not a regular file or directory", cp.src)
718 } else if st.Mode().IsRegular() {
719 err = copyfile(cp.src, cp.bind)
721 err = os.Chmod(cp.bind, st.Mode()|0777)
725 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
729 return bindmounts, nil
732 func (runner *ContainerRunner) stopHoststat() error {
733 if runner.hoststatReporter == nil {
736 runner.hoststatReporter.Stop()
737 err := runner.hoststatLogger.Close()
739 return fmt.Errorf("error closing hoststat logs: %v", err)
744 func (runner *ContainerRunner) startHoststat() error {
745 w, err := runner.NewLogWriter("hoststat")
749 runner.hoststatLogger = NewThrottledLogger(w)
750 runner.hoststatReporter = &crunchstat.Reporter{
751 Logger: log.New(runner.hoststatLogger, "", 0),
752 CgroupRoot: runner.cgroupRoot,
753 PollPeriod: runner.statInterval,
755 runner.hoststatReporter.Start()
756 runner.hoststatReporter.ReportPID("crunch-run", os.Getpid())
760 func (runner *ContainerRunner) startCrunchstat() error {
761 w, err := runner.NewLogWriter("crunchstat")
765 runner.statLogger = NewThrottledLogger(w)
766 runner.statReporter = &crunchstat.Reporter{
767 CID: runner.executor.CgroupID(),
768 Logger: log.New(runner.statLogger, "", 0),
769 CgroupParent: runner.expectCgroupParent,
770 CgroupRoot: runner.cgroupRoot,
771 PollPeriod: runner.statInterval,
772 TempDir: runner.parentTemp,
774 runner.statReporter.Start()
778 type infoCommand struct {
783 // LogHostInfo logs info about the current host, for debugging and
784 // accounting purposes. Although it's logged as "node-info", this is
785 // about the environment where crunch-run is actually running, which
786 // might differ from what's described in the node record (see
788 func (runner *ContainerRunner) LogHostInfo() (err error) {
789 w, err := runner.NewLogWriter("node-info")
794 commands := []infoCommand{
796 label: "Host Information",
797 cmd: []string{"uname", "-a"},
800 label: "CPU Information",
801 cmd: []string{"cat", "/proc/cpuinfo"},
804 label: "Memory Information",
805 cmd: []string{"cat", "/proc/meminfo"},
809 cmd: []string{"df", "-m", "/", os.TempDir()},
812 label: "Disk INodes",
813 cmd: []string{"df", "-i", "/", os.TempDir()},
817 // Run commands with informational output to be logged.
818 for _, command := range commands {
819 fmt.Fprintln(w, command.label)
820 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
823 if err := cmd.Run(); err != nil {
824 err = fmt.Errorf("While running command %q: %v", command.cmd, err)
833 return fmt.Errorf("While closing node-info logs: %v", err)
838 // LogContainerRecord gets and saves the raw JSON container record from the API server
839 func (runner *ContainerRunner) LogContainerRecord() error {
840 logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
841 if !logged && err == nil {
842 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
847 // LogNodeRecord logs the current host's InstanceType config entry (or
848 // the arvados#node record, if running via crunch-dispatch-slurm).
849 func (runner *ContainerRunner) LogNodeRecord() error {
850 if it := os.Getenv("InstanceType"); it != "" {
851 // Dispatched via arvados-dispatch-cloud. Save
852 // InstanceType config fragment received from
853 // dispatcher on stdin.
854 w, err := runner.LogCollection.OpenFile("node.json", os.O_CREATE|os.O_WRONLY, 0666)
859 _, err = io.WriteString(w, it)
865 // Dispatched via crunch-dispatch-slurm. Look up
866 // apiserver's node record corresponding to
868 hostname := os.Getenv("SLURMD_NODENAME")
870 hostname, _ = os.Hostname()
872 _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
873 // The "info" field has admin-only info when
874 // obtained with a privileged token, and
875 // should not be logged.
876 node, ok := resp.(map[string]interface{})
884 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
885 writer, err := runner.LogCollection.OpenFile(label+".json", os.O_CREATE|os.O_WRONLY, 0666)
890 ArvClient: runner.DispatcherArvClient,
891 UUID: runner.Container.UUID,
892 loggingStream: label,
896 reader, err := runner.DispatcherArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
898 return false, fmt.Errorf("error getting %s record: %v", label, err)
902 dec := json.NewDecoder(reader)
904 var resp map[string]interface{}
905 if err = dec.Decode(&resp); err != nil {
906 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
908 items, ok := resp["items"].([]interface{})
910 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
911 } else if len(items) < 1 {
917 // Re-encode it using indentation to improve readability
918 enc := json.NewEncoder(w)
919 enc.SetIndent("", " ")
920 if err = enc.Encode(items[0]); err != nil {
921 return false, fmt.Errorf("error logging %s record: %v", label, err)
925 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
930 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
931 stdoutPath := mntPath[len(runner.Container.OutputPath):]
932 index := strings.LastIndex(stdoutPath, "/")
934 subdirs := stdoutPath[:index]
936 st, err := os.Stat(runner.HostOutputDir)
938 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
940 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
941 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
943 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
947 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
949 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
952 return stdoutFile, nil
955 // CreateContainer creates the docker container.
956 func (runner *ContainerRunner) CreateContainer(imageID string, bindmounts map[string]bindmount) error {
957 var stdin io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
958 if mnt, ok := runner.Container.Mounts["stdin"]; ok {
965 collID = mnt.PortableDataHash
967 path := runner.ArvMountPoint + "/by_id/" + collID + "/" + mnt.Path
968 f, err := os.Open(path)
974 j, err := json.Marshal(mnt.Content)
976 return fmt.Errorf("error encoding stdin json data: %v", err)
978 stdin = ioutil.NopCloser(bytes.NewReader(j))
980 return fmt.Errorf("stdin mount has unsupported kind %q", mnt.Kind)
984 var stdout, stderr io.WriteCloser
985 if mnt, ok := runner.Container.Mounts["stdout"]; ok {
986 f, err := runner.getStdoutFile(mnt.Path)
991 } else if w, err := runner.NewLogWriter("stdout"); err != nil {
994 stdout = NewThrottledLogger(w)
997 if mnt, ok := runner.Container.Mounts["stderr"]; ok {
998 f, err := runner.getStdoutFile(mnt.Path)
1003 } else if w, err := runner.NewLogWriter("stderr"); err != nil {
1006 stderr = NewThrottledLogger(w)
1009 env := runner.Container.Environment
1010 enableNetwork := runner.enableNetwork == "always"
1011 if runner.Container.RuntimeConstraints.API {
1012 enableNetwork = true
1013 tok, err := runner.ContainerToken()
1017 env = map[string]string{}
1018 for k, v := range runner.Container.Environment {
1021 env["ARVADOS_API_TOKEN"] = tok
1022 env["ARVADOS_API_HOST"] = os.Getenv("ARVADOS_API_HOST")
1023 env["ARVADOS_API_HOST_INSECURE"] = os.Getenv("ARVADOS_API_HOST_INSECURE")
1024 env["ARVADOS_KEEP_SERVICES"] = os.Getenv("ARVADOS_KEEP_SERVICES")
1026 workdir := runner.Container.Cwd
1028 // both "" and "." mean default
1031 ram := runner.Container.RuntimeConstraints.RAM
1032 if !runner.enableMemoryLimit {
1035 runner.executorStdin = stdin
1036 runner.executorStdout = stdout
1037 runner.executorStderr = stderr
1039 if runner.Container.RuntimeConstraints.CUDA.DeviceCount > 0 {
1040 nvidiaModprobe(runner.CrunchLog)
1043 return runner.executor.Create(containerSpec{
1045 VCPUs: runner.Container.RuntimeConstraints.VCPUs,
1047 WorkingDir: workdir,
1049 BindMounts: bindmounts,
1050 Command: runner.Container.Command,
1051 EnableNetwork: enableNetwork,
1052 CUDADeviceCount: runner.Container.RuntimeConstraints.CUDA.DeviceCount,
1053 NetworkMode: runner.networkMode,
1054 CgroupParent: runner.setCgroupParent,
1061 // StartContainer starts the docker container created by CreateContainer.
1062 func (runner *ContainerRunner) StartContainer() error {
1063 runner.CrunchLog.Printf("Starting container")
1064 runner.cStateLock.Lock()
1065 defer runner.cStateLock.Unlock()
1066 if runner.cCancelled {
1069 err := runner.executor.Start()
1072 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
1073 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])
1075 return fmt.Errorf("could not start container: %v%s", err, advice)
1080 // WaitFinish waits for the container to terminate, capture the exit code, and
1081 // close the stdout/stderr logging.
1082 func (runner *ContainerRunner) WaitFinish() error {
1083 runner.CrunchLog.Print("Waiting for container to finish")
1084 var timeout <-chan time.Time
1085 if s := runner.Container.SchedulingParameters.MaxRunTime; s > 0 {
1086 timeout = time.After(time.Duration(s) * time.Second)
1088 ctx, cancel := context.WithCancel(context.Background())
1093 runner.CrunchLog.Printf("maximum run time exceeded. Stopping container.")
1095 case <-runner.ArvMountExit:
1096 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
1101 exitcode, err := runner.executor.Wait(ctx)
1103 runner.checkBrokenNode(err)
1106 runner.ExitCode = &exitcode
1109 if exitcode&0x80 != 0 {
1110 // Convert raw exit status (0x80 + signal number) to a
1111 // string to log after the code, like " (signal 101)"
1112 // or " (signal 9, killed)"
1113 sig := syscall.WaitStatus(exitcode).Signal()
1114 if name := unix.SignalName(sig); name != "" {
1115 extra = fmt.Sprintf(" (signal %d, %s)", sig, name)
1117 extra = fmt.Sprintf(" (signal %d)", sig)
1120 runner.CrunchLog.Printf("Container exited with status code %d%s", exitcode, extra)
1121 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1122 "container": arvadosclient.Dict{"exit_code": exitcode},
1125 runner.CrunchLog.Printf("ignoring error updating exit_code: %s", err)
1129 if err = runner.executorStdin.Close(); err != nil {
1130 err = fmt.Errorf("error closing container stdin: %s", err)
1131 runner.CrunchLog.Printf("%s", err)
1134 if err = runner.executorStdout.Close(); err != nil {
1135 err = fmt.Errorf("error closing container stdout: %s", err)
1136 runner.CrunchLog.Printf("%s", err)
1137 if returnErr == nil {
1141 if err = runner.executorStderr.Close(); err != nil {
1142 err = fmt.Errorf("error closing container stderr: %s", err)
1143 runner.CrunchLog.Printf("%s", err)
1144 if returnErr == nil {
1149 if runner.statReporter != nil {
1150 runner.statReporter.Stop()
1151 err = runner.statLogger.Close()
1153 runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
1159 func (runner *ContainerRunner) updateLogs() {
1160 ticker := time.NewTicker(crunchLogUpdatePeriod / 360)
1163 sigusr1 := make(chan os.Signal, 1)
1164 signal.Notify(sigusr1, syscall.SIGUSR1)
1165 defer signal.Stop(sigusr1)
1167 saveAtTime := time.Now().Add(crunchLogUpdatePeriod)
1168 saveAtSize := crunchLogUpdateSize
1174 saveAtTime = time.Now()
1176 runner.logMtx.Lock()
1177 done := runner.LogsPDH != nil
1178 runner.logMtx.Unlock()
1182 size := runner.LogCollection.Size()
1183 if size == savedSize || (time.Now().Before(saveAtTime) && size < saveAtSize) {
1186 saveAtTime = time.Now().Add(crunchLogUpdatePeriod)
1187 saveAtSize = runner.LogCollection.Size() + crunchLogUpdateSize
1188 saved, err := runner.saveLogCollection(false)
1190 runner.CrunchLog.Printf("error updating log collection: %s", err)
1194 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1195 "container": arvadosclient.Dict{"log": saved.PortableDataHash},
1198 runner.CrunchLog.Printf("error updating container log to %s: %s", saved.PortableDataHash, err)
1206 var spotInterruptionCheckInterval = 5 * time.Second
1207 var ec2MetadataBaseURL = "http://169.254.169.254"
1209 const ec2TokenTTL = time.Second * 21600
1211 func (runner *ContainerRunner) checkSpotInterruptionNotices() {
1212 type ec2metadata struct {
1213 Action string `json:"action"`
1214 Time time.Time `json:"time"`
1216 runner.CrunchLog.Printf("Checking for spot interruptions every %v using instance metadata at %s", spotInterruptionCheckInterval, ec2MetadataBaseURL)
1217 var metadata ec2metadata
1219 var tokenExp time.Time
1220 check := func() error {
1221 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute))
1223 if token == "" || tokenExp.Sub(time.Now()) < time.Minute {
1224 req, err := http.NewRequestWithContext(ctx, http.MethodPut, ec2MetadataBaseURL+"/latest/api/token", nil)
1228 req.Header.Set("X-aws-ec2-metadata-token-ttl-seconds", fmt.Sprintf("%d", int(ec2TokenTTL/time.Second)))
1229 resp, err := http.DefaultClient.Do(req)
1233 defer resp.Body.Close()
1234 if resp.StatusCode != http.StatusOK {
1235 return fmt.Errorf("%s", resp.Status)
1237 newtoken, err := ioutil.ReadAll(resp.Body)
1241 token = strings.TrimSpace(string(newtoken))
1242 tokenExp = time.Now().Add(ec2TokenTTL)
1244 req, err := http.NewRequestWithContext(ctx, http.MethodGet, ec2MetadataBaseURL+"/latest/meta-data/spot/instance-action", nil)
1248 req.Header.Set("X-aws-ec2-metadata-token", token)
1249 resp, err := http.DefaultClient.Do(req)
1253 defer resp.Body.Close()
1254 metadata = ec2metadata{}
1255 switch resp.StatusCode {
1258 case http.StatusNotFound:
1259 // "If Amazon EC2 is not preparing to stop or
1260 // terminate the instance, or if you
1261 // terminated the instance yourself,
1262 // instance-action is not present in the
1263 // instance metadata and you receive an HTTP
1264 // 404 error when you try to retrieve it."
1266 case http.StatusUnauthorized:
1268 return fmt.Errorf("%s", resp.Status)
1270 return fmt.Errorf("%s", resp.Status)
1272 err = json.NewDecoder(resp.Body).Decode(&metadata)
1279 var lastmetadata ec2metadata
1280 for range time.NewTicker(spotInterruptionCheckInterval).C {
1283 runner.CrunchLog.Printf("Error checking spot interruptions: %s", err)
1286 runner.CrunchLog.Printf("Giving up on checking spot interruptions after too many consecutive failures")
1292 if metadata != lastmetadata {
1293 lastmetadata = metadata
1294 text := fmt.Sprintf("Cloud provider indicates instance action %q scheduled for time %q", metadata.Action, metadata.Time.UTC().Format(time.RFC3339))
1295 runner.CrunchLog.Printf("%s", text)
1296 runner.updateRuntimeStatus(arvadosclient.Dict{
1297 "warning": "preemption notice",
1298 "warningDetail": text,
1299 "preemptionNotice": text,
1301 if proc, err := os.FindProcess(os.Getpid()); err == nil {
1302 // trigger updateLogs
1303 proc.Signal(syscall.SIGUSR1)
1309 func (runner *ContainerRunner) updateRuntimeStatus(status arvadosclient.Dict) {
1310 err := runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1311 "container": arvadosclient.Dict{
1312 "runtime_status": status,
1316 runner.CrunchLog.Printf("error updating container runtime_status: %s", err)
1320 // CaptureOutput saves data from the container's output directory if
1321 // needed, and updates the container output accordingly.
1322 func (runner *ContainerRunner) CaptureOutput(bindmounts map[string]bindmount) error {
1323 if runner.Container.RuntimeConstraints.API {
1324 // Output may have been set directly by the container, so
1325 // refresh the container record to check.
1326 err := runner.DispatcherArvClient.Get("containers", runner.Container.UUID,
1327 nil, &runner.Container)
1331 if runner.Container.Output != "" {
1332 // Container output is already set.
1333 runner.OutputPDH = &runner.Container.Output
1338 txt, err := (&copier{
1339 client: runner.containerClient,
1340 arvClient: runner.ContainerArvClient,
1341 keepClient: runner.ContainerKeepClient,
1342 hostOutputDir: runner.HostOutputDir,
1343 ctrOutputDir: runner.Container.OutputPath,
1344 bindmounts: bindmounts,
1345 mounts: runner.Container.Mounts,
1346 secretMounts: runner.SecretMounts,
1347 logger: runner.CrunchLog,
1352 if n := len(regexp.MustCompile(` [0-9a-f]+\+\S*\+R`).FindAllStringIndex(txt, -1)); n > 0 {
1353 runner.CrunchLog.Printf("Copying %d data blocks from remote input collections...", n)
1354 fs, err := (&arvados.Collection{ManifestText: txt}).FileSystem(runner.containerClient, runner.ContainerKeepClient)
1358 txt, err = fs.MarshalManifest(".")
1363 var resp arvados.Collection
1364 err = runner.ContainerArvClient.Create("collections", arvadosclient.Dict{
1365 "ensure_unique_name": true,
1366 "collection": arvadosclient.Dict{
1368 "name": "output for " + runner.Container.UUID,
1369 "manifest_text": txt,
1373 return fmt.Errorf("error creating output collection: %v", err)
1375 runner.OutputPDH = &resp.PortableDataHash
1379 func (runner *ContainerRunner) CleanupDirs() {
1380 if runner.ArvMount != nil {
1382 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1383 umount.Stdout = runner.CrunchLog
1384 umount.Stderr = runner.CrunchLog
1385 runner.CrunchLog.Printf("Running %v", umount.Args)
1386 umnterr := umount.Start()
1389 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1390 runner.ArvMount.Process.Kill()
1392 // If arv-mount --unmount gets stuck for any reason, we
1393 // don't want to wait for it forever. Do Wait() in a goroutine
1394 // so it doesn't block crunch-run.
1395 umountExit := make(chan error)
1397 mnterr := umount.Wait()
1399 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1401 umountExit <- mnterr
1404 for again := true; again; {
1410 case <-runner.ArvMountExit:
1412 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1413 runner.CrunchLog.Printf("Timed out waiting for unmount")
1415 umount.Process.Kill()
1417 runner.ArvMount.Process.Kill()
1421 runner.ArvMount = nil
1424 if runner.ArvMountPoint != "" {
1425 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1426 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1428 runner.ArvMountPoint = ""
1431 if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1432 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1436 // CommitLogs posts the collection containing the final container logs.
1437 func (runner *ContainerRunner) CommitLogs() error {
1439 // Hold cStateLock to prevent races on CrunchLog (e.g., stop()).
1440 runner.cStateLock.Lock()
1441 defer runner.cStateLock.Unlock()
1443 runner.CrunchLog.Print(runner.finalState)
1445 if runner.arvMountLog != nil {
1446 runner.arvMountLog.Close()
1448 runner.CrunchLog.Close()
1450 // Closing CrunchLog above allows them to be committed to Keep at this
1451 // point, but re-open crunch log with ArvClient in case there are any
1452 // other further errors (such as failing to write the log to Keep!)
1453 // while shutting down
1454 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{
1455 ArvClient: runner.DispatcherArvClient,
1456 UUID: runner.Container.UUID,
1457 loggingStream: "crunch-run",
1460 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1463 if runner.keepstoreLogger != nil {
1464 // Flush any buffered logs from our local keepstore
1465 // process. Discard anything logged after this point
1466 // -- it won't end up in the log collection, so
1467 // there's no point writing it to the collectionfs.
1468 runner.keepstoreLogbuf.SetWriter(io.Discard)
1469 runner.keepstoreLogger.Close()
1470 runner.keepstoreLogger = nil
1473 if runner.LogsPDH != nil {
1474 // If we have already assigned something to LogsPDH,
1475 // we must be closing the re-opened log, which won't
1476 // end up getting attached to the container record and
1477 // therefore doesn't need to be saved as a collection
1478 // -- it exists only to send logs to other channels.
1482 saved, err := runner.saveLogCollection(true)
1484 return fmt.Errorf("error saving log collection: %s", err)
1486 runner.logMtx.Lock()
1487 defer runner.logMtx.Unlock()
1488 runner.LogsPDH = &saved.PortableDataHash
1492 func (runner *ContainerRunner) saveLogCollection(final bool) (response arvados.Collection, err error) {
1493 runner.logMtx.Lock()
1494 defer runner.logMtx.Unlock()
1495 if runner.LogsPDH != nil {
1496 // Already finalized.
1499 updates := arvadosclient.Dict{
1500 "name": "logs for " + runner.Container.UUID,
1502 mt, err1 := runner.LogCollection.MarshalManifest(".")
1504 // Only send updated manifest text if there was no
1506 updates["manifest_text"] = mt
1509 // Even if flushing the manifest had an error, we still want
1510 // to update the log record, if possible, to push the trash_at
1511 // and delete_at times into the future. Details on bug
1514 updates["is_trashed"] = true
1516 exp := time.Now().Add(crunchLogUpdatePeriod * 24)
1517 updates["trash_at"] = exp
1518 updates["delete_at"] = exp
1520 reqBody := arvadosclient.Dict{"collection": updates}
1522 if runner.logUUID == "" {
1523 reqBody["ensure_unique_name"] = true
1524 err2 = runner.DispatcherArvClient.Create("collections", reqBody, &response)
1526 err2 = runner.DispatcherArvClient.Update("collections", runner.logUUID, reqBody, &response)
1529 runner.logUUID = response.UUID
1532 if err1 != nil || err2 != nil {
1533 err = fmt.Errorf("error recording logs: %q, %q", err1, err2)
1538 // UpdateContainerRunning updates the container state to "Running"
1539 func (runner *ContainerRunner) UpdateContainerRunning(logId string) error {
1540 runner.cStateLock.Lock()
1541 defer runner.cStateLock.Unlock()
1542 if runner.cCancelled {
1545 updates := arvadosclient.Dict{
1546 "gateway_address": runner.gateway.Address,
1550 updates["log"] = logId
1552 return runner.DispatcherArvClient.Update(
1554 runner.Container.UUID,
1555 arvadosclient.Dict{"container": updates},
1560 // ContainerToken returns the api_token the container (and any
1561 // arv-mount processes) are allowed to use.
1562 func (runner *ContainerRunner) ContainerToken() (string, error) {
1563 if runner.token != "" {
1564 return runner.token, nil
1567 var auth arvados.APIClientAuthorization
1568 err := runner.DispatcherArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1572 runner.token = fmt.Sprintf("v2/%s/%s/%s", auth.UUID, auth.APIToken, runner.Container.UUID)
1573 return runner.token, nil
1576 // UpdateContainerFinal updates the container record state on API
1577 // server to "Complete" or "Cancelled"
1578 func (runner *ContainerRunner) UpdateContainerFinal() error {
1579 update := arvadosclient.Dict{}
1580 update["state"] = runner.finalState
1581 if runner.LogsPDH != nil {
1582 update["log"] = *runner.LogsPDH
1584 if runner.ExitCode != nil {
1585 update["exit_code"] = *runner.ExitCode
1587 update["exit_code"] = nil
1589 if runner.finalState == "Complete" && runner.OutputPDH != nil {
1590 update["output"] = *runner.OutputPDH
1592 update["cost"] = runner.calculateCost(time.Now())
1593 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1596 // IsCancelled returns the value of Cancelled, with goroutine safety.
1597 func (runner *ContainerRunner) IsCancelled() bool {
1598 runner.cStateLock.Lock()
1599 defer runner.cStateLock.Unlock()
1600 return runner.cCancelled
1603 // NewArvLogWriter creates an ArvLogWriter
1604 func (runner *ContainerRunner) NewArvLogWriter(name string) (io.WriteCloser, error) {
1605 writer, err := runner.LogCollection.OpenFile(name+".txt", os.O_CREATE|os.O_WRONLY, 0666)
1609 return &ArvLogWriter{
1610 ArvClient: runner.DispatcherArvClient,
1611 UUID: runner.Container.UUID,
1612 loggingStream: name,
1613 writeCloser: writer,
1617 // Run the full container lifecycle.
1618 func (runner *ContainerRunner) Run() (err error) {
1619 runner.CrunchLog.Printf("crunch-run %s started", cmd.Version.String())
1620 runner.CrunchLog.Printf("%s", currentUserAndGroups())
1621 v, _ := exec.Command("arv-mount", "--version").CombinedOutput()
1622 runner.CrunchLog.Printf("Using FUSE mount: %s", v)
1623 runner.CrunchLog.Printf("Using container runtime: %s", runner.executor.Runtime())
1624 runner.CrunchLog.Printf("Executing container: %s", runner.Container.UUID)
1625 runner.costStartTime = time.Now()
1627 hostname, hosterr := os.Hostname()
1629 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1631 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1634 sigusr2 := make(chan os.Signal, 1)
1635 signal.Notify(sigusr2, syscall.SIGUSR2)
1636 defer signal.Stop(sigusr2)
1644 runner.finalState = "Queued"
1647 runner.CleanupDirs()
1649 runner.CrunchLog.Printf("crunch-run finished")
1650 runner.CrunchLog.Close()
1653 err = runner.fetchContainerRecord()
1657 if runner.Container.State != "Locked" {
1658 return fmt.Errorf("dispatch error detected: container %q has state %q", runner.Container.UUID, runner.Container.State)
1661 var bindmounts map[string]bindmount
1663 // checkErr prints e (unless it's nil) and sets err to
1664 // e (unless err is already non-nil). Thus, if err
1665 // hasn't already been assigned when Run() returns,
1666 // this cleanup func will cause Run() to return the
1667 // first non-nil error that is passed to checkErr().
1668 checkErr := func(errorIn string, e error) {
1672 runner.CrunchLog.Printf("error in %s: %v", errorIn, e)
1676 if runner.finalState == "Complete" {
1677 // There was an error in the finalization.
1678 runner.finalState = "Cancelled"
1682 // Log the error encountered in Run(), if any
1683 checkErr("Run", err)
1685 if runner.finalState == "Queued" {
1686 runner.UpdateContainerFinal()
1690 if runner.IsCancelled() {
1691 runner.finalState = "Cancelled"
1692 // but don't return yet -- we still want to
1693 // capture partial output and write logs
1696 if bindmounts != nil {
1697 checkErr("CaptureOutput", runner.CaptureOutput(bindmounts))
1699 checkErr("stopHoststat", runner.stopHoststat())
1700 checkErr("CommitLogs", runner.CommitLogs())
1701 runner.CleanupDirs()
1702 checkErr("UpdateContainerFinal", runner.UpdateContainerFinal())
1705 runner.setupSignals()
1706 err = runner.startHoststat()
1710 if runner.keepstore != nil {
1711 runner.hoststatReporter.ReportPID("keepstore", runner.keepstore.Process.Pid)
1714 // set up FUSE mount and binds
1715 bindmounts, err = runner.SetupMounts()
1717 runner.finalState = "Cancelled"
1718 err = fmt.Errorf("While setting up mounts: %v", err)
1722 // check for and/or load image
1723 imageID, err := runner.LoadImage()
1725 if !runner.checkBrokenNode(err) {
1726 // Failed to load image but not due to a "broken node"
1727 // condition, probably user error.
1728 runner.finalState = "Cancelled"
1730 err = fmt.Errorf("While loading container image: %v", err)
1734 err = runner.CreateContainer(imageID, bindmounts)
1738 err = runner.LogHostInfo()
1742 err = runner.LogNodeRecord()
1746 err = runner.LogContainerRecord()
1751 if runner.IsCancelled() {
1755 logCollection, err := runner.saveLogCollection(false)
1758 logId = logCollection.PortableDataHash
1760 runner.CrunchLog.Printf("Error committing initial log collection: %v", err)
1762 err = runner.UpdateContainerRunning(logId)
1766 runner.finalState = "Cancelled"
1768 err = runner.startCrunchstat()
1773 err = runner.StartContainer()
1775 runner.checkBrokenNode(err)
1779 err = runner.WaitFinish()
1780 if err == nil && !runner.IsCancelled() {
1781 runner.finalState = "Complete"
1786 // Fetch the current container record (uuid = runner.Container.UUID)
1787 // into runner.Container.
1788 func (runner *ContainerRunner) fetchContainerRecord() error {
1789 reader, err := runner.DispatcherArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1791 return fmt.Errorf("error fetching container record: %v", err)
1793 defer reader.Close()
1795 dec := json.NewDecoder(reader)
1797 err = dec.Decode(&runner.Container)
1799 return fmt.Errorf("error decoding container record: %v", err)
1803 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
1806 containerToken, err := runner.ContainerToken()
1808 return fmt.Errorf("error getting container token: %v", err)
1811 runner.ContainerArvClient, runner.ContainerKeepClient,
1812 runner.containerClient, err = runner.MkArvClient(containerToken)
1814 return fmt.Errorf("error creating container API client: %v", err)
1817 runner.ContainerKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1818 runner.DispatcherKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1820 err = runner.ContainerArvClient.Call("GET", "containers", runner.Container.UUID, "secret_mounts", nil, &sm)
1822 if apierr, ok := err.(arvadosclient.APIServerError); !ok || apierr.HttpStatusCode != 404 {
1823 return fmt.Errorf("error fetching secret_mounts: %v", err)
1825 // ok && apierr.HttpStatusCode == 404, which means
1826 // secret_mounts isn't supported by this API server.
1828 runner.SecretMounts = sm.SecretMounts
1833 // NewContainerRunner creates a new container runner.
1834 func NewContainerRunner(dispatcherClient *arvados.Client,
1835 dispatcherArvClient IArvadosClient,
1836 dispatcherKeepClient IKeepClient,
1837 containerUUID string) (*ContainerRunner, error) {
1839 cr := &ContainerRunner{
1840 dispatcherClient: dispatcherClient,
1841 DispatcherArvClient: dispatcherArvClient,
1842 DispatcherKeepClient: dispatcherKeepClient,
1844 cr.NewLogWriter = cr.NewArvLogWriter
1845 cr.RunArvMount = cr.ArvMountCmd
1846 cr.MkTempDir = ioutil.TempDir
1847 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1848 cl, err := arvadosclient.MakeArvadosClient()
1850 return nil, nil, nil, err
1853 kc, err := keepclient.MakeKeepClient(cl)
1855 return nil, nil, nil, err
1857 c2 := arvados.NewClientFromEnv()
1858 c2.AuthToken = token
1859 return cl, kc, c2, nil
1862 cr.LogCollection, err = (&arvados.Collection{}).FileSystem(cr.dispatcherClient, cr.DispatcherKeepClient)
1866 cr.Container.UUID = containerUUID
1867 w, err := cr.NewLogWriter("crunch-run")
1871 cr.CrunchLog = NewThrottledLogger(w)
1872 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1874 loadLogThrottleParams(dispatcherArvClient)
1880 func (command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
1881 log := log.New(stderr, "", 0)
1882 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
1883 statInterval := flags.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1884 cgroupRoot := flags.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1885 cgroupParent := flags.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1886 cgroupParentSubsystem := flags.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1887 caCertsPath := flags.String("ca-certs", "", "Path to TLS root certificates")
1888 detach := flags.Bool("detach", false, "Detach from parent process and run in the background")
1889 stdinConfig := flags.Bool("stdin-config", false, "Load config and environment variables from JSON message on stdin")
1890 configFile := flags.String("config", arvados.DefaultConfigFile, "filename of cluster config file to try loading if -stdin-config=false (default is $ARVADOS_CONFIG)")
1891 sleep := flags.Duration("sleep", 0, "Delay before starting (testing use only)")
1892 kill := flags.Int("kill", -1, "Send signal to an existing crunch-run process for given UUID")
1893 list := flags.Bool("list", false, "List UUIDs of existing crunch-run processes (and notify them to use price data passed on stdin)")
1894 enableMemoryLimit := flags.Bool("enable-memory-limit", true, "tell container runtime to limit container's memory usage")
1895 enableNetwork := flags.String("container-enable-networking", "default", "enable networking \"always\" (for all containers) or \"default\" (for containers that request it)")
1896 networkMode := flags.String("container-network-mode", "default", `Docker network mode for container (use any argument valid for docker --net)`)
1897 memprofile := flags.String("memprofile", "", "write memory profile to `file` after running container")
1898 runtimeEngine := flags.String("runtime-engine", "docker", "container runtime: docker or singularity")
1899 brokenNodeHook := flags.String("broken-node-hook", "", "script to run if node is detected to be broken (for example, Docker daemon is not running)")
1900 flags.Duration("check-containerd", 0, "Ignored. Exists for compatibility with older versions.")
1901 version := flags.Bool("version", false, "Write version information to stdout and exit 0.")
1903 ignoreDetachFlag := false
1904 if len(args) > 0 && args[0] == "-no-detach" {
1905 // This process was invoked by a parent process, which
1906 // has passed along its own arguments, including
1907 // -detach, after the leading -no-detach flag. Strip
1908 // the leading -no-detach flag (it's not recognized by
1909 // flags.Parse()) and ignore the -detach flag that
1912 ignoreDetachFlag = true
1915 if ok, code := cmd.ParseFlags(flags, prog, args, "container-uuid", stderr); !ok {
1917 } else if *version {
1918 fmt.Fprintln(stdout, prog, cmd.Version.String())
1920 } else if !*list && flags.NArg() != 1 {
1921 fmt.Fprintf(stderr, "missing required argument: container-uuid (try -help)\n")
1925 containerUUID := flags.Arg(0)
1928 case *detach && !ignoreDetachFlag:
1929 return Detach(containerUUID, prog, args, stdin, stdout, stderr)
1931 return KillProcess(containerUUID, syscall.Signal(*kill), stdout, stderr)
1933 return ListProcesses(stdin, stdout, stderr)
1936 if len(containerUUID) != 27 {
1937 log.Printf("usage: %s [options] UUID", prog)
1941 var keepstoreLogbuf bufThenWrite
1944 err := json.NewDecoder(stdin).Decode(&conf)
1946 log.Printf("decode stdin: %s", err)
1949 for k, v := range conf.Env {
1950 err = os.Setenv(k, v)
1952 log.Printf("setenv(%q): %s", k, err)
1956 if conf.Cluster != nil {
1957 // ClusterID is missing from the JSON
1958 // representation, but we need it to generate
1959 // a valid config file for keepstore, so we
1960 // fill it using the container UUID prefix.
1961 conf.Cluster.ClusterID = containerUUID[:5]
1964 conf = hpcConfData(containerUUID, *configFile, io.MultiWriter(&keepstoreLogbuf, stderr))
1967 log.Printf("crunch-run %s started", cmd.Version.String())
1970 if *caCertsPath != "" {
1971 arvadosclient.CertFiles = []string{*caCertsPath}
1974 keepstore, err := startLocalKeepstore(conf, io.MultiWriter(&keepstoreLogbuf, stderr))
1979 if keepstore != nil {
1980 defer keepstore.Process.Kill()
1983 api, err := arvadosclient.MakeArvadosClient()
1985 log.Printf("%s: %v", containerUUID, err)
1990 kc, err := keepclient.MakeKeepClient(api)
1992 log.Printf("%s: %v", containerUUID, err)
1995 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1998 cr, err := NewContainerRunner(arvados.NewClientFromEnv(), api, kc, containerUUID)
2004 cr.keepstore = keepstore
2005 if keepstore == nil {
2006 // Log explanation (if any) for why we're not running
2007 // a local keepstore.
2008 var buf bytes.Buffer
2009 keepstoreLogbuf.SetWriter(&buf)
2011 cr.CrunchLog.Printf("%s", strings.TrimSpace(buf.String()))
2013 } else if logWhat := conf.Cluster.Containers.LocalKeepLogsToContainerLog; logWhat == "none" {
2014 cr.CrunchLog.Printf("using local keepstore process (pid %d) at %s", keepstore.Process.Pid, os.Getenv("ARVADOS_KEEP_SERVICES"))
2015 keepstoreLogbuf.SetWriter(io.Discard)
2017 cr.CrunchLog.Printf("using local keepstore process (pid %d) at %s, writing logs to keepstore.txt in log collection", keepstore.Process.Pid, os.Getenv("ARVADOS_KEEP_SERVICES"))
2018 logwriter, err := cr.NewLogWriter("keepstore")
2023 cr.keepstoreLogger = NewThrottledLogger(logwriter)
2025 var writer io.WriteCloser = cr.keepstoreLogger
2026 if logWhat == "errors" {
2027 writer = &filterKeepstoreErrorsOnly{WriteCloser: writer}
2028 } else if logWhat != "all" {
2029 // should have been caught earlier by
2030 // dispatcher's config loader
2031 log.Printf("invalid value for Containers.LocalKeepLogsToContainerLog: %q", logWhat)
2034 err = keepstoreLogbuf.SetWriter(writer)
2039 cr.keepstoreLogbuf = &keepstoreLogbuf
2042 switch *runtimeEngine {
2044 cr.executor, err = newDockerExecutor(containerUUID, cr.CrunchLog.Printf, cr.containerWatchdogInterval)
2046 cr.executor, err = newSingularityExecutor(cr.CrunchLog.Printf)
2048 cr.CrunchLog.Printf("%s: unsupported RuntimeEngine %q", containerUUID, *runtimeEngine)
2049 cr.CrunchLog.Close()
2053 cr.CrunchLog.Printf("%s: %v", containerUUID, err)
2054 cr.checkBrokenNode(err)
2055 cr.CrunchLog.Close()
2058 defer cr.executor.Close()
2060 cr.brokenNodeHook = *brokenNodeHook
2062 gwAuthSecret := os.Getenv("GatewayAuthSecret")
2063 os.Unsetenv("GatewayAuthSecret")
2064 if gwAuthSecret == "" {
2065 // not safe to run a gateway service without an auth
2067 cr.CrunchLog.Printf("Not starting a gateway server (GatewayAuthSecret was not provided by dispatcher)")
2069 gwListen := os.Getenv("GatewayAddress")
2070 cr.gateway = Gateway{
2072 AuthSecret: gwAuthSecret,
2073 ContainerUUID: containerUUID,
2074 Target: cr.executor,
2078 // Direct connection won't work, so we use the
2079 // gateway_address field to indicate the
2080 // internalURL of the controller process that
2081 // has the current tunnel connection.
2082 cr.gateway.ArvadosClient = cr.dispatcherClient
2083 cr.gateway.UpdateTunnelURL = func(url string) {
2084 cr.gateway.Address = "tunnel " + url
2085 cr.DispatcherArvClient.Update("containers", containerUUID,
2086 arvadosclient.Dict{"container": arvadosclient.Dict{"gateway_address": cr.gateway.Address}}, nil)
2089 err = cr.gateway.Start()
2091 log.Printf("error starting gateway server: %s", err)
2096 parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerUUID+".")
2098 log.Printf("%s: %v", containerUUID, tmperr)
2102 cr.parentTemp = parentTemp
2103 cr.statInterval = *statInterval
2104 cr.cgroupRoot = *cgroupRoot
2105 cr.expectCgroupParent = *cgroupParent
2106 cr.enableMemoryLimit = *enableMemoryLimit
2107 cr.enableNetwork = *enableNetwork
2108 cr.networkMode = *networkMode
2109 if *cgroupParentSubsystem != "" {
2110 p, err := findCgroup(*cgroupParentSubsystem)
2112 log.Printf("fatal: cgroup parent subsystem: %s", err)
2115 cr.setCgroupParent = p
2116 cr.expectCgroupParent = p
2119 if conf.EC2SpotCheck {
2120 go cr.checkSpotInterruptionNotices()
2125 if *memprofile != "" {
2126 f, err := os.Create(*memprofile)
2128 log.Printf("could not create memory profile: %s", err)
2130 runtime.GC() // get up-to-date statistics
2131 if err := pprof.WriteHeapProfile(f); err != nil {
2132 log.Printf("could not write memory profile: %s", err)
2134 closeerr := f.Close()
2135 if closeerr != nil {
2136 log.Printf("closing memprofile file: %s", err)
2141 log.Printf("%s: %v", containerUUID, runerr)
2147 // Try to load ConfigData in hpc (slurm/lsf) environment. This means
2148 // loading the cluster config from the specified file and (if that
2149 // works) getting the runtime_constraints container field from
2150 // controller to determine # VCPUs so we can calculate KeepBuffers.
2151 func hpcConfData(uuid string, configFile string, stderr io.Writer) ConfigData {
2153 conf.Cluster = loadClusterConfigFile(configFile, stderr)
2154 if conf.Cluster == nil {
2155 // skip loading the container record -- we won't be
2156 // able to start local keepstore anyway.
2159 arv, err := arvadosclient.MakeArvadosClient()
2161 fmt.Fprintf(stderr, "error setting up arvadosclient: %s\n", err)
2165 var ctr arvados.Container
2166 err = arv.Call("GET", "containers", uuid, "", arvadosclient.Dict{"select": []string{"runtime_constraints"}}, &ctr)
2168 fmt.Fprintf(stderr, "error getting container record: %s\n", err)
2171 if ctr.RuntimeConstraints.VCPUs > 0 {
2172 conf.KeepBuffers = ctr.RuntimeConstraints.VCPUs * conf.Cluster.Containers.LocalKeepBlobBuffersPerVCPU
2177 // Load cluster config file from given path. If an error occurs, log
2178 // the error to stderr and return nil.
2179 func loadClusterConfigFile(path string, stderr io.Writer) *arvados.Cluster {
2180 ldr := config.NewLoader(&bytes.Buffer{}, ctxlog.New(stderr, "plain", "info"))
2182 cfg, err := ldr.Load()
2184 fmt.Fprintf(stderr, "could not load config file %s: %s\n", path, err)
2187 cluster, err := cfg.GetCluster("")
2189 fmt.Fprintf(stderr, "could not use config file %s: %s\n", path, err)
2192 fmt.Fprintf(stderr, "loaded config file %s\n", path)
2196 func startLocalKeepstore(configData ConfigData, logbuf io.Writer) (*exec.Cmd, error) {
2197 if configData.KeepBuffers < 1 {
2198 fmt.Fprintf(logbuf, "not starting a local keepstore process because KeepBuffers=%v in config\n", configData.KeepBuffers)
2201 if configData.Cluster == nil {
2202 fmt.Fprint(logbuf, "not starting a local keepstore process because cluster config file was not loaded\n")
2205 for uuid, vol := range configData.Cluster.Volumes {
2206 if len(vol.AccessViaHosts) > 0 {
2207 fmt.Fprintf(logbuf, "not starting a local keepstore process because a volume (%s) uses AccessViaHosts\n", uuid)
2210 if !vol.ReadOnly && vol.Replication < configData.Cluster.Collections.DefaultReplication {
2211 fmt.Fprintf(logbuf, "not starting a local keepstore process because a writable volume (%s) has replication less than Collections.DefaultReplication (%d < %d)\n", uuid, vol.Replication, configData.Cluster.Collections.DefaultReplication)
2216 // Rather than have an alternate way to tell keepstore how
2217 // many buffers to use when starting it this way, we just
2218 // modify the cluster configuration that we feed it on stdin.
2219 configData.Cluster.API.MaxKeepBlobBuffers = configData.KeepBuffers
2221 localaddr := localKeepstoreAddr()
2222 ln, err := net.Listen("tcp", net.JoinHostPort(localaddr, "0"))
2226 _, port, err := net.SplitHostPort(ln.Addr().String())
2232 url := "http://" + net.JoinHostPort(localaddr, port)
2234 fmt.Fprintf(logbuf, "starting keepstore on %s\n", url)
2236 var confJSON bytes.Buffer
2237 err = json.NewEncoder(&confJSON).Encode(arvados.Config{
2238 Clusters: map[string]arvados.Cluster{
2239 configData.Cluster.ClusterID: *configData.Cluster,
2245 cmd := exec.Command("/proc/self/exe", "keepstore", "-config=-")
2246 if target, err := os.Readlink(cmd.Path); err == nil && strings.HasSuffix(target, ".test") {
2247 // If we're a 'go test' process, running
2248 // /proc/self/exe would start the test suite in a
2249 // child process, which is not what we want.
2250 cmd.Path, _ = exec.LookPath("go")
2251 cmd.Args = append([]string{"go", "run", "../../cmd/arvados-server"}, cmd.Args[1:]...)
2252 cmd.Env = os.Environ()
2254 cmd.Stdin = &confJSON
2257 cmd.Env = append(cmd.Env,
2259 "ARVADOS_SERVICE_INTERNAL_URL="+url)
2262 return nil, fmt.Errorf("error starting keepstore process: %w", err)
2269 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*10))
2271 poll := time.NewTicker(time.Second / 10)
2273 client := http.Client{}
2275 testReq, err := http.NewRequestWithContext(ctx, "GET", url+"/_health/ping", nil)
2276 testReq.Header.Set("Authorization", "Bearer "+configData.Cluster.ManagementToken)
2280 resp, err := client.Do(testReq)
2283 if resp.StatusCode == http.StatusOK {
2288 return nil, fmt.Errorf("keepstore child process exited")
2290 if ctx.Err() != nil {
2291 return nil, fmt.Errorf("timed out waiting for new keepstore process to report healthy")
2294 os.Setenv("ARVADOS_KEEP_SERVICES", url)
2298 // return current uid, gid, groups in a format suitable for logging:
2299 // "crunch-run process has uid=1234(arvados) gid=1234(arvados)
2300 // groups=1234(arvados),114(fuse)"
2301 func currentUserAndGroups() string {
2302 u, err := user.Current()
2304 return fmt.Sprintf("error getting current user ID: %s", err)
2306 s := fmt.Sprintf("crunch-run process has uid=%s(%s) gid=%s", u.Uid, u.Username, u.Gid)
2307 if g, err := user.LookupGroupId(u.Gid); err == nil {
2308 s += fmt.Sprintf("(%s)", g.Name)
2311 if gids, err := u.GroupIds(); err == nil {
2312 for i, gid := range gids {
2317 if g, err := user.LookupGroupId(gid); err == nil {
2318 s += fmt.Sprintf("(%s)", g.Name)
2325 // Return a suitable local interface address for a local keepstore
2326 // service. Currently this is the numerically lowest non-loopback ipv4
2327 // address assigned to a local interface that is not in any of the
2328 // link-local/vpn/loopback ranges 169.254/16, 100.64/10, or 127/8.
2329 func localKeepstoreAddr() string {
2331 // Ignore error (proceed with zero IPs)
2332 addrs, _ := processIPs(os.Getpid())
2333 for addr := range addrs {
2334 ip := net.ParseIP(addr)
2339 if ip.Mask(net.CIDRMask(8, 32)).Equal(net.IPv4(127, 0, 0, 0)) ||
2340 ip.Mask(net.CIDRMask(10, 32)).Equal(net.IPv4(100, 64, 0, 0)) ||
2341 ip.Mask(net.CIDRMask(16, 32)).Equal(net.IPv4(169, 254, 0, 0)) {
2345 ips = append(ips, ip)
2350 sort.Slice(ips, func(ii, jj int) bool {
2351 i, j := ips[ii], ips[jj]
2352 if len(i) != len(j) {
2353 return len(i) < len(j)
2362 return ips[0].String()
2365 func (cr *ContainerRunner) loadPrices() {
2366 buf, err := os.ReadFile(filepath.Join(lockdir, pricesfile))
2368 if !os.IsNotExist(err) {
2369 cr.CrunchLog.Printf("loadPrices: read: %s", err)
2373 var prices []cloud.InstancePrice
2374 err = json.Unmarshal(buf, &prices)
2376 cr.CrunchLog.Printf("loadPrices: decode: %s", err)
2379 cr.pricesLock.Lock()
2380 defer cr.pricesLock.Unlock()
2381 var lastKnown time.Time
2382 if len(cr.prices) > 0 {
2383 lastKnown = cr.prices[0].StartTime
2385 cr.prices = cloud.NormalizePriceHistory(append(prices, cr.prices...))
2386 for i := len(cr.prices) - 1; i >= 0; i-- {
2387 price := cr.prices[i]
2388 if price.StartTime.After(lastKnown) {
2389 cr.CrunchLog.Printf("Instance price changed to %#.3g at %s", price.Price, price.StartTime.UTC())
2394 func (cr *ContainerRunner) calculateCost(now time.Time) float64 {
2395 cr.pricesLock.Lock()
2396 defer cr.pricesLock.Unlock()
2398 // First, make a "prices" slice with the real data as far back
2399 // as it goes, and (if needed) a "since the beginning of time"
2400 // placeholder containing a reasonable guess about what the
2401 // price was between cr.costStartTime and the earliest real
2404 if len(prices) == 0 {
2405 // use price info in InstanceType record initially
2406 // provided by cloud dispatcher
2408 var it arvados.InstanceType
2409 if j := os.Getenv("InstanceType"); j != "" && json.Unmarshal([]byte(j), &it) == nil && it.Price > 0 {
2412 prices = []cloud.InstancePrice{{Price: p}}
2413 } else if prices[len(prices)-1].StartTime.After(cr.costStartTime) {
2414 // guess earlier pricing was the same as the earliest
2415 // price we know about
2416 filler := prices[len(prices)-1]
2417 filler.StartTime = time.Time{}
2418 prices = append(prices, filler)
2421 // Now that our history of price changes goes back at least as
2422 // far as cr.costStartTime, add up the costs for each
2426 for _, ip := range prices {
2427 spanStart := ip.StartTime
2428 if spanStart.After(now) {
2429 // pricing information from the future -- not
2430 // expected from AWS, but possible in
2431 // principle, and exercised by tests.
2435 if spanStart.Before(cr.costStartTime) {
2436 spanStart = cr.costStartTime
2439 cost += ip.Price * spanEnd.Sub(spanStart).Seconds() / 3600