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 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 metadata = ec2metadata{}
1240 switch resp.StatusCode {
1243 case http.StatusNotFound:
1244 // "If Amazon EC2 is not preparing to stop or
1245 // terminate the instance, or if you
1246 // terminated the instance yourself,
1247 // instance-action is not present in the
1248 // instance metadata and you receive an HTTP
1249 // 404 error when you try to retrieve it."
1251 case http.StatusUnauthorized:
1253 return fmt.Errorf("%s", resp.Status)
1255 return fmt.Errorf("%s", resp.Status)
1257 err = json.NewDecoder(resp.Body).Decode(&metadata)
1264 var lastmetadata ec2metadata
1265 for range time.NewTicker(spotInterruptionCheckInterval).C {
1268 runner.CrunchLog.Printf("Error checking spot interruptions: %s", err)
1271 runner.CrunchLog.Printf("Giving up on checking spot interruptions after too many consecutive failures")
1277 if metadata != lastmetadata {
1278 lastmetadata = metadata
1279 text := fmt.Sprintf("Cloud provider scheduled instance %s at %s", metadata.Action, metadata.Time.UTC().Format(time.RFC3339))
1280 runner.CrunchLog.Printf("%s", text)
1281 runner.updateRuntimeStatus(arvadosclient.Dict{
1282 "warning": "preemption notice",
1283 "warningDetail": text,
1284 "preemptionNotice": text,
1286 if proc, err := os.FindProcess(os.Getpid()); err == nil {
1287 // trigger updateLogs
1288 proc.Signal(syscall.SIGUSR1)
1294 func (runner *ContainerRunner) updateRuntimeStatus(status arvadosclient.Dict) {
1295 err := runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1296 "select": []string{"uuid"},
1297 "container": arvadosclient.Dict{
1298 "runtime_status": status,
1302 runner.CrunchLog.Printf("error updating container runtime_status: %s", err)
1306 // CaptureOutput saves data from the container's output directory if
1307 // needed, and updates the container output accordingly.
1308 func (runner *ContainerRunner) CaptureOutput(bindmounts map[string]bindmount) error {
1309 if runner.Container.RuntimeConstraints.API {
1310 // Output may have been set directly by the container, so
1311 // refresh the container record to check.
1312 err := runner.DispatcherArvClient.Get("containers", runner.Container.UUID,
1314 "select": []string{"output"},
1315 }, &runner.Container)
1319 if runner.Container.Output != "" {
1320 // Container output is already set.
1321 runner.OutputPDH = &runner.Container.Output
1326 txt, err := (&copier{
1327 client: runner.containerClient,
1328 keepClient: runner.ContainerKeepClient,
1329 hostOutputDir: runner.HostOutputDir,
1330 ctrOutputDir: runner.Container.OutputPath,
1331 globs: runner.Container.OutputGlob,
1332 bindmounts: bindmounts,
1333 mounts: runner.Container.Mounts,
1334 secretMounts: runner.SecretMounts,
1335 logger: runner.CrunchLog,
1340 if n := len(regexp.MustCompile(` [0-9a-f]+\+\S*\+R`).FindAllStringIndex(txt, -1)); n > 0 {
1341 runner.CrunchLog.Printf("Copying %d data blocks from remote input collections...", n)
1342 fs, err := (&arvados.Collection{ManifestText: txt}).FileSystem(runner.containerClient, runner.ContainerKeepClient)
1346 txt, err = fs.MarshalManifest(".")
1351 var resp arvados.Collection
1352 err = runner.ContainerArvClient.Create("collections", arvadosclient.Dict{
1353 "ensure_unique_name": true,
1354 "select": []string{"portable_data_hash"},
1355 "collection": arvadosclient.Dict{
1357 "name": "output for " + runner.Container.UUID,
1358 "manifest_text": txt,
1362 return fmt.Errorf("error creating output collection: %v", err)
1364 runner.OutputPDH = &resp.PortableDataHash
1368 func (runner *ContainerRunner) CleanupDirs() {
1369 if runner.ArvMount != nil {
1371 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1372 umount.Stdout = runner.CrunchLog
1373 umount.Stderr = runner.CrunchLog
1374 runner.CrunchLog.Printf("Running %v", umount.Args)
1375 umnterr := umount.Start()
1378 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1379 runner.ArvMount.Process.Kill()
1381 // If arv-mount --unmount gets stuck for any reason, we
1382 // don't want to wait for it forever. Do Wait() in a goroutine
1383 // so it doesn't block crunch-run.
1384 umountExit := make(chan error)
1386 mnterr := umount.Wait()
1388 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1390 umountExit <- mnterr
1393 for again := true; again; {
1399 case <-runner.ArvMountExit:
1401 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1402 runner.CrunchLog.Printf("Timed out waiting for unmount")
1404 umount.Process.Kill()
1406 runner.ArvMount.Process.Kill()
1410 runner.ArvMount = nil
1413 if runner.ArvMountPoint != "" {
1414 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1415 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1417 runner.ArvMountPoint = ""
1420 if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1421 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1425 // CommitLogs posts the collection containing the final container logs.
1426 func (runner *ContainerRunner) CommitLogs() error {
1428 // Hold cStateLock to prevent races on CrunchLog (e.g., stop()).
1429 runner.cStateLock.Lock()
1430 defer runner.cStateLock.Unlock()
1432 runner.CrunchLog.Print(runner.finalState)
1434 if runner.arvMountLog != nil {
1435 runner.arvMountLog.Close()
1438 // From now on just log to stderr, in case there are
1439 // any other further errors (such as failing to write
1440 // the log to Keep!) while shutting down
1441 runner.CrunchLog = newLogWriter(newTimestamper(newStringPrefixer(os.Stderr, runner.Container.UUID+" ")))
1444 if runner.keepstoreLogger != nil {
1445 // Flush any buffered logs from our local keepstore
1446 // process. Discard anything logged after this point
1447 // -- it won't end up in the log collection, so
1448 // there's no point writing it to the collectionfs.
1449 runner.keepstoreLogbuf.SetWriter(io.Discard)
1450 runner.keepstoreLogger.Close()
1451 runner.keepstoreLogger = nil
1454 if runner.LogsPDH != nil {
1455 // If we have already assigned something to LogsPDH,
1456 // we must be closing the re-opened log, which won't
1457 // end up getting attached to the container record and
1458 // therefore doesn't need to be saved as a collection
1459 // -- it exists only to send logs to other channels.
1463 saved, err := runner.saveLogCollection(true)
1465 return fmt.Errorf("error saving log collection: %s", err)
1467 runner.logMtx.Lock()
1468 defer runner.logMtx.Unlock()
1469 runner.LogsPDH = &saved.PortableDataHash
1473 // Create/update the log collection. Return value has UUID and
1474 // PortableDataHash fields populated, but others may be blank.
1475 func (runner *ContainerRunner) saveLogCollection(final bool) (response arvados.Collection, err error) {
1476 runner.logMtx.Lock()
1477 defer runner.logMtx.Unlock()
1478 if runner.LogsPDH != nil {
1479 // Already finalized.
1482 updates := arvadosclient.Dict{
1483 "name": "logs for " + runner.Container.UUID,
1485 mt, err1 := runner.LogCollection.MarshalManifest(".")
1487 // Only send updated manifest text if there was no
1489 updates["manifest_text"] = mt
1492 // Even if flushing the manifest had an error, we still want
1493 // to update the log record, if possible, to push the trash_at
1494 // and delete_at times into the future. Details on bug
1497 updates["is_trashed"] = true
1499 // We set trash_at so this collection gets
1500 // automatically cleaned up eventually. It used to be
1501 // 12 hours but we had a situation where the API
1502 // server was down over a weekend but the containers
1503 // kept running such that the log collection got
1504 // trashed, so now we make it 2 weeks. refs #20378
1505 exp := time.Now().Add(time.Duration(24*14) * time.Hour)
1506 updates["trash_at"] = exp
1507 updates["delete_at"] = exp
1509 reqBody := arvadosclient.Dict{
1510 "select": []string{"uuid", "portable_data_hash"},
1511 "collection": updates,
1514 if runner.logUUID == "" {
1515 reqBody["ensure_unique_name"] = true
1516 err2 = runner.DispatcherArvClient.Create("collections", reqBody, &response)
1518 err2 = runner.DispatcherArvClient.Update("collections", runner.logUUID, reqBody, &response)
1521 runner.logUUID = response.UUID
1524 if err1 != nil || err2 != nil {
1525 err = fmt.Errorf("error recording logs: %q, %q", err1, err2)
1530 // UpdateContainerRunning updates the container state to "Running"
1531 func (runner *ContainerRunner) UpdateContainerRunning(logId string) error {
1532 runner.cStateLock.Lock()
1533 defer runner.cStateLock.Unlock()
1534 if runner.cCancelled {
1537 updates := arvadosclient.Dict{
1538 "gateway_address": runner.gateway.Address,
1542 updates["log"] = logId
1544 return runner.DispatcherArvClient.Update(
1546 runner.Container.UUID,
1548 "select": []string{"uuid"},
1549 "container": updates,
1555 // ContainerToken returns the api_token the container (and any
1556 // arv-mount processes) are allowed to use.
1557 func (runner *ContainerRunner) ContainerToken() (string, error) {
1558 if runner.token != "" {
1559 return runner.token, nil
1562 var auth arvados.APIClientAuthorization
1563 err := runner.DispatcherArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1567 runner.token = fmt.Sprintf("v2/%s/%s/%s", auth.UUID, auth.APIToken, runner.Container.UUID)
1568 return runner.token, nil
1571 // UpdateContainerFinal updates the container record state on API
1572 // server to "Complete" or "Cancelled"
1573 func (runner *ContainerRunner) UpdateContainerFinal() error {
1574 update := arvadosclient.Dict{}
1575 update["state"] = runner.finalState
1576 if runner.LogsPDH != nil {
1577 update["log"] = *runner.LogsPDH
1579 if runner.ExitCode != nil {
1580 update["exit_code"] = *runner.ExitCode
1582 update["exit_code"] = nil
1584 if runner.finalState == "Complete" && runner.OutputPDH != nil {
1585 update["output"] = *runner.OutputPDH
1587 update["cost"] = runner.calculateCost(time.Now())
1588 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1589 "select": []string{"uuid"},
1590 "container": update,
1594 // IsCancelled returns the value of Cancelled, with goroutine safety.
1595 func (runner *ContainerRunner) IsCancelled() bool {
1596 runner.cStateLock.Lock()
1597 defer runner.cStateLock.Unlock()
1598 return runner.cCancelled
1601 func (runner *ContainerRunner) openLogFile(name string) (io.WriteCloser, error) {
1602 return runner.LogCollection.OpenFile(name+".txt", os.O_CREATE|os.O_WRONLY, 0666)
1605 // Run the full container lifecycle.
1606 func (runner *ContainerRunner) Run() (err error) {
1607 runner.CrunchLog.Printf("crunch-run %s started", cmd.Version.String())
1608 runner.CrunchLog.Printf("%s", currentUserAndGroups())
1609 v, _ := exec.Command("arv-mount", "--version").CombinedOutput()
1610 runner.CrunchLog.Printf("Using FUSE mount: %s", v)
1611 runner.CrunchLog.Printf("Using container runtime: %s", runner.executor.Runtime())
1612 runner.CrunchLog.Printf("Executing container: %s", runner.Container.UUID)
1613 runner.costStartTime = time.Now()
1615 hostname, hosterr := os.Hostname()
1617 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1619 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1622 sigusr2 := make(chan os.Signal, 1)
1623 signal.Notify(sigusr2, syscall.SIGUSR2)
1624 defer signal.Stop(sigusr2)
1626 go runner.handleSIGUSR2(sigusr2)
1628 runner.finalState = "Queued"
1631 runner.CleanupDirs()
1632 runner.CrunchLog.Printf("crunch-run finished")
1635 err = runner.fetchContainerRecord()
1639 if runner.Container.State != "Locked" {
1640 return fmt.Errorf("dispatch error detected: container %q has state %q", runner.Container.UUID, runner.Container.State)
1643 var bindmounts map[string]bindmount
1645 // checkErr prints e (unless it's nil) and sets err to
1646 // e (unless err is already non-nil). Thus, if err
1647 // hasn't already been assigned when Run() returns,
1648 // this cleanup func will cause Run() to return the
1649 // first non-nil error that is passed to checkErr().
1650 checkErr := func(errorIn string, e error) {
1654 runner.CrunchLog.Printf("error in %s: %v", errorIn, e)
1658 if runner.finalState == "Complete" {
1659 // There was an error in the finalization.
1660 runner.finalState = "Cancelled"
1664 // Log the error encountered in Run(), if any
1665 checkErr("Run", err)
1667 if runner.finalState == "Queued" {
1668 runner.UpdateContainerFinal()
1672 if runner.IsCancelled() {
1673 runner.finalState = "Cancelled"
1674 // but don't return yet -- we still want to
1675 // capture partial output and write logs
1678 if bindmounts != nil {
1679 checkErr("CaptureOutput", runner.CaptureOutput(bindmounts))
1681 checkErr("stopHoststat", runner.stopHoststat())
1682 checkErr("CommitLogs", runner.CommitLogs())
1683 runner.CleanupDirs()
1684 checkErr("UpdateContainerFinal", runner.UpdateContainerFinal())
1687 runner.setupSignals()
1688 err = runner.startHoststat()
1692 if runner.keepstore != nil {
1693 runner.hoststatReporter.ReportPID("keepstore", runner.keepstore.Process.Pid)
1696 // set up FUSE mount and binds
1697 bindmounts, err = runner.SetupMounts()
1699 runner.finalState = "Cancelled"
1700 err = fmt.Errorf("While setting up mounts: %v", err)
1704 // check for and/or load image
1705 imageID, err := runner.LoadImage()
1707 if !runner.checkBrokenNode(err) {
1708 // Failed to load image but not due to a "broken node"
1709 // condition, probably user error.
1710 runner.finalState = "Cancelled"
1712 err = fmt.Errorf("While loading container image: %v", err)
1716 err = runner.CreateContainer(imageID, bindmounts)
1720 err = runner.LogHostInfo()
1724 err = runner.LogNodeRecord()
1728 err = runner.LogContainerRecord()
1733 if runner.IsCancelled() {
1737 logCollection, err := runner.saveLogCollection(false)
1740 logId = logCollection.PortableDataHash
1742 runner.CrunchLog.Printf("Error committing initial log collection: %v", err)
1744 err = runner.UpdateContainerRunning(logId)
1748 runner.finalState = "Cancelled"
1750 err = runner.startCrunchstat()
1755 err = runner.StartContainer()
1757 runner.checkBrokenNode(err)
1761 err = runner.WaitFinish()
1762 if err == nil && !runner.IsCancelled() {
1763 runner.finalState = "Complete"
1768 // Fetch the current container record (uuid = runner.Container.UUID)
1769 // into runner.Container.
1770 func (runner *ContainerRunner) fetchContainerRecord() error {
1771 reader, err := runner.DispatcherArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1773 return fmt.Errorf("error fetching container record: %v", err)
1775 defer reader.Close()
1777 dec := json.NewDecoder(reader)
1779 err = dec.Decode(&runner.Container)
1781 return fmt.Errorf("error decoding container record: %v", err)
1785 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
1788 containerToken, err := runner.ContainerToken()
1790 return fmt.Errorf("error getting container token: %v", err)
1793 runner.ContainerArvClient, runner.ContainerKeepClient,
1794 runner.containerClient, err = runner.MkArvClient(containerToken)
1796 return fmt.Errorf("error creating container API client: %v", err)
1799 runner.ContainerKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1800 runner.DispatcherKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1802 err = runner.ContainerArvClient.Call("GET", "containers", runner.Container.UUID, "secret_mounts", nil, &sm)
1804 if apierr, ok := err.(arvadosclient.APIServerError); !ok || apierr.HttpStatusCode != 404 {
1805 return fmt.Errorf("error fetching secret_mounts: %v", err)
1807 // ok && apierr.HttpStatusCode == 404, which means
1808 // secret_mounts isn't supported by this API server.
1810 runner.SecretMounts = sm.SecretMounts
1815 // NewContainerRunner creates a new container runner.
1816 func NewContainerRunner(dispatcherClient *arvados.Client,
1817 dispatcherArvClient IArvadosClient,
1818 dispatcherKeepClient IKeepClient,
1819 containerUUID string) (*ContainerRunner, error) {
1821 cr := &ContainerRunner{
1822 dispatcherClient: dispatcherClient,
1823 DispatcherArvClient: dispatcherArvClient,
1824 DispatcherKeepClient: dispatcherKeepClient,
1826 cr.RunArvMount = cr.ArvMountCmd
1827 cr.MkTempDir = ioutil.TempDir
1828 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1829 cl, err := arvadosclient.MakeArvadosClient()
1831 return nil, nil, nil, err
1834 kc, err := keepclient.MakeKeepClient(cl)
1836 return nil, nil, nil, err
1838 c2 := arvados.NewClientFromEnv()
1839 c2.AuthToken = token
1840 return cl, kc, c2, nil
1843 cr.LogCollection, err = (&arvados.Collection{}).FileSystem(cr.dispatcherClient, cr.DispatcherKeepClient)
1847 cr.Container.UUID = containerUUID
1848 f, err := cr.openLogFile("crunch-run")
1852 cr.CrunchLog = newLogWriter(newTimestamper(io.MultiWriter(f, newStringPrefixer(os.Stderr, cr.Container.UUID+" "))))
1859 func (command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
1860 log := log.New(stderr, "", 0)
1861 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
1862 statInterval := flags.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1863 flags.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree (obsolete, ignored)")
1864 flags.String("cgroup-parent", "docker", "name of container's parent cgroup (obsolete, ignored)")
1865 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")
1866 caCertsPath := flags.String("ca-certs", "", "Path to TLS root certificates")
1867 detach := flags.Bool("detach", false, "Detach from parent process and run in the background")
1868 stdinConfig := flags.Bool("stdin-config", false, "Load config and environment variables from JSON message on stdin")
1869 configFile := flags.String("config", arvados.DefaultConfigFile, "filename of cluster config file to try loading if -stdin-config=false (default is $ARVADOS_CONFIG)")
1870 sleep := flags.Duration("sleep", 0, "Delay before starting (testing use only)")
1871 kill := flags.Int("kill", -1, "Send signal to an existing crunch-run process for given UUID")
1872 list := flags.Bool("list", false, "List UUIDs of existing crunch-run processes (and notify them to use price data passed on stdin)")
1873 enableMemoryLimit := flags.Bool("enable-memory-limit", true, "tell container runtime to limit container's memory usage")
1874 enableNetwork := flags.String("container-enable-networking", "default", "enable networking \"always\" (for all containers) or \"default\" (for containers that request it)")
1875 networkMode := flags.String("container-network-mode", "default", `Docker network mode for container (use any argument valid for docker --net)`)
1876 memprofile := flags.String("memprofile", "", "write memory profile to `file` after running container")
1877 runtimeEngine := flags.String("runtime-engine", "docker", "container runtime: docker or singularity")
1878 brokenNodeHook := flags.String("broken-node-hook", "", "script to run if node is detected to be broken (for example, Docker daemon is not running)")
1879 flags.Duration("check-containerd", 0, "Ignored. Exists for compatibility with older versions.")
1880 version := flags.Bool("version", false, "Write version information to stdout and exit 0.")
1882 ignoreDetachFlag := false
1883 if len(args) > 0 && args[0] == "-no-detach" {
1884 // This process was invoked by a parent process, which
1885 // has passed along its own arguments, including
1886 // -detach, after the leading -no-detach flag. Strip
1887 // the leading -no-detach flag (it's not recognized by
1888 // flags.Parse()) and ignore the -detach flag that
1891 ignoreDetachFlag = true
1894 if ok, code := cmd.ParseFlags(flags, prog, args, "container-uuid", stderr); !ok {
1896 } else if *version {
1897 fmt.Fprintln(stdout, prog, cmd.Version.String())
1899 } else if !*list && flags.NArg() != 1 {
1900 fmt.Fprintf(stderr, "missing required argument: container-uuid (try -help)\n")
1904 containerUUID := flags.Arg(0)
1907 case *detach && !ignoreDetachFlag:
1908 return Detach(containerUUID, prog, args, stdin, stdout, stderr)
1910 return KillProcess(containerUUID, syscall.Signal(*kill), stdout, stderr)
1912 return ListProcesses(stdin, stdout, stderr)
1915 if len(containerUUID) != 27 {
1916 log.Printf("usage: %s [options] UUID", prog)
1920 var keepstoreLogbuf bufThenWrite
1923 err := json.NewDecoder(stdin).Decode(&conf)
1925 log.Printf("decode stdin: %s", err)
1928 for k, v := range conf.Env {
1929 err = os.Setenv(k, v)
1931 log.Printf("setenv(%q): %s", k, err)
1935 if conf.Cluster != nil {
1936 // ClusterID is missing from the JSON
1937 // representation, but we need it to generate
1938 // a valid config file for keepstore, so we
1939 // fill it using the container UUID prefix.
1940 conf.Cluster.ClusterID = containerUUID[:5]
1943 conf = hpcConfData(containerUUID, *configFile, io.MultiWriter(&keepstoreLogbuf, stderr))
1946 log.Printf("crunch-run %s started", cmd.Version.String())
1949 if *caCertsPath != "" {
1950 os.Setenv("SSL_CERT_FILE", *caCertsPath)
1953 keepstore, err := startLocalKeepstore(conf, io.MultiWriter(&keepstoreLogbuf, stderr))
1958 if keepstore != nil {
1959 defer keepstore.Process.Kill()
1962 api, err := arvadosclient.MakeArvadosClient()
1964 log.Printf("%s: %v", containerUUID, err)
1967 // arvadosclient now interprets Retries=10 to mean
1968 // Timeout=10m, retrying with exponential backoff + jitter.
1971 kc, err := keepclient.MakeKeepClient(api)
1973 log.Printf("%s: %v", containerUUID, err)
1978 cr, err := NewContainerRunner(arvados.NewClientFromEnv(), api, kc, containerUUID)
1984 cr.keepstore = keepstore
1985 if keepstore == nil {
1986 // Log explanation (if any) for why we're not running
1987 // a local keepstore.
1988 var buf bytes.Buffer
1989 keepstoreLogbuf.SetWriter(&buf)
1991 cr.CrunchLog.Printf("%s", strings.TrimSpace(buf.String()))
1993 } else if logWhat := conf.Cluster.Containers.LocalKeepLogsToContainerLog; logWhat == "none" {
1994 cr.CrunchLog.Printf("using local keepstore process (pid %d) at %s", keepstore.Process.Pid, os.Getenv("ARVADOS_KEEP_SERVICES"))
1995 keepstoreLogbuf.SetWriter(io.Discard)
1997 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"))
1998 cr.keepstoreLogger, err = cr.openLogFile("keepstore")
2004 var writer io.WriteCloser = cr.keepstoreLogger
2005 if logWhat == "errors" {
2006 writer = &filterKeepstoreErrorsOnly{WriteCloser: writer}
2007 } else if logWhat != "all" {
2008 // should have been caught earlier by
2009 // dispatcher's config loader
2010 log.Printf("invalid value for Containers.LocalKeepLogsToContainerLog: %q", logWhat)
2013 err = keepstoreLogbuf.SetWriter(writer)
2018 cr.keepstoreLogbuf = &keepstoreLogbuf
2021 switch *runtimeEngine {
2023 cr.executor, err = newDockerExecutor(containerUUID, cr.CrunchLog.Printf, cr.containerWatchdogInterval)
2025 cr.executor, err = newSingularityExecutor(cr.CrunchLog.Printf)
2027 cr.CrunchLog.Printf("%s: unsupported RuntimeEngine %q", containerUUID, *runtimeEngine)
2031 cr.CrunchLog.Printf("%s: %v", containerUUID, err)
2032 cr.checkBrokenNode(err)
2035 defer cr.executor.Close()
2037 cr.brokenNodeHook = *brokenNodeHook
2039 gwAuthSecret := os.Getenv("GatewayAuthSecret")
2040 os.Unsetenv("GatewayAuthSecret")
2041 if gwAuthSecret == "" {
2042 // not safe to run a gateway service without an auth
2044 cr.CrunchLog.Printf("Not starting a gateway server (GatewayAuthSecret was not provided by dispatcher)")
2046 gwListen := os.Getenv("GatewayAddress")
2047 cr.gateway = Gateway{
2049 AuthSecret: gwAuthSecret,
2050 ContainerUUID: containerUUID,
2051 Target: cr.executor,
2053 LogCollection: cr.LogCollection,
2056 // Direct connection won't work, so we use the
2057 // gateway_address field to indicate the
2058 // internalURL of the controller process that
2059 // has the current tunnel connection.
2060 cr.gateway.ArvadosClient = cr.dispatcherClient
2061 cr.gateway.UpdateTunnelURL = func(url string) {
2062 cr.gateway.Address = "tunnel " + url
2063 cr.DispatcherArvClient.Update("containers", containerUUID,
2065 "select": []string{"uuid"},
2066 "container": arvadosclient.Dict{"gateway_address": cr.gateway.Address},
2070 err = cr.gateway.Start()
2072 log.Printf("error starting gateway server: %s", err)
2077 parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerUUID+".")
2079 log.Printf("%s: %v", containerUUID, tmperr)
2083 cr.parentTemp = parentTemp
2084 cr.statInterval = *statInterval
2085 cr.enableMemoryLimit = *enableMemoryLimit
2086 cr.enableNetwork = *enableNetwork
2087 cr.networkMode = *networkMode
2088 if *cgroupParentSubsystem != "" {
2089 p, err := findCgroup(os.DirFS("/"), *cgroupParentSubsystem)
2091 log.Printf("fatal: cgroup parent subsystem: %s", err)
2094 cr.setCgroupParent = p
2097 if conf.EC2SpotCheck {
2098 go cr.checkSpotInterruptionNotices()
2103 if *memprofile != "" {
2104 f, err := os.Create(*memprofile)
2106 log.Printf("could not create memory profile: %s", err)
2108 runtime.GC() // get up-to-date statistics
2109 if err := pprof.WriteHeapProfile(f); err != nil {
2110 log.Printf("could not write memory profile: %s", err)
2112 closeerr := f.Close()
2113 if closeerr != nil {
2114 log.Printf("closing memprofile file: %s", err)
2119 log.Printf("%s: %v", containerUUID, runerr)
2125 // Try to load ConfigData in hpc (slurm/lsf) environment. This means
2126 // loading the cluster config from the specified file and (if that
2127 // works) getting the runtime_constraints container field from
2128 // controller to determine # VCPUs so we can calculate KeepBuffers.
2129 func hpcConfData(uuid string, configFile string, stderr io.Writer) ConfigData {
2131 conf.Cluster = loadClusterConfigFile(configFile, stderr)
2132 if conf.Cluster == nil {
2133 // skip loading the container record -- we won't be
2134 // able to start local keepstore anyway.
2137 arv, err := arvadosclient.MakeArvadosClient()
2139 fmt.Fprintf(stderr, "error setting up arvadosclient: %s\n", err)
2142 // arvadosclient now interprets Retries=10 to mean
2143 // Timeout=10m, retrying with exponential backoff + jitter.
2145 var ctr arvados.Container
2146 err = arv.Call("GET", "containers", uuid, "", arvadosclient.Dict{"select": []string{"runtime_constraints"}}, &ctr)
2148 fmt.Fprintf(stderr, "error getting container record: %s\n", err)
2151 if ctr.RuntimeConstraints.VCPUs > 0 {
2152 conf.KeepBuffers = ctr.RuntimeConstraints.VCPUs * conf.Cluster.Containers.LocalKeepBlobBuffersPerVCPU
2157 // Load cluster config file from given path. If an error occurs, log
2158 // the error to stderr and return nil.
2159 func loadClusterConfigFile(path string, stderr io.Writer) *arvados.Cluster {
2160 ldr := config.NewLoader(&bytes.Buffer{}, ctxlog.New(stderr, "plain", "info"))
2162 cfg, err := ldr.Load()
2164 fmt.Fprintf(stderr, "could not load config file %s: %s\n", path, err)
2167 cluster, err := cfg.GetCluster("")
2169 fmt.Fprintf(stderr, "could not use config file %s: %s\n", path, err)
2172 fmt.Fprintf(stderr, "loaded config file %s\n", path)
2176 func startLocalKeepstore(configData ConfigData, logbuf io.Writer) (*exec.Cmd, error) {
2177 if configData.KeepBuffers < 1 {
2178 fmt.Fprintf(logbuf, "not starting a local keepstore process because KeepBuffers=%v in config\n", configData.KeepBuffers)
2181 if configData.Cluster == nil {
2182 fmt.Fprint(logbuf, "not starting a local keepstore process because cluster config file was not loaded\n")
2185 for uuid, vol := range configData.Cluster.Volumes {
2186 if len(vol.AccessViaHosts) > 0 {
2187 fmt.Fprintf(logbuf, "not starting a local keepstore process because a volume (%s) uses AccessViaHosts\n", uuid)
2190 if !vol.ReadOnly && vol.Replication < configData.Cluster.Collections.DefaultReplication {
2191 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)
2196 // Rather than have an alternate way to tell keepstore how
2197 // many buffers to use, etc., when starting it this way, we
2198 // just modify the cluster configuration that we feed it on
2200 ccfg := *configData.Cluster
2201 ccfg.API.MaxKeepBlobBuffers = configData.KeepBuffers
2202 ccfg.Collections.BlobTrash = false
2203 ccfg.Collections.BlobTrashConcurrency = 0
2204 ccfg.Collections.BlobDeleteConcurrency = 0
2206 localaddr := localKeepstoreAddr()
2207 ln, err := net.Listen("tcp", net.JoinHostPort(localaddr, "0"))
2211 _, port, err := net.SplitHostPort(ln.Addr().String())
2217 url := "http://" + net.JoinHostPort(localaddr, port)
2219 fmt.Fprintf(logbuf, "starting keepstore on %s\n", url)
2221 var confJSON bytes.Buffer
2222 err = json.NewEncoder(&confJSON).Encode(arvados.Config{
2223 Clusters: map[string]arvados.Cluster{
2224 ccfg.ClusterID: ccfg,
2230 cmd := exec.Command("/proc/self/exe", "keepstore", "-config=-")
2231 if target, err := os.Readlink(cmd.Path); err == nil && strings.HasSuffix(target, ".test") {
2232 // If we're a 'go test' process, running
2233 // /proc/self/exe would start the test suite in a
2234 // child process, which is not what we want.
2235 cmd.Path, _ = exec.LookPath("go")
2236 cmd.Args = append([]string{"go", "run", "../../cmd/arvados-server"}, cmd.Args[1:]...)
2237 cmd.Env = os.Environ()
2239 cmd.Stdin = &confJSON
2242 cmd.Env = append(cmd.Env,
2244 "ARVADOS_SERVICE_INTERNAL_URL="+url)
2247 return nil, fmt.Errorf("error starting keepstore process: %w", err)
2254 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*10))
2256 poll := time.NewTicker(time.Second / 10)
2258 client := http.Client{}
2260 testReq, err := http.NewRequestWithContext(ctx, "GET", url+"/_health/ping", nil)
2261 testReq.Header.Set("Authorization", "Bearer "+configData.Cluster.ManagementToken)
2265 resp, err := client.Do(testReq)
2268 if resp.StatusCode == http.StatusOK {
2273 return nil, fmt.Errorf("keepstore child process exited")
2275 if ctx.Err() != nil {
2276 return nil, fmt.Errorf("timed out waiting for new keepstore process to report healthy")
2279 os.Setenv("ARVADOS_KEEP_SERVICES", url)
2283 // return current uid, gid, groups in a format suitable for logging:
2284 // "crunch-run process has uid=1234(arvados) gid=1234(arvados)
2285 // groups=1234(arvados),114(fuse)"
2286 func currentUserAndGroups() string {
2287 u, err := user.Current()
2289 return fmt.Sprintf("error getting current user ID: %s", err)
2291 s := fmt.Sprintf("crunch-run process has uid=%s(%s) gid=%s", u.Uid, u.Username, u.Gid)
2292 if g, err := user.LookupGroupId(u.Gid); err == nil {
2293 s += fmt.Sprintf("(%s)", g.Name)
2296 if gids, err := u.GroupIds(); err == nil {
2297 for i, gid := range gids {
2302 if g, err := user.LookupGroupId(gid); err == nil {
2303 s += fmt.Sprintf("(%s)", g.Name)
2310 // Return a suitable local interface address for a local keepstore
2311 // service. Currently this is the numerically lowest non-loopback ipv4
2312 // address assigned to a local interface that is not in any of the
2313 // link-local/vpn/loopback ranges 169.254/16, 100.64/10, or 127/8.
2314 func localKeepstoreAddr() string {
2316 // Ignore error (proceed with zero IPs)
2317 addrs, _ := processIPs(os.Getpid())
2318 for addr := range addrs {
2319 ip := net.ParseIP(addr)
2324 if ip.Mask(net.CIDRMask(8, 32)).Equal(net.IPv4(127, 0, 0, 0)) ||
2325 ip.Mask(net.CIDRMask(10, 32)).Equal(net.IPv4(100, 64, 0, 0)) ||
2326 ip.Mask(net.CIDRMask(16, 32)).Equal(net.IPv4(169, 254, 0, 0)) {
2330 ips = append(ips, ip)
2335 sort.Slice(ips, func(ii, jj int) bool {
2336 i, j := ips[ii], ips[jj]
2337 if len(i) != len(j) {
2338 return len(i) < len(j)
2347 return ips[0].String()
2350 func (cr *ContainerRunner) loadPrices() {
2351 buf, err := os.ReadFile(filepath.Join(lockdir, pricesfile))
2353 if !os.IsNotExist(err) {
2354 cr.CrunchLog.Printf("loadPrices: read: %s", err)
2358 var prices []cloud.InstancePrice
2359 err = json.Unmarshal(buf, &prices)
2361 cr.CrunchLog.Printf("loadPrices: decode: %s", err)
2364 cr.pricesLock.Lock()
2365 defer cr.pricesLock.Unlock()
2366 var lastKnown time.Time
2367 if len(cr.prices) > 0 {
2368 lastKnown = cr.prices[0].StartTime
2370 cr.prices = cloud.NormalizePriceHistory(append(prices, cr.prices...))
2371 for i := len(cr.prices) - 1; i >= 0; i-- {
2372 price := cr.prices[i]
2373 if price.StartTime.After(lastKnown) {
2374 cr.CrunchLog.Printf("Instance price changed to %#.3g at %s", price.Price, price.StartTime.UTC())
2379 func (cr *ContainerRunner) calculateCost(now time.Time) float64 {
2380 cr.pricesLock.Lock()
2381 defer cr.pricesLock.Unlock()
2383 // First, make a "prices" slice with the real data as far back
2384 // as it goes, and (if needed) a "since the beginning of time"
2385 // placeholder containing a reasonable guess about what the
2386 // price was between cr.costStartTime and the earliest real
2389 if len(prices) == 0 {
2390 // use price info in InstanceType record initially
2391 // provided by cloud dispatcher
2393 var it arvados.InstanceType
2394 if j := os.Getenv("InstanceType"); j != "" && json.Unmarshal([]byte(j), &it) == nil && it.Price > 0 {
2397 prices = []cloud.InstancePrice{{Price: p}}
2398 } else if prices[len(prices)-1].StartTime.After(cr.costStartTime) {
2399 // guess earlier pricing was the same as the earliest
2400 // price we know about
2401 filler := prices[len(prices)-1]
2402 filler.StartTime = time.Time{}
2403 prices = append(prices, filler)
2406 // Now that our history of price changes goes back at least as
2407 // far as cr.costStartTime, add up the costs for each
2411 for _, ip := range prices {
2412 spanStart := ip.StartTime
2413 if spanStart.After(now) {
2414 // pricing information from the future -- not
2415 // expected from AWS, but possible in
2416 // principle, and exercised by tests.
2420 if spanStart.Before(cr.costStartTime) {
2421 spanStart = cr.costStartTime
2424 cost += ip.Price * spanEnd.Sub(spanStart).Seconds() / 3600
2434 func (runner *ContainerRunner) handleSIGUSR2(sigchan chan os.Signal) {
2437 update := arvadosclient.Dict{
2438 "select": []string{"uuid"},
2439 "container": arvadosclient.Dict{
2440 "cost": runner.calculateCost(time.Now()),
2443 runner.DispatcherArvClient.Update("containers", runner.Container.UUID, update, nil)