1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
35 "git.arvados.org/arvados.git/lib/cloud"
36 "git.arvados.org/arvados.git/lib/cmd"
37 "git.arvados.org/arvados.git/lib/config"
38 "git.arvados.org/arvados.git/lib/crunchstat"
39 "git.arvados.org/arvados.git/sdk/go/arvados"
40 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
41 "git.arvados.org/arvados.git/sdk/go/ctxlog"
42 "git.arvados.org/arvados.git/sdk/go/keepclient"
43 "golang.org/x/sys/unix"
48 var arvadosCertPath = "/etc/arvados/ca-certificates.crt"
50 var Command = command{}
52 // ConfigData contains environment variables and (when needed) cluster
53 // configuration, passed from dispatchcloud to crunch-run on stdin.
54 type ConfigData struct {
58 Cluster *arvados.Cluster
61 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
62 type IArvadosClient interface {
63 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
64 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
65 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
66 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
67 CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
68 Discovery(key string) (interface{}, error)
71 // ErrCancelled is the error returned when the container is cancelled.
72 var ErrCancelled = errors.New("Cancelled")
74 // IKeepClient is the minimal Keep API methods used by crunch-run.
75 type IKeepClient interface {
76 BlockWrite(context.Context, arvados.BlockWriteOptions) (arvados.BlockWriteResponse, error)
77 ReadAt(locator string, p []byte, off int) (int, error)
78 LocalLocator(locator string) (string, error)
79 SetStorageClasses(sc []string)
82 type RunArvMount func(cmdline []string, tok string) (*exec.Cmd, error)
84 type MkTempDir func(string, string) (string, error)
86 type PsProcess interface {
87 CmdlineSlice() ([]string, error)
90 // ContainerRunner is the main stateful struct used for a single execution of a
92 type ContainerRunner struct {
93 executor containerExecutor
94 executorStdin io.Closer
95 executorStdout io.Closer
96 executorStderr io.Closer
98 // Dispatcher client is initialized with the Dispatcher token.
99 // This is a privileged token used to manage container status
102 // We have both dispatcherClient and DispatcherArvClient
103 // because there are two different incompatible Arvados Go
104 // SDKs and we have to use both (hopefully this gets fixed in
106 dispatcherClient *arvados.Client
107 DispatcherArvClient IArvadosClient
108 DispatcherKeepClient IKeepClient
110 // Container client is initialized with the Container token
111 // This token controls the permissions of the container, and
112 // must be used for operations such as reading collections.
114 // Same comment as above applies to
115 // containerClient/ContainerArvClient.
116 containerClient *arvados.Client
117 ContainerArvClient IArvadosClient
118 ContainerKeepClient IKeepClient
120 Container arvados.Container
126 LogCollection arvados.CollectionFileSystem
128 RunArvMount RunArvMount
133 Volumes map[string]struct{}
135 SigChan chan os.Signal
136 ArvMountExit chan error
137 SecretMounts map[string]arvados.Mount
138 MkArvClient func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error)
141 costStartTime time.Time
144 keepstoreLogger io.WriteCloser
145 keepstoreLogbuf *bufThenWrite
146 statLogger io.WriteCloser
147 statReporter *crunchstat.Reporter
148 hoststatLogger io.WriteCloser
149 hoststatReporter *crunchstat.Reporter
150 statInterval time.Duration
151 // What we tell docker to use as the container's cgroup
153 setCgroupParent string
154 // Fake root dir where crunchstat.Reporter should read OS
155 // files, for testing.
156 crunchstatFakeFS fs.FS
158 cStateLock sync.Mutex
159 cCancelled bool // StopContainer() invoked
161 enableMemoryLimit bool
162 enableNetwork string // one of "default" or "always"
163 networkMode string // "none", "host", or "" -- passed through to executor
164 brokenNodeHook string // script to run if node appears to be broken
165 arvMountLog io.WriteCloser
167 containerWatchdogInterval time.Duration
171 prices []cloud.InstancePrice
172 pricesLock sync.Mutex
175 // setupSignals sets up signal handling to gracefully terminate the
176 // underlying container and update state when receiving a TERM, INT or
178 func (runner *ContainerRunner) setupSignals() {
179 runner.SigChan = make(chan os.Signal, 1)
180 signal.Notify(runner.SigChan, syscall.SIGTERM)
181 signal.Notify(runner.SigChan, syscall.SIGINT)
182 signal.Notify(runner.SigChan, syscall.SIGQUIT)
184 go func(sig chan os.Signal) {
191 // stop the underlying container.
192 func (runner *ContainerRunner) stop(sig os.Signal) {
193 runner.cStateLock.Lock()
194 defer runner.cStateLock.Unlock()
196 runner.CrunchLog.Printf("caught signal: %v", sig)
198 runner.cCancelled = true
199 runner.CrunchLog.Printf("stopping container")
200 err := runner.executor.Stop()
202 runner.CrunchLog.Printf("error stopping container: %s", err)
206 var errorBlacklist = []string{
207 "(?ms).*[Cc]annot connect to the Docker daemon.*",
208 "(?ms).*oci runtime error.*starting container process.*container init.*mounting.*to rootfs.*no such file or directory.*",
209 "(?ms).*grpc: the connection is unavailable.*",
212 func (runner *ContainerRunner) runBrokenNodeHook() {
213 if runner.brokenNodeHook == "" {
214 path := filepath.Join(lockdir, brokenfile)
215 runner.CrunchLog.Printf("Writing %s to mark node as broken", path)
216 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0700)
218 runner.CrunchLog.Printf("Error writing %s: %s", path, err)
223 runner.CrunchLog.Printf("Running broken node hook %q", runner.brokenNodeHook)
225 c := exec.Command(runner.brokenNodeHook)
226 c.Stdout = runner.CrunchLog
227 c.Stderr = runner.CrunchLog
230 runner.CrunchLog.Printf("Error running broken node hook: %v", err)
235 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
236 for _, d := range errorBlacklist {
237 if m, e := regexp.MatchString(d, goterr.Error()); m && e == nil {
238 runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
239 runner.runBrokenNodeHook()
246 // LoadImage determines the docker image id from the container record and
247 // checks if it is available in the local Docker image store. If not, it loads
248 // the image from Keep.
249 func (runner *ContainerRunner) LoadImage() (string, error) {
250 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
252 d, err := os.Open(runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage)
257 allfiles, err := d.Readdirnames(-1)
261 var tarfiles []string
262 for _, fnm := range allfiles {
263 if strings.HasSuffix(fnm, ".tar") {
264 tarfiles = append(tarfiles, fnm)
267 if len(tarfiles) == 0 {
268 return "", fmt.Errorf("image collection does not include a .tar image file")
270 if len(tarfiles) > 1 {
271 return "", fmt.Errorf("cannot choose from multiple tar files in image collection: %v", tarfiles)
273 imageID := tarfiles[0][:len(tarfiles[0])-4]
274 imageTarballPath := runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage + "/" + imageID + ".tar"
275 runner.CrunchLog.Printf("Using Docker image id %q", imageID)
277 runner.CrunchLog.Print("Loading Docker image from keep")
278 err = runner.executor.LoadImage(imageID, imageTarballPath, runner.Container, runner.ArvMountPoint,
279 runner.containerClient)
287 func (runner *ContainerRunner) ArvMountCmd(cmdline []string, token string) (c *exec.Cmd, err error) {
288 c = exec.Command(cmdline[0], cmdline[1:]...)
290 // Copy our environment, but override ARVADOS_API_TOKEN with
291 // the container auth token.
293 for _, s := range os.Environ() {
294 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
295 c.Env = append(c.Env, s)
298 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
300 runner.arvMountLog, err = runner.openLogFile("arv-mount")
304 scanner := logScanner{
307 "Block not found error",
308 "Unhandled exception during FUSE operation",
310 ReportFunc: func(pattern, text string) {
311 runner.updateRuntimeStatus(arvadosclient.Dict{
312 "warning": "arv-mount: " + pattern,
313 "warningDetail": text,
317 c.Stdout = newTimestamper(io.MultiWriter(runner.arvMountLog, os.Stderr))
318 c.Stderr = io.MultiWriter(&scanner, newTimestamper(io.MultiWriter(runner.arvMountLog, os.Stderr)))
320 runner.CrunchLog.Printf("Running %v", c.Args)
327 statReadme := make(chan bool)
328 runner.ArvMountExit = make(chan error)
333 time.Sleep(100 * time.Millisecond)
334 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
346 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
348 runner.ArvMountExit <- mnterr
349 close(runner.ArvMountExit)
355 case err := <-runner.ArvMountExit:
356 runner.ArvMount = nil
364 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
365 if runner.ArvMountPoint == "" {
366 runner.ArvMountPoint, err = runner.MkTempDir(runner.parentTemp, prefix)
371 func copyfile(src string, dst string) (err error) {
372 srcfile, err := os.Open(src)
377 os.MkdirAll(path.Dir(dst), 0777)
379 dstfile, err := os.Create(dst)
383 _, err = io.Copy(dstfile, srcfile)
388 err = srcfile.Close()
389 err2 := dstfile.Close()
402 func (runner *ContainerRunner) SetupMounts() (map[string]bindmount, error) {
403 bindmounts := map[string]bindmount{}
404 err := runner.SetupArvMountPoint("keep")
406 return nil, fmt.Errorf("While creating keep mount temp dir: %v", err)
409 token, err := runner.ContainerToken()
411 return nil, fmt.Errorf("could not get container token: %s", err)
413 runner.CrunchLog.Printf("container token %q", token)
417 arvMountCmd := []string{
421 "--storage-classes", strings.Join(runner.Container.OutputStorageClasses, ","),
422 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
424 if _, isdocker := runner.executor.(*dockerExecutor); isdocker {
425 arvMountCmd = append(arvMountCmd, "--allow-other")
428 if runner.Container.RuntimeConstraints.KeepCacheDisk > 0 {
429 keepcachedir, err := runner.MkTempDir(runner.parentTemp, "keepcache")
431 return nil, fmt.Errorf("while creating keep cache temp dir: %v", err)
433 arvMountCmd = append(arvMountCmd, "--disk-cache", "--disk-cache-dir", keepcachedir, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheDisk))
434 } else if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
435 arvMountCmd = append(arvMountCmd, "--ram-cache", "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
438 collectionPaths := []string{}
439 needCertMount := true
440 type copyFile struct {
444 var copyFiles []copyFile
447 for bind := range runner.Container.Mounts {
448 binds = append(binds, bind)
450 for bind := range runner.SecretMounts {
451 if _, ok := runner.Container.Mounts[bind]; ok {
452 return nil, fmt.Errorf("secret mount %q conflicts with regular mount", bind)
454 if runner.SecretMounts[bind].Kind != "json" &&
455 runner.SecretMounts[bind].Kind != "text" {
456 return nil, fmt.Errorf("secret mount %q type is %q but only 'json' and 'text' are permitted",
457 bind, runner.SecretMounts[bind].Kind)
459 binds = append(binds, bind)
463 for _, bind := range binds {
464 mnt, notSecret := runner.Container.Mounts[bind]
466 mnt = runner.SecretMounts[bind]
468 if bind == "stdout" || bind == "stderr" {
469 // Is it a "file" mount kind?
470 if mnt.Kind != "file" {
471 return nil, fmt.Errorf("unsupported mount kind '%s' for %s: only 'file' is supported", mnt.Kind, bind)
474 // Does path start with OutputPath?
475 prefix := runner.Container.OutputPath
476 if !strings.HasSuffix(prefix, "/") {
479 if !strings.HasPrefix(mnt.Path, prefix) {
480 return nil, fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
485 // Is it a "collection" mount kind?
486 if mnt.Kind != "collection" && mnt.Kind != "json" {
487 return nil, fmt.Errorf("unsupported mount kind '%s' for stdin: only 'collection' and 'json' are supported", mnt.Kind)
491 if bind == arvadosCertPath {
492 needCertMount = false
495 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
496 if mnt.Kind != "collection" && mnt.Kind != "text" && mnt.Kind != "json" {
497 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)
502 case mnt.Kind == "collection" && bind != "stdin":
504 if mnt.UUID != "" && mnt.PortableDataHash != "" {
505 return nil, fmt.Errorf("cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
509 return nil, fmt.Errorf("writing to existing collections currently not permitted")
512 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
513 } else if mnt.PortableDataHash != "" {
514 if mnt.Writable && !strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
515 return nil, fmt.Errorf("can never write to a collection specified by portable data hash")
517 idx := strings.Index(mnt.PortableDataHash, "/")
519 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
520 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
521 runner.Container.Mounts[bind] = mnt
523 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
524 if mnt.Path != "" && mnt.Path != "." {
525 if strings.HasPrefix(mnt.Path, "./") {
526 mnt.Path = mnt.Path[2:]
527 } else if strings.HasPrefix(mnt.Path, "/") {
528 mnt.Path = mnt.Path[1:]
530 src += "/" + mnt.Path
533 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
534 arvMountCmd = append(arvMountCmd, "--mount-tmp", fmt.Sprintf("tmp%d", tmpcount))
538 if bind == runner.Container.OutputPath {
539 runner.HostOutputDir = src
540 bindmounts[bind] = bindmount{HostPath: src}
541 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
542 copyFiles = append(copyFiles, copyFile{src, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
544 bindmounts[bind] = bindmount{HostPath: src}
547 bindmounts[bind] = bindmount{HostPath: src, ReadOnly: true}
549 collectionPaths = append(collectionPaths, src)
551 case mnt.Kind == "tmp":
553 tmpdir, err = runner.MkTempDir(runner.parentTemp, "tmp")
555 return nil, fmt.Errorf("while creating mount temp dir: %v", err)
557 st, staterr := os.Stat(tmpdir)
559 return nil, fmt.Errorf("while Stat on temp dir: %v", staterr)
561 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
563 return nil, fmt.Errorf("while Chmod temp dir: %v", err)
565 bindmounts[bind] = bindmount{HostPath: tmpdir}
566 if bind == runner.Container.OutputPath {
567 runner.HostOutputDir = tmpdir
570 case mnt.Kind == "json" || mnt.Kind == "text":
572 if mnt.Kind == "json" {
573 filedata, err = json.Marshal(mnt.Content)
575 return nil, fmt.Errorf("encoding json data: %v", err)
578 text, ok := mnt.Content.(string)
580 return nil, fmt.Errorf("content for mount %q must be a string", bind)
582 filedata = []byte(text)
585 tmpdir, err := runner.MkTempDir(runner.parentTemp, mnt.Kind)
587 return nil, fmt.Errorf("creating temp dir: %v", err)
589 tmpfn := filepath.Join(tmpdir, "mountdata."+mnt.Kind)
590 err = ioutil.WriteFile(tmpfn, filedata, 0444)
592 return nil, fmt.Errorf("writing temp file: %v", err)
594 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && (notSecret || runner.Container.Mounts[runner.Container.OutputPath].Kind != "collection") {
595 // In most cases, if the container
596 // specifies a literal file inside the
597 // output path, we copy it into the
598 // output directory (either a mounted
599 // collection or a staging area on the
600 // host fs). If it's a secret, it will
601 // be skipped when copying output from
602 // staging to Keep later.
603 copyFiles = append(copyFiles, copyFile{tmpfn, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
605 // If a secret is outside OutputPath,
606 // we bind mount the secret file
607 // directly just like other mounts. We
608 // also use this strategy when a
609 // secret is inside OutputPath but
610 // OutputPath is a live collection, to
611 // avoid writing the secret to
612 // Keep. Attempting to remove a
613 // bind-mounted secret file from
614 // inside the container will return a
615 // "Device or resource busy" error
616 // that might not be handled well by
617 // the container, which is why we
618 // don't use this strategy when
619 // OutputPath is a staging directory.
620 bindmounts[bind] = bindmount{HostPath: tmpfn, ReadOnly: true}
625 if runner.HostOutputDir == "" {
626 return nil, fmt.Errorf("output path does not correspond to a writable mount point")
629 if needCertMount && runner.Container.RuntimeConstraints.API {
630 for _, certfile := range []string{
631 // Populated by caller, or sdk/go/arvados init(), or test suite:
632 os.Getenv("SSL_CERT_FILE"),
633 // Copied from Go 1.21 stdlib (src/crypto/x509/root_linux.go):
634 "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu/Gentoo etc.
635 "/etc/pki/tls/certs/ca-bundle.crt", // Fedora/RHEL 6
636 "/etc/ssl/ca-bundle.pem", // OpenSUSE
637 "/etc/pki/tls/cacert.pem", // OpenELEC
638 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", // CentOS/RHEL 7
639 "/etc/ssl/cert.pem", // Alpine Linux
641 if _, err := os.Stat(certfile); err == nil {
642 bindmounts[arvadosCertPath] = bindmount{HostPath: certfile, ReadOnly: true}
649 // If we are only mounting collections by pdh, make
650 // sure we don't subscribe to websocket events to
651 // avoid putting undesired load on the API server
652 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id", "--disable-event-listening")
654 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
656 // the by_uuid mount point is used by singularity when writing
657 // out docker images converted to SIF
658 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_uuid")
659 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
661 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
663 return nil, fmt.Errorf("while trying to start arv-mount: %v", err)
665 if runner.hoststatReporter != nil && runner.ArvMount != nil {
666 runner.hoststatReporter.ReportPID("arv-mount", runner.ArvMount.Process.Pid)
669 for _, p := range collectionPaths {
672 return nil, fmt.Errorf("while checking that input files exist: %v", err)
676 for _, cp := range copyFiles {
677 st, err := os.Stat(cp.src)
679 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
682 err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
686 target := path.Join(cp.bind, walkpath[len(cp.src):])
687 if walkinfo.Mode().IsRegular() {
688 copyerr := copyfile(walkpath, target)
692 return os.Chmod(target, walkinfo.Mode()|0777)
693 } else if walkinfo.Mode().IsDir() {
694 mkerr := os.MkdirAll(target, 0777)
698 return os.Chmod(target, walkinfo.Mode()|os.ModeSetgid|0777)
700 return fmt.Errorf("source %q is not a regular file or directory", cp.src)
703 } else if st.Mode().IsRegular() {
704 err = copyfile(cp.src, cp.bind)
706 err = os.Chmod(cp.bind, st.Mode()|0777)
710 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
714 return bindmounts, nil
717 func (runner *ContainerRunner) stopHoststat() error {
718 if runner.hoststatReporter == nil {
721 runner.hoststatReporter.Stop()
722 runner.hoststatReporter.LogProcessMemMax(runner.CrunchLog)
723 err := runner.hoststatLogger.Close()
725 return fmt.Errorf("error closing hoststat logs: %v", err)
730 func (runner *ContainerRunner) startHoststat() error {
732 runner.hoststatLogger, err = runner.openLogFile("hoststat")
736 runner.hoststatReporter = &crunchstat.Reporter{
737 Logger: newLogWriter(newTimestamper(runner.hoststatLogger)),
738 // Our own cgroup is the "host" cgroup, in the sense
739 // that it accounts for resource usage outside the
740 // container. It doesn't count _all_ resource usage on
743 // TODO?: Use the furthest ancestor of our own cgroup
744 // that has stats available. (Currently crunchstat
745 // does not have that capability.)
747 PollPeriod: runner.statInterval,
749 runner.hoststatReporter.Start()
750 runner.hoststatReporter.ReportPID("crunch-run", os.Getpid())
754 func (runner *ContainerRunner) startCrunchstat() error {
756 runner.statLogger, err = runner.openLogFile("crunchstat")
760 runner.statReporter = &crunchstat.Reporter{
761 Pid: runner.executor.Pid,
762 FS: runner.crunchstatFakeFS,
763 Logger: newLogWriter(newTimestamper(runner.statLogger)),
764 MemThresholds: map[string][]crunchstat.Threshold{
765 "rss": crunchstat.NewThresholdsFromPercentages(runner.Container.RuntimeConstraints.RAM, []int64{90, 95, 99}),
767 PollPeriod: runner.statInterval,
768 TempDir: runner.parentTemp,
769 ThresholdLogger: runner.CrunchLog,
771 runner.statReporter.Start()
775 type infoCommand struct {
780 // LogHostInfo logs info about the current host, for debugging and
781 // accounting purposes. Although it's logged as "node-info", this is
782 // about the environment where crunch-run is actually running, which
783 // might differ from what's described in the node record (see
785 func (runner *ContainerRunner) LogHostInfo() (err error) {
786 w, err := runner.openLogFile("node-info")
791 commands := []infoCommand{
793 label: "Host Information",
794 cmd: []string{"uname", "-a"},
797 label: "CPU Information",
798 cmd: []string{"cat", "/proc/cpuinfo"},
801 label: "Memory Information",
802 cmd: []string{"cat", "/proc/meminfo"},
806 cmd: []string{"df", "-m", "/", os.TempDir()},
809 label: "Disk INodes",
810 cmd: []string{"df", "-i", "/", os.TempDir()},
814 // Run commands with informational output to be logged.
815 for _, command := range commands {
816 fmt.Fprintln(w, command.label)
817 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
820 if err := cmd.Run(); err != nil {
821 err = fmt.Errorf("While running command %q: %v", command.cmd, err)
830 return fmt.Errorf("While closing node-info logs: %v", err)
835 // LogContainerRecord gets and saves the raw JSON container record from the API server
836 func (runner *ContainerRunner) LogContainerRecord() error {
837 logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}})
838 if !logged && err == nil {
839 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
844 // LogNodeRecord logs the current host's InstanceType config entry, if
845 // running via arvados-dispatch-cloud.
846 func (runner *ContainerRunner) LogNodeRecord() error {
847 it := os.Getenv("InstanceType")
849 // Not dispatched by arvados-dispatch-cloud.
852 // Save InstanceType config fragment received from dispatcher
854 w, err := runner.LogCollection.OpenFile("node.json", os.O_CREATE|os.O_WRONLY, 0666)
859 _, err = io.WriteString(w, it)
866 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}) (logged bool, err error) {
867 writer, err := runner.LogCollection.OpenFile(label+".json", os.O_CREATE|os.O_WRONLY, 0666)
871 reader, err := runner.DispatcherArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
873 return false, fmt.Errorf("error getting %s record: %v", label, err)
877 dec := json.NewDecoder(reader)
879 var resp map[string]interface{}
880 if err = dec.Decode(&resp); err != nil {
881 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
883 items, ok := resp["items"].([]interface{})
885 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
886 } else if len(items) < 1 {
889 // Re-encode it using indentation to improve readability
890 enc := json.NewEncoder(writer)
891 enc.SetIndent("", " ")
892 if err = enc.Encode(items[0]); err != nil {
893 return false, fmt.Errorf("error logging %s record: %v", label, err)
897 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
902 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
903 stdoutPath := mntPath[len(runner.Container.OutputPath):]
904 index := strings.LastIndex(stdoutPath, "/")
906 subdirs := stdoutPath[:index]
908 st, err := os.Stat(runner.HostOutputDir)
910 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
912 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
913 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
915 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
919 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
921 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
924 return stdoutFile, nil
927 // CreateContainer creates the docker container.
928 func (runner *ContainerRunner) CreateContainer(imageID string, bindmounts map[string]bindmount) error {
930 if mnt, ok := runner.Container.Mounts["stdin"]; ok {
937 collID = mnt.PortableDataHash
939 path := runner.ArvMountPoint + "/by_id/" + collID + "/" + mnt.Path
940 f, err := os.Open(path)
945 runner.executorStdin = f
947 j, err := json.Marshal(mnt.Content)
949 return fmt.Errorf("error encoding stdin json data: %v", err)
951 stdin = bytes.NewReader(j)
952 runner.executorStdin = io.NopCloser(nil)
954 return fmt.Errorf("stdin mount has unsupported kind %q", mnt.Kind)
957 stdin = bytes.NewReader(nil)
958 runner.executorStdin = ioutil.NopCloser(nil)
961 var stdout, stderr io.Writer
962 if mnt, ok := runner.Container.Mounts["stdout"]; ok {
963 f, err := runner.getStdoutFile(mnt.Path)
968 runner.executorStdout = f
969 } else if w, err := runner.openLogFile("stdout"); err != nil {
972 stdout = newTimestamper(w)
973 runner.executorStdout = w
976 if mnt, ok := runner.Container.Mounts["stderr"]; ok {
977 f, err := runner.getStdoutFile(mnt.Path)
982 runner.executorStderr = f
983 } else if w, err := runner.openLogFile("stderr"); err != nil {
986 stderr = newTimestamper(w)
987 runner.executorStderr = w
990 env := runner.Container.Environment
991 enableNetwork := runner.enableNetwork == "always"
992 if runner.Container.RuntimeConstraints.API {
994 tok, err := runner.ContainerToken()
998 env = map[string]string{}
999 for k, v := range runner.Container.Environment {
1002 env["ARVADOS_API_TOKEN"] = tok
1003 env["ARVADOS_API_HOST"] = os.Getenv("ARVADOS_API_HOST")
1004 env["ARVADOS_API_HOST_INSECURE"] = os.Getenv("ARVADOS_API_HOST_INSECURE")
1005 env["ARVADOS_KEEP_SERVICES"] = os.Getenv("ARVADOS_KEEP_SERVICES")
1007 workdir := runner.Container.Cwd
1009 // both "" and "." mean default
1012 ram := runner.Container.RuntimeConstraints.RAM
1013 if !runner.enableMemoryLimit {
1017 if runner.Container.RuntimeConstraints.CUDA.DeviceCount > 0 {
1018 nvidiaModprobe(runner.CrunchLog)
1021 return runner.executor.Create(containerSpec{
1023 VCPUs: runner.Container.RuntimeConstraints.VCPUs,
1025 WorkingDir: workdir,
1027 BindMounts: bindmounts,
1028 Command: runner.Container.Command,
1029 EnableNetwork: enableNetwork,
1030 CUDADeviceCount: runner.Container.RuntimeConstraints.CUDA.DeviceCount,
1031 NetworkMode: runner.networkMode,
1032 CgroupParent: runner.setCgroupParent,
1039 // StartContainer starts the docker container created by CreateContainer.
1040 func (runner *ContainerRunner) StartContainer() error {
1041 runner.CrunchLog.Printf("Starting container")
1042 runner.cStateLock.Lock()
1043 defer runner.cStateLock.Unlock()
1044 if runner.cCancelled {
1047 err := runner.executor.Start()
1050 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
1051 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])
1053 return fmt.Errorf("could not start container: %v%s", err, advice)
1058 // WaitFinish waits for the container to terminate, capture the exit code, and
1059 // close the stdout/stderr logging.
1060 func (runner *ContainerRunner) WaitFinish() error {
1061 runner.CrunchLog.Print("Waiting for container to finish")
1062 var timeout <-chan time.Time
1063 if s := runner.Container.SchedulingParameters.MaxRunTime; s > 0 {
1064 timeout = time.After(time.Duration(s) * time.Second)
1066 ctx, cancel := context.WithCancel(context.Background())
1071 runner.CrunchLog.Printf("maximum run time exceeded. Stopping container.")
1073 case <-runner.ArvMountExit:
1074 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
1079 exitcode, err := runner.executor.Wait(ctx)
1081 runner.checkBrokenNode(err)
1084 runner.ExitCode = &exitcode
1087 if exitcode&0x80 != 0 {
1088 // Convert raw exit status (0x80 + signal number) to a
1089 // string to log after the code, like " (signal 101)"
1090 // or " (signal 9, killed)"
1091 sig := syscall.WaitStatus(exitcode).Signal()
1092 if name := unix.SignalName(sig); name != "" {
1093 extra = fmt.Sprintf(" (signal %d, %s)", sig, name)
1095 extra = fmt.Sprintf(" (signal %d)", sig)
1098 runner.CrunchLog.Printf("Container exited with status code %d%s", exitcode, extra)
1099 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1100 "select": []string{"uuid"},
1101 "container": arvadosclient.Dict{"exit_code": exitcode},
1104 runner.CrunchLog.Printf("ignoring error updating exit_code: %s", err)
1108 if err = runner.executorStdin.Close(); err != nil {
1109 err = fmt.Errorf("error closing container stdin: %s", err)
1110 runner.CrunchLog.Printf("%s", err)
1113 if err = runner.executorStdout.Close(); err != nil {
1114 err = fmt.Errorf("error closing container stdout: %s", err)
1115 runner.CrunchLog.Printf("%s", err)
1116 if returnErr == nil {
1120 if err = runner.executorStderr.Close(); err != nil {
1121 err = fmt.Errorf("error closing container stderr: %s", err)
1122 runner.CrunchLog.Printf("%s", err)
1123 if returnErr == nil {
1128 if runner.statReporter != nil {
1129 runner.statReporter.Stop()
1130 runner.statReporter.LogMaxima(runner.CrunchLog, map[string]int64{
1131 "rss": runner.Container.RuntimeConstraints.RAM,
1133 err = runner.statLogger.Close()
1135 runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
1141 func (runner *ContainerRunner) updateLogs() {
1142 ticker := time.NewTicker(crunchLogUpdatePeriod / 360)
1145 sigusr1 := make(chan os.Signal, 1)
1146 signal.Notify(sigusr1, syscall.SIGUSR1)
1147 defer signal.Stop(sigusr1)
1149 saveAtTime := time.Now().Add(crunchLogUpdatePeriod)
1150 saveAtSize := crunchLogUpdateSize
1156 saveAtTime = time.Now()
1158 runner.logMtx.Lock()
1159 done := runner.LogsPDH != nil
1160 runner.logMtx.Unlock()
1164 size := runner.LogCollection.Size()
1165 if size == savedSize || (time.Now().Before(saveAtTime) && size < saveAtSize) {
1168 saveAtTime = time.Now().Add(crunchLogUpdatePeriod)
1169 saveAtSize = runner.LogCollection.Size() + crunchLogUpdateSize
1170 saved, err := runner.saveLogCollection(false)
1172 runner.CrunchLog.Printf("error updating log collection: %s", err)
1176 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1177 "select": []string{"uuid"},
1178 "container": arvadosclient.Dict{
1179 "log": saved.PortableDataHash,
1183 runner.CrunchLog.Printf("error updating container log to %s: %s", saved.PortableDataHash, err)
1191 var spotInterruptionCheckInterval = 5 * time.Second
1192 var ec2MetadataBaseURL = "http://169.254.169.254"
1194 const ec2TokenTTL = time.Second * 21600
1196 func (runner *ContainerRunner) checkSpotInterruptionNotices() {
1197 type ec2metadata struct {
1198 Action string `json:"action"`
1199 Time time.Time `json:"time"`
1201 runner.CrunchLog.Printf("Checking for spot instance interruptions every %v using instance metadata at %s", spotInterruptionCheckInterval, ec2MetadataBaseURL)
1202 var metadata ec2metadata
1204 var tokenExp time.Time
1205 check := func() error {
1206 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute))
1208 if token == "" || tokenExp.Sub(time.Now()) < time.Minute {
1209 req, err := http.NewRequestWithContext(ctx, http.MethodPut, ec2MetadataBaseURL+"/latest/api/token", nil)
1213 req.Header.Set("X-aws-ec2-metadata-token-ttl-seconds", fmt.Sprintf("%d", int(ec2TokenTTL/time.Second)))
1214 resp, err := http.DefaultClient.Do(req)
1218 defer resp.Body.Close()
1219 if resp.StatusCode != http.StatusOK {
1220 return fmt.Errorf("%s", resp.Status)
1222 newtoken, err := ioutil.ReadAll(resp.Body)
1226 token = strings.TrimSpace(string(newtoken))
1227 tokenExp = time.Now().Add(ec2TokenTTL)
1229 req, err := http.NewRequestWithContext(ctx, http.MethodGet, ec2MetadataBaseURL+"/latest/meta-data/spot/instance-action", nil)
1233 req.Header.Set("X-aws-ec2-metadata-token", token)
1234 resp, err := http.DefaultClient.Do(req)
1238 defer resp.Body.Close()
1239 switch resp.StatusCode {
1242 case http.StatusNotFound:
1243 // "If Amazon EC2 is not preparing to stop or
1244 // terminate the instance, or if you
1245 // terminated the instance yourself,
1246 // instance-action is not present in the
1247 // instance metadata and you receive an HTTP
1248 // 404 error when you try to retrieve it."
1249 metadata = ec2metadata{}
1251 case http.StatusUnauthorized:
1253 return fmt.Errorf("%s", resp.Status)
1255 return fmt.Errorf("%s", resp.Status)
1257 nextmetadata := ec2metadata{}
1258 err = json.NewDecoder(resp.Body).Decode(&nextmetadata)
1262 metadata = nextmetadata
1266 var lastmetadata ec2metadata
1267 for range time.NewTicker(spotInterruptionCheckInterval).C {
1270 message := fmt.Sprintf("Unable to check spot instance interruptions: %s", err)
1271 if failures++; failures > 5 {
1272 runner.CrunchLog.Printf("%s -- now giving up after too many consecutive errors", message)
1275 runner.CrunchLog.Printf("%s -- will retry in %v", message, spotInterruptionCheckInterval)
1280 if metadata.Action != "" && metadata != lastmetadata {
1281 lastmetadata = metadata
1282 text := fmt.Sprintf("Cloud provider scheduled instance %s at %s", metadata.Action, metadata.Time.UTC().Format(time.RFC3339))
1283 runner.CrunchLog.Printf("%s", text)
1284 runner.updateRuntimeStatus(arvadosclient.Dict{
1285 "warning": "preemption notice",
1286 "warningDetail": text,
1287 "preemptionNotice": text,
1289 if proc, err := os.FindProcess(os.Getpid()); err == nil {
1290 // trigger updateLogs
1291 proc.Signal(syscall.SIGUSR1)
1297 func (runner *ContainerRunner) updateRuntimeStatus(status arvadosclient.Dict) {
1298 err := runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1299 "select": []string{"uuid"},
1300 "container": arvadosclient.Dict{
1301 "runtime_status": status,
1305 runner.CrunchLog.Printf("error updating container runtime_status: %s", err)
1309 // CaptureOutput saves data from the container's output directory if
1310 // needed, and updates the container output accordingly.
1311 func (runner *ContainerRunner) CaptureOutput(bindmounts map[string]bindmount) error {
1312 if runner.Container.RuntimeConstraints.API {
1313 // Output may have been set directly by the container, so
1314 // refresh the container record to check.
1315 err := runner.DispatcherArvClient.Get("containers", runner.Container.UUID,
1317 "select": []string{"output"},
1318 }, &runner.Container)
1322 if runner.Container.Output != "" {
1323 // Container output is already set.
1324 runner.OutputPDH = &runner.Container.Output
1329 txt, err := (&copier{
1330 client: runner.containerClient,
1331 keepClient: runner.ContainerKeepClient,
1332 hostOutputDir: runner.HostOutputDir,
1333 ctrOutputDir: runner.Container.OutputPath,
1334 globs: runner.Container.OutputGlob,
1335 bindmounts: bindmounts,
1336 mounts: runner.Container.Mounts,
1337 secretMounts: runner.SecretMounts,
1338 logger: runner.CrunchLog,
1343 if n := len(regexp.MustCompile(` [0-9a-f]+\+\S*\+R`).FindAllStringIndex(txt, -1)); n > 0 {
1344 runner.CrunchLog.Printf("Copying %d data blocks from remote input collections...", n)
1345 fs, err := (&arvados.Collection{ManifestText: txt}).FileSystem(runner.containerClient, runner.ContainerKeepClient)
1349 txt, err = fs.MarshalManifest(".")
1354 var resp arvados.Collection
1355 err = runner.ContainerArvClient.Create("collections", arvadosclient.Dict{
1356 "ensure_unique_name": true,
1357 "select": []string{"portable_data_hash"},
1358 "collection": arvadosclient.Dict{
1360 "name": "output for " + runner.Container.UUID,
1361 "manifest_text": txt,
1365 return fmt.Errorf("error creating output collection: %v", err)
1367 runner.OutputPDH = &resp.PortableDataHash
1371 func (runner *ContainerRunner) CleanupDirs() {
1372 if runner.ArvMount != nil {
1374 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1375 umount.Stdout = runner.CrunchLog
1376 umount.Stderr = runner.CrunchLog
1377 runner.CrunchLog.Printf("Running %v", umount.Args)
1378 umnterr := umount.Start()
1381 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1382 runner.ArvMount.Process.Kill()
1384 // If arv-mount --unmount gets stuck for any reason, we
1385 // don't want to wait for it forever. Do Wait() in a goroutine
1386 // so it doesn't block crunch-run.
1387 umountExit := make(chan error)
1389 mnterr := umount.Wait()
1391 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1393 umountExit <- mnterr
1396 for again := true; again; {
1402 case <-runner.ArvMountExit:
1404 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1405 runner.CrunchLog.Printf("Timed out waiting for unmount")
1407 umount.Process.Kill()
1409 runner.ArvMount.Process.Kill()
1413 runner.ArvMount = nil
1416 if runner.ArvMountPoint != "" {
1417 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1418 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1420 runner.ArvMountPoint = ""
1423 if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1424 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1428 // CommitLogs posts the collection containing the final container logs.
1429 func (runner *ContainerRunner) CommitLogs() error {
1431 // Hold cStateLock to prevent races on CrunchLog (e.g., stop()).
1432 runner.cStateLock.Lock()
1433 defer runner.cStateLock.Unlock()
1435 runner.CrunchLog.Print(runner.finalState)
1437 if runner.arvMountLog != nil {
1438 runner.arvMountLog.Close()
1441 // From now on just log to stderr, in case there are
1442 // any other further errors (such as failing to write
1443 // the log to Keep!) while shutting down
1444 runner.CrunchLog = newLogWriter(newTimestamper(newStringPrefixer(os.Stderr, runner.Container.UUID+" ")))
1447 if runner.keepstoreLogger != nil {
1448 // Flush any buffered logs from our local keepstore
1449 // process. Discard anything logged after this point
1450 // -- it won't end up in the log collection, so
1451 // there's no point writing it to the collectionfs.
1452 runner.keepstoreLogbuf.SetWriter(io.Discard)
1453 runner.keepstoreLogger.Close()
1454 runner.keepstoreLogger = nil
1457 if runner.LogsPDH != nil {
1458 // If we have already assigned something to LogsPDH,
1459 // we must be closing the re-opened log, which won't
1460 // end up getting attached to the container record and
1461 // therefore doesn't need to be saved as a collection
1462 // -- it exists only to send logs to other channels.
1466 saved, err := runner.saveLogCollection(true)
1468 return fmt.Errorf("error saving log collection: %s", err)
1470 runner.logMtx.Lock()
1471 defer runner.logMtx.Unlock()
1472 runner.LogsPDH = &saved.PortableDataHash
1476 // Create/update the log collection. Return value has UUID and
1477 // PortableDataHash fields populated, but others may be blank.
1478 func (runner *ContainerRunner) saveLogCollection(final bool) (response arvados.Collection, err error) {
1479 runner.logMtx.Lock()
1480 defer runner.logMtx.Unlock()
1481 if runner.LogsPDH != nil {
1482 // Already finalized.
1485 updates := arvadosclient.Dict{
1486 "name": "logs for " + runner.Container.UUID,
1488 mt, err1 := runner.LogCollection.MarshalManifest(".")
1490 // Only send updated manifest text if there was no
1492 updates["manifest_text"] = mt
1495 // Even if flushing the manifest had an error, we still want
1496 // to update the log record, if possible, to push the trash_at
1497 // and delete_at times into the future. Details on bug
1500 updates["is_trashed"] = true
1502 // We set trash_at so this collection gets
1503 // automatically cleaned up eventually. It used to be
1504 // 12 hours but we had a situation where the API
1505 // server was down over a weekend but the containers
1506 // kept running such that the log collection got
1507 // trashed, so now we make it 2 weeks. refs #20378
1508 exp := time.Now().Add(time.Duration(24*14) * time.Hour)
1509 updates["trash_at"] = exp
1510 updates["delete_at"] = exp
1512 reqBody := arvadosclient.Dict{
1513 "select": []string{"uuid", "portable_data_hash"},
1514 "collection": updates,
1517 if runner.logUUID == "" {
1518 reqBody["ensure_unique_name"] = true
1519 err2 = runner.DispatcherArvClient.Create("collections", reqBody, &response)
1521 err2 = runner.DispatcherArvClient.Update("collections", runner.logUUID, reqBody, &response)
1524 runner.logUUID = response.UUID
1527 if err1 != nil || err2 != nil {
1528 err = fmt.Errorf("error recording logs: %q, %q", err1, err2)
1533 // UpdateContainerRunning updates the container state to "Running"
1534 func (runner *ContainerRunner) UpdateContainerRunning(logId string) error {
1535 runner.cStateLock.Lock()
1536 defer runner.cStateLock.Unlock()
1537 if runner.cCancelled {
1540 updates := arvadosclient.Dict{
1541 "gateway_address": runner.gateway.Address,
1545 updates["log"] = logId
1547 return runner.DispatcherArvClient.Update(
1549 runner.Container.UUID,
1551 "select": []string{"uuid"},
1552 "container": updates,
1558 // ContainerToken returns the api_token the container (and any
1559 // arv-mount processes) are allowed to use.
1560 func (runner *ContainerRunner) ContainerToken() (string, error) {
1561 if runner.token != "" {
1562 return runner.token, nil
1565 var auth arvados.APIClientAuthorization
1566 err := runner.DispatcherArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1570 runner.token = fmt.Sprintf("v2/%s/%s/%s", auth.UUID, auth.APIToken, runner.Container.UUID)
1571 return runner.token, nil
1574 // UpdateContainerFinal updates the container record state on API
1575 // server to "Complete" or "Cancelled"
1576 func (runner *ContainerRunner) UpdateContainerFinal() error {
1577 update := arvadosclient.Dict{}
1578 update["state"] = runner.finalState
1579 if runner.LogsPDH != nil {
1580 update["log"] = *runner.LogsPDH
1582 if runner.ExitCode != nil {
1583 update["exit_code"] = *runner.ExitCode
1585 update["exit_code"] = nil
1587 if runner.finalState == "Complete" && runner.OutputPDH != nil {
1588 update["output"] = *runner.OutputPDH
1590 update["cost"] = runner.calculateCost(time.Now())
1591 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1592 "select": []string{"uuid"},
1593 "container": update,
1597 // IsCancelled returns the value of Cancelled, with goroutine safety.
1598 func (runner *ContainerRunner) IsCancelled() bool {
1599 runner.cStateLock.Lock()
1600 defer runner.cStateLock.Unlock()
1601 return runner.cCancelled
1604 func (runner *ContainerRunner) openLogFile(name string) (io.WriteCloser, error) {
1605 return runner.LogCollection.OpenFile(name+".txt", os.O_CREATE|os.O_WRONLY, 0666)
1608 // Run the full container lifecycle.
1609 func (runner *ContainerRunner) Run() (err error) {
1610 runner.CrunchLog.Printf("crunch-run %s started", cmd.Version.String())
1611 runner.CrunchLog.Printf("%s", currentUserAndGroups())
1612 v, _ := exec.Command("arv-mount", "--version").CombinedOutput()
1613 runner.CrunchLog.Printf("Using FUSE mount: %s", v)
1614 runner.CrunchLog.Printf("Using container runtime: %s", runner.executor.Runtime())
1615 runner.CrunchLog.Printf("Executing container: %s", runner.Container.UUID)
1616 runner.costStartTime = time.Now()
1618 hostname, hosterr := os.Hostname()
1620 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1622 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1625 sigusr2 := make(chan os.Signal, 1)
1626 signal.Notify(sigusr2, syscall.SIGUSR2)
1627 defer signal.Stop(sigusr2)
1629 go runner.handleSIGUSR2(sigusr2)
1631 runner.finalState = "Queued"
1634 runner.CleanupDirs()
1635 runner.CrunchLog.Printf("crunch-run finished")
1638 err = runner.fetchContainerRecord()
1642 if runner.Container.State != "Locked" {
1643 return fmt.Errorf("dispatch error detected: container %q has state %q", runner.Container.UUID, runner.Container.State)
1646 var bindmounts map[string]bindmount
1648 // checkErr prints e (unless it's nil) and sets err to
1649 // e (unless err is already non-nil). Thus, if err
1650 // hasn't already been assigned when Run() returns,
1651 // this cleanup func will cause Run() to return the
1652 // first non-nil error that is passed to checkErr().
1653 checkErr := func(errorIn string, e error) {
1657 runner.CrunchLog.Printf("error in %s: %v", errorIn, e)
1661 if runner.finalState == "Complete" {
1662 // There was an error in the finalization.
1663 runner.finalState = "Cancelled"
1667 // Log the error encountered in Run(), if any
1668 checkErr("Run", err)
1670 if runner.finalState == "Queued" {
1671 runner.UpdateContainerFinal()
1675 if runner.IsCancelled() {
1676 runner.finalState = "Cancelled"
1677 // but don't return yet -- we still want to
1678 // capture partial output and write logs
1681 if bindmounts != nil {
1682 checkErr("CaptureOutput", runner.CaptureOutput(bindmounts))
1684 checkErr("stopHoststat", runner.stopHoststat())
1685 checkErr("CommitLogs", runner.CommitLogs())
1686 runner.CleanupDirs()
1687 checkErr("UpdateContainerFinal", runner.UpdateContainerFinal())
1690 runner.setupSignals()
1691 err = runner.startHoststat()
1695 if runner.keepstore != nil {
1696 runner.hoststatReporter.ReportPID("keepstore", runner.keepstore.Process.Pid)
1699 // set up FUSE mount and binds
1700 bindmounts, err = runner.SetupMounts()
1702 runner.finalState = "Cancelled"
1703 err = fmt.Errorf("While setting up mounts: %v", err)
1707 // check for and/or load image
1708 imageID, err := runner.LoadImage()
1710 if !runner.checkBrokenNode(err) {
1711 // Failed to load image but not due to a "broken node"
1712 // condition, probably user error.
1713 runner.finalState = "Cancelled"
1715 err = fmt.Errorf("While loading container image: %v", err)
1719 err = runner.CreateContainer(imageID, bindmounts)
1723 err = runner.LogHostInfo()
1727 err = runner.LogNodeRecord()
1731 err = runner.LogContainerRecord()
1736 if runner.IsCancelled() {
1740 logCollection, err := runner.saveLogCollection(false)
1743 logId = logCollection.PortableDataHash
1745 runner.CrunchLog.Printf("Error committing initial log collection: %v", err)
1747 err = runner.UpdateContainerRunning(logId)
1751 runner.finalState = "Cancelled"
1753 err = runner.startCrunchstat()
1758 err = runner.StartContainer()
1760 runner.checkBrokenNode(err)
1764 err = runner.WaitFinish()
1765 if err == nil && !runner.IsCancelled() {
1766 runner.finalState = "Complete"
1771 // Fetch the current container record (uuid = runner.Container.UUID)
1772 // into runner.Container.
1773 func (runner *ContainerRunner) fetchContainerRecord() error {
1774 reader, err := runner.DispatcherArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1776 return fmt.Errorf("error fetching container record: %v", err)
1778 defer reader.Close()
1780 dec := json.NewDecoder(reader)
1782 err = dec.Decode(&runner.Container)
1784 return fmt.Errorf("error decoding container record: %v", err)
1788 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
1791 containerToken, err := runner.ContainerToken()
1793 return fmt.Errorf("error getting container token: %v", err)
1796 runner.ContainerArvClient, runner.ContainerKeepClient,
1797 runner.containerClient, err = runner.MkArvClient(containerToken)
1799 return fmt.Errorf("error creating container API client: %v", err)
1802 runner.ContainerKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1803 runner.DispatcherKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1805 err = runner.ContainerArvClient.Call("GET", "containers", runner.Container.UUID, "secret_mounts", nil, &sm)
1807 if apierr, ok := err.(arvadosclient.APIServerError); !ok || apierr.HttpStatusCode != 404 {
1808 return fmt.Errorf("error fetching secret_mounts: %v", err)
1810 // ok && apierr.HttpStatusCode == 404, which means
1811 // secret_mounts isn't supported by this API server.
1813 runner.SecretMounts = sm.SecretMounts
1818 // NewContainerRunner creates a new container runner.
1819 func NewContainerRunner(dispatcherClient *arvados.Client,
1820 dispatcherArvClient IArvadosClient,
1821 dispatcherKeepClient IKeepClient,
1822 containerUUID string) (*ContainerRunner, error) {
1824 cr := &ContainerRunner{
1825 dispatcherClient: dispatcherClient,
1826 DispatcherArvClient: dispatcherArvClient,
1827 DispatcherKeepClient: dispatcherKeepClient,
1829 cr.RunArvMount = cr.ArvMountCmd
1830 cr.MkTempDir = ioutil.TempDir
1831 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1832 cl, err := arvadosclient.MakeArvadosClient()
1834 return nil, nil, nil, err
1837 kc, err := keepclient.MakeKeepClient(cl)
1839 return nil, nil, nil, err
1841 c2 := arvados.NewClientFromEnv()
1842 c2.AuthToken = token
1843 return cl, kc, c2, nil
1846 cr.LogCollection, err = (&arvados.Collection{}).FileSystem(cr.dispatcherClient, cr.DispatcherKeepClient)
1850 cr.Container.UUID = containerUUID
1851 f, err := cr.openLogFile("crunch-run")
1855 cr.CrunchLog = newLogWriter(newTimestamper(io.MultiWriter(f, newStringPrefixer(os.Stderr, cr.Container.UUID+" "))))
1862 func (command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
1863 log := log.New(stderr, "", 0)
1864 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
1865 statInterval := flags.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1866 flags.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree (obsolete, ignored)")
1867 flags.String("cgroup-parent", "docker", "name of container's parent cgroup (obsolete, ignored)")
1868 cgroupParentSubsystem := flags.String("cgroup-parent-subsystem", "", "use current cgroup for given `subsystem` as parent cgroup for container (subsystem argument is only relevant for cgroups v1; in cgroups v2 / unified mode, any non-empty value means use current cgroup); if empty, use the docker daemon's default cgroup parent. See https://doc.arvados.org/install/crunch2-slurm/install-dispatch.html#CrunchRunCommand-cgroups")
1869 caCertsPath := flags.String("ca-certs", "", "Path to TLS root certificates")
1870 detach := flags.Bool("detach", false, "Detach from parent process and run in the background")
1871 stdinConfig := flags.Bool("stdin-config", false, "Load config and environment variables from JSON message on stdin")
1872 configFile := flags.String("config", arvados.DefaultConfigFile, "filename of cluster config file to try loading if -stdin-config=false (default is $ARVADOS_CONFIG)")
1873 sleep := flags.Duration("sleep", 0, "Delay before starting (testing use only)")
1874 kill := flags.Int("kill", -1, "Send signal to an existing crunch-run process for given UUID")
1875 list := flags.Bool("list", false, "List UUIDs of existing crunch-run processes (and notify them to use price data passed on stdin)")
1876 enableMemoryLimit := flags.Bool("enable-memory-limit", true, "tell container runtime to limit container's memory usage")
1877 enableNetwork := flags.String("container-enable-networking", "default", "enable networking \"always\" (for all containers) or \"default\" (for containers that request it)")
1878 networkMode := flags.String("container-network-mode", "default", `Docker network mode for container (use any argument valid for docker --net)`)
1879 memprofile := flags.String("memprofile", "", "write memory profile to `file` after running container")
1880 runtimeEngine := flags.String("runtime-engine", "docker", "container runtime: docker or singularity")
1881 brokenNodeHook := flags.String("broken-node-hook", "", "script to run if node is detected to be broken (for example, Docker daemon is not running)")
1882 flags.Duration("check-containerd", 0, "Ignored. Exists for compatibility with older versions.")
1883 version := flags.Bool("version", false, "Write version information to stdout and exit 0.")
1885 ignoreDetachFlag := false
1886 if len(args) > 0 && args[0] == "-no-detach" {
1887 // This process was invoked by a parent process, which
1888 // has passed along its own arguments, including
1889 // -detach, after the leading -no-detach flag. Strip
1890 // the leading -no-detach flag (it's not recognized by
1891 // flags.Parse()) and ignore the -detach flag that
1894 ignoreDetachFlag = true
1897 if ok, code := cmd.ParseFlags(flags, prog, args, "container-uuid", stderr); !ok {
1899 } else if *version {
1900 fmt.Fprintln(stdout, prog, cmd.Version.String())
1902 } else if !*list && flags.NArg() != 1 {
1903 fmt.Fprintf(stderr, "missing required argument: container-uuid (try -help)\n")
1907 containerUUID := flags.Arg(0)
1910 case *detach && !ignoreDetachFlag:
1911 return Detach(containerUUID, prog, args, stdin, stdout, stderr)
1913 return KillProcess(containerUUID, syscall.Signal(*kill), stdout, stderr)
1915 return ListProcesses(stdin, stdout, stderr)
1918 if len(containerUUID) != 27 {
1919 log.Printf("usage: %s [options] UUID", prog)
1923 var keepstoreLogbuf bufThenWrite
1926 err := json.NewDecoder(stdin).Decode(&conf)
1928 log.Printf("decode stdin: %s", err)
1931 for k, v := range conf.Env {
1932 err = os.Setenv(k, v)
1934 log.Printf("setenv(%q): %s", k, err)
1938 if conf.Cluster != nil {
1939 // ClusterID is missing from the JSON
1940 // representation, but we need it to generate
1941 // a valid config file for keepstore, so we
1942 // fill it using the container UUID prefix.
1943 conf.Cluster.ClusterID = containerUUID[:5]
1946 conf = hpcConfData(containerUUID, *configFile, io.MultiWriter(&keepstoreLogbuf, stderr))
1949 log.Printf("crunch-run %s started", cmd.Version.String())
1952 if *caCertsPath != "" {
1953 os.Setenv("SSL_CERT_FILE", *caCertsPath)
1956 keepstore, err := startLocalKeepstore(conf, io.MultiWriter(&keepstoreLogbuf, stderr))
1961 if keepstore != nil {
1962 defer keepstore.Process.Kill()
1965 api, err := arvadosclient.MakeArvadosClient()
1967 log.Printf("%s: %v", containerUUID, err)
1970 // arvadosclient now interprets Retries=10 to mean
1971 // Timeout=10m, retrying with exponential backoff + jitter.
1974 kc, err := keepclient.MakeKeepClient(api)
1976 log.Printf("%s: %v", containerUUID, err)
1981 cr, err := NewContainerRunner(arvados.NewClientFromEnv(), api, kc, containerUUID)
1987 cr.keepstore = keepstore
1988 if keepstore == nil {
1989 // Log explanation (if any) for why we're not running
1990 // a local keepstore.
1991 var buf bytes.Buffer
1992 keepstoreLogbuf.SetWriter(&buf)
1994 cr.CrunchLog.Printf("%s", strings.TrimSpace(buf.String()))
1996 } else if logWhat := conf.Cluster.Containers.LocalKeepLogsToContainerLog; logWhat == "none" {
1997 cr.CrunchLog.Printf("using local keepstore process (pid %d) at %s", keepstore.Process.Pid, os.Getenv("ARVADOS_KEEP_SERVICES"))
1998 keepstoreLogbuf.SetWriter(io.Discard)
2000 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"))
2001 cr.keepstoreLogger, err = cr.openLogFile("keepstore")
2007 var writer io.WriteCloser = cr.keepstoreLogger
2008 if logWhat == "errors" {
2009 writer = &filterKeepstoreErrorsOnly{WriteCloser: writer}
2010 } else if logWhat != "all" {
2011 // should have been caught earlier by
2012 // dispatcher's config loader
2013 log.Printf("invalid value for Containers.LocalKeepLogsToContainerLog: %q", logWhat)
2016 err = keepstoreLogbuf.SetWriter(writer)
2021 cr.keepstoreLogbuf = &keepstoreLogbuf
2024 switch *runtimeEngine {
2026 cr.executor, err = newDockerExecutor(containerUUID, cr.CrunchLog.Printf, cr.containerWatchdogInterval)
2028 cr.executor, err = newSingularityExecutor(cr.CrunchLog.Printf)
2030 cr.CrunchLog.Printf("%s: unsupported RuntimeEngine %q", containerUUID, *runtimeEngine)
2034 cr.CrunchLog.Printf("%s: %v", containerUUID, err)
2035 cr.checkBrokenNode(err)
2038 defer cr.executor.Close()
2040 cr.brokenNodeHook = *brokenNodeHook
2042 gwAuthSecret := os.Getenv("GatewayAuthSecret")
2043 os.Unsetenv("GatewayAuthSecret")
2044 if gwAuthSecret == "" {
2045 // not safe to run a gateway service without an auth
2047 cr.CrunchLog.Printf("Not starting a gateway server (GatewayAuthSecret was not provided by dispatcher)")
2049 gwListen := os.Getenv("GatewayAddress")
2050 cr.gateway = Gateway{
2052 AuthSecret: gwAuthSecret,
2053 ContainerUUID: containerUUID,
2054 Target: cr.executor,
2056 LogCollection: cr.LogCollection,
2059 // Direct connection won't work, so we use the
2060 // gateway_address field to indicate the
2061 // internalURL of the controller process that
2062 // has the current tunnel connection.
2063 cr.gateway.ArvadosClient = cr.dispatcherClient
2064 cr.gateway.UpdateTunnelURL = func(url string) {
2065 cr.gateway.Address = "tunnel " + url
2066 cr.DispatcherArvClient.Update("containers", containerUUID,
2068 "select": []string{"uuid"},
2069 "container": arvadosclient.Dict{"gateway_address": cr.gateway.Address},
2073 err = cr.gateway.Start()
2075 log.Printf("error starting gateway server: %s", err)
2080 parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerUUID+".")
2082 log.Printf("%s: %v", containerUUID, tmperr)
2086 cr.parentTemp = parentTemp
2087 cr.statInterval = *statInterval
2088 cr.enableMemoryLimit = *enableMemoryLimit
2089 cr.enableNetwork = *enableNetwork
2090 cr.networkMode = *networkMode
2091 if *cgroupParentSubsystem != "" {
2092 p, err := findCgroup(os.DirFS("/"), *cgroupParentSubsystem)
2094 log.Printf("fatal: cgroup parent subsystem: %s", err)
2097 cr.setCgroupParent = p
2100 if conf.EC2SpotCheck {
2101 go cr.checkSpotInterruptionNotices()
2106 if *memprofile != "" {
2107 f, err := os.Create(*memprofile)
2109 log.Printf("could not create memory profile: %s", err)
2111 runtime.GC() // get up-to-date statistics
2112 if err := pprof.WriteHeapProfile(f); err != nil {
2113 log.Printf("could not write memory profile: %s", err)
2115 closeerr := f.Close()
2116 if closeerr != nil {
2117 log.Printf("closing memprofile file: %s", err)
2122 log.Printf("%s: %v", containerUUID, runerr)
2128 // Try to load ConfigData in hpc (slurm/lsf) environment. This means
2129 // loading the cluster config from the specified file and (if that
2130 // works) getting the runtime_constraints container field from
2131 // controller to determine # VCPUs so we can calculate KeepBuffers.
2132 func hpcConfData(uuid string, configFile string, stderr io.Writer) ConfigData {
2134 conf.Cluster = loadClusterConfigFile(configFile, stderr)
2135 if conf.Cluster == nil {
2136 // skip loading the container record -- we won't be
2137 // able to start local keepstore anyway.
2140 arv, err := arvadosclient.MakeArvadosClient()
2142 fmt.Fprintf(stderr, "error setting up arvadosclient: %s\n", err)
2145 // arvadosclient now interprets Retries=10 to mean
2146 // Timeout=10m, retrying with exponential backoff + jitter.
2148 var ctr arvados.Container
2149 err = arv.Call("GET", "containers", uuid, "", arvadosclient.Dict{"select": []string{"runtime_constraints"}}, &ctr)
2151 fmt.Fprintf(stderr, "error getting container record: %s\n", err)
2154 if ctr.RuntimeConstraints.VCPUs > 0 {
2155 conf.KeepBuffers = ctr.RuntimeConstraints.VCPUs * conf.Cluster.Containers.LocalKeepBlobBuffersPerVCPU
2160 // Load cluster config file from given path. If an error occurs, log
2161 // the error to stderr and return nil.
2162 func loadClusterConfigFile(path string, stderr io.Writer) *arvados.Cluster {
2163 ldr := config.NewLoader(&bytes.Buffer{}, ctxlog.New(stderr, "plain", "info"))
2165 cfg, err := ldr.Load()
2167 fmt.Fprintf(stderr, "could not load config file %s: %s\n", path, err)
2170 cluster, err := cfg.GetCluster("")
2172 fmt.Fprintf(stderr, "could not use config file %s: %s\n", path, err)
2175 fmt.Fprintf(stderr, "loaded config file %s\n", path)
2179 func startLocalKeepstore(configData ConfigData, logbuf io.Writer) (*exec.Cmd, error) {
2180 if configData.KeepBuffers < 1 {
2181 fmt.Fprintf(logbuf, "not starting a local keepstore process because KeepBuffers=%v in config\n", configData.KeepBuffers)
2184 if configData.Cluster == nil {
2185 fmt.Fprint(logbuf, "not starting a local keepstore process because cluster config file was not loaded\n")
2188 for uuid, vol := range configData.Cluster.Volumes {
2189 if len(vol.AccessViaHosts) > 0 {
2190 fmt.Fprintf(logbuf, "not starting a local keepstore process because a volume (%s) uses AccessViaHosts\n", uuid)
2193 if !vol.ReadOnly && vol.Replication < configData.Cluster.Collections.DefaultReplication {
2194 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)
2199 // Rather than have an alternate way to tell keepstore how
2200 // many buffers to use, etc., when starting it this way, we
2201 // just modify the cluster configuration that we feed it on
2203 ccfg := *configData.Cluster
2204 ccfg.API.MaxKeepBlobBuffers = configData.KeepBuffers
2205 ccfg.Collections.BlobTrash = false
2206 ccfg.Collections.BlobTrashConcurrency = 0
2207 ccfg.Collections.BlobDeleteConcurrency = 0
2209 localaddr := localKeepstoreAddr()
2210 ln, err := net.Listen("tcp", net.JoinHostPort(localaddr, "0"))
2214 _, port, err := net.SplitHostPort(ln.Addr().String())
2220 url := "http://" + net.JoinHostPort(localaddr, port)
2222 fmt.Fprintf(logbuf, "starting keepstore on %s\n", url)
2224 var confJSON bytes.Buffer
2225 err = json.NewEncoder(&confJSON).Encode(arvados.Config{
2226 Clusters: map[string]arvados.Cluster{
2227 ccfg.ClusterID: ccfg,
2233 cmd := exec.Command("/proc/self/exe", "keepstore", "-config=-")
2234 if target, err := os.Readlink(cmd.Path); err == nil && strings.HasSuffix(target, ".test") {
2235 // If we're a 'go test' process, running
2236 // /proc/self/exe would start the test suite in a
2237 // child process, which is not what we want.
2238 cmd.Path, _ = exec.LookPath("go")
2239 cmd.Args = append([]string{"go", "run", "../../cmd/arvados-server"}, cmd.Args[1:]...)
2240 cmd.Env = os.Environ()
2242 cmd.Stdin = &confJSON
2245 cmd.Env = append(cmd.Env,
2247 "ARVADOS_SERVICE_INTERNAL_URL="+url)
2250 return nil, fmt.Errorf("error starting keepstore process: %w", err)
2257 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*10))
2259 poll := time.NewTicker(time.Second / 10)
2261 client := http.Client{}
2263 testReq, err := http.NewRequestWithContext(ctx, "GET", url+"/_health/ping", nil)
2264 testReq.Header.Set("Authorization", "Bearer "+configData.Cluster.ManagementToken)
2268 resp, err := client.Do(testReq)
2271 if resp.StatusCode == http.StatusOK {
2276 return nil, fmt.Errorf("keepstore child process exited")
2278 if ctx.Err() != nil {
2279 return nil, fmt.Errorf("timed out waiting for new keepstore process to report healthy")
2282 os.Setenv("ARVADOS_KEEP_SERVICES", url)
2286 // return current uid, gid, groups in a format suitable for logging:
2287 // "crunch-run process has uid=1234(arvados) gid=1234(arvados)
2288 // groups=1234(arvados),114(fuse)"
2289 func currentUserAndGroups() string {
2290 u, err := user.Current()
2292 return fmt.Sprintf("error getting current user ID: %s", err)
2294 s := fmt.Sprintf("crunch-run process has uid=%s(%s) gid=%s", u.Uid, u.Username, u.Gid)
2295 if g, err := user.LookupGroupId(u.Gid); err == nil {
2296 s += fmt.Sprintf("(%s)", g.Name)
2299 if gids, err := u.GroupIds(); err == nil {
2300 for i, gid := range gids {
2305 if g, err := user.LookupGroupId(gid); err == nil {
2306 s += fmt.Sprintf("(%s)", g.Name)
2313 // Return a suitable local interface address for a local keepstore
2314 // service. Currently this is the numerically lowest non-loopback ipv4
2315 // address assigned to a local interface that is not in any of the
2316 // link-local/vpn/loopback ranges 169.254/16, 100.64/10, or 127/8.
2317 func localKeepstoreAddr() string {
2319 // Ignore error (proceed with zero IPs)
2320 addrs, _ := processIPs(os.Getpid())
2321 for addr := range addrs {
2322 ip := net.ParseIP(addr)
2327 if ip.Mask(net.CIDRMask(8, 32)).Equal(net.IPv4(127, 0, 0, 0)) ||
2328 ip.Mask(net.CIDRMask(10, 32)).Equal(net.IPv4(100, 64, 0, 0)) ||
2329 ip.Mask(net.CIDRMask(16, 32)).Equal(net.IPv4(169, 254, 0, 0)) {
2333 ips = append(ips, ip)
2338 sort.Slice(ips, func(ii, jj int) bool {
2339 i, j := ips[ii], ips[jj]
2340 if len(i) != len(j) {
2341 return len(i) < len(j)
2350 return ips[0].String()
2353 func (cr *ContainerRunner) loadPrices() {
2354 buf, err := os.ReadFile(filepath.Join(lockdir, pricesfile))
2356 if !os.IsNotExist(err) {
2357 cr.CrunchLog.Printf("loadPrices: read: %s", err)
2361 var prices []cloud.InstancePrice
2362 err = json.Unmarshal(buf, &prices)
2364 cr.CrunchLog.Printf("loadPrices: decode: %s", err)
2367 cr.pricesLock.Lock()
2368 defer cr.pricesLock.Unlock()
2369 var lastKnown time.Time
2370 if len(cr.prices) > 0 {
2371 lastKnown = cr.prices[0].StartTime
2373 cr.prices = cloud.NormalizePriceHistory(append(prices, cr.prices...))
2374 for i := len(cr.prices) - 1; i >= 0; i-- {
2375 price := cr.prices[i]
2376 if price.StartTime.After(lastKnown) {
2377 cr.CrunchLog.Printf("Instance price changed to %#.3g at %s", price.Price, price.StartTime.UTC())
2382 func (cr *ContainerRunner) calculateCost(now time.Time) float64 {
2383 cr.pricesLock.Lock()
2384 defer cr.pricesLock.Unlock()
2386 // First, make a "prices" slice with the real data as far back
2387 // as it goes, and (if needed) a "since the beginning of time"
2388 // placeholder containing a reasonable guess about what the
2389 // price was between cr.costStartTime and the earliest real
2392 if len(prices) == 0 {
2393 // use price info in InstanceType record initially
2394 // provided by cloud dispatcher
2396 var it arvados.InstanceType
2397 if j := os.Getenv("InstanceType"); j != "" && json.Unmarshal([]byte(j), &it) == nil && it.Price > 0 {
2400 prices = []cloud.InstancePrice{{Price: p}}
2401 } else if prices[len(prices)-1].StartTime.After(cr.costStartTime) {
2402 // guess earlier pricing was the same as the earliest
2403 // price we know about
2404 filler := prices[len(prices)-1]
2405 filler.StartTime = time.Time{}
2406 prices = append(prices, filler)
2409 // Now that our history of price changes goes back at least as
2410 // far as cr.costStartTime, add up the costs for each
2414 for _, ip := range prices {
2415 spanStart := ip.StartTime
2416 if spanStart.After(now) {
2417 // pricing information from the future -- not
2418 // expected from AWS, but possible in
2419 // principle, and exercised by tests.
2423 if spanStart.Before(cr.costStartTime) {
2424 spanStart = cr.costStartTime
2427 cost += ip.Price * spanEnd.Sub(spanStart).Seconds() / 3600
2437 func (runner *ContainerRunner) handleSIGUSR2(sigchan chan os.Signal) {
2440 update := arvadosclient.Dict{
2441 "select": []string{"uuid"},
2442 "container": arvadosclient.Dict{
2443 "cost": runner.calculateCost(time.Now()),
2446 runner.DispatcherArvClient.Update("containers", runner.Container.UUID, update, nil)