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 "git.arvados.org/arvados.git/sdk/go/manifest"
44 "golang.org/x/sys/unix"
49 var arvadosCertPath = "/etc/arvados/ca-certificates.crt"
51 var Command = command{}
53 // ConfigData contains environment variables and (when needed) cluster
54 // configuration, passed from dispatchcloud to crunch-run on stdin.
55 type ConfigData struct {
59 Cluster *arvados.Cluster
62 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
63 type IArvadosClient interface {
64 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
65 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
66 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
67 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
68 CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
69 Discovery(key string) (interface{}, error)
72 // ErrCancelled is the error returned when the container is cancelled.
73 var ErrCancelled = errors.New("Cancelled")
75 // IKeepClient is the minimal Keep API methods used by crunch-run.
76 type IKeepClient interface {
77 BlockWrite(context.Context, arvados.BlockWriteOptions) (arvados.BlockWriteResponse, error)
78 ReadAt(locator string, p []byte, off int) (int, error)
79 ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error)
80 LocalLocator(locator string) (string, error)
81 SetStorageClasses(sc []string)
84 type RunArvMount func(cmdline []string, tok string) (*exec.Cmd, error)
86 type MkTempDir func(string, string) (string, error)
88 type PsProcess interface {
89 CmdlineSlice() ([]string, error)
92 // ContainerRunner is the main stateful struct used for a single execution of a
94 type ContainerRunner struct {
95 executor containerExecutor
96 executorStdin io.Closer
97 executorStdout io.Closer
98 executorStderr io.Closer
100 // Dispatcher client is initialized with the Dispatcher token.
101 // This is a privileged token used to manage container status
104 // We have both dispatcherClient and DispatcherArvClient
105 // because there are two different incompatible Arvados Go
106 // SDKs and we have to use both (hopefully this gets fixed in
108 dispatcherClient *arvados.Client
109 DispatcherArvClient IArvadosClient
110 DispatcherKeepClient IKeepClient
112 // Container client is initialized with the Container token
113 // This token controls the permissions of the container, and
114 // must be used for operations such as reading collections.
116 // Same comment as above applies to
117 // containerClient/ContainerArvClient.
118 containerClient *arvados.Client
119 ContainerArvClient IArvadosClient
120 ContainerKeepClient IKeepClient
122 Container arvados.Container
128 LogCollection arvados.CollectionFileSystem
130 RunArvMount RunArvMount
135 Volumes map[string]struct{}
137 SigChan chan os.Signal
138 ArvMountExit chan error
139 SecretMounts map[string]arvados.Mount
140 MkArvClient func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error)
143 costStartTime time.Time
146 keepstoreLogger io.WriteCloser
147 keepstoreLogbuf *bufThenWrite
148 statLogger io.WriteCloser
149 statReporter *crunchstat.Reporter
150 hoststatLogger io.WriteCloser
151 hoststatReporter *crunchstat.Reporter
152 statInterval time.Duration
153 // What we tell docker to use as the container's cgroup
155 setCgroupParent string
156 // Fake root dir where crunchstat.Reporter should read OS
157 // files, for testing.
158 crunchstatFakeFS fs.FS
160 cStateLock sync.Mutex
161 cCancelled bool // StopContainer() invoked
163 enableMemoryLimit bool
164 enableNetwork string // one of "default" or "always"
165 networkMode string // "none", "host", or "" -- passed through to executor
166 brokenNodeHook string // script to run if node appears to be broken
167 arvMountLog io.WriteCloser
169 containerWatchdogInterval time.Duration
173 prices []cloud.InstancePrice
174 pricesLock sync.Mutex
177 // setupSignals sets up signal handling to gracefully terminate the
178 // underlying container and update state when receiving a TERM, INT or
180 func (runner *ContainerRunner) setupSignals() {
181 runner.SigChan = make(chan os.Signal, 1)
182 signal.Notify(runner.SigChan, syscall.SIGTERM)
183 signal.Notify(runner.SigChan, syscall.SIGINT)
184 signal.Notify(runner.SigChan, syscall.SIGQUIT)
186 go func(sig chan os.Signal) {
193 // stop the underlying container.
194 func (runner *ContainerRunner) stop(sig os.Signal) {
195 runner.cStateLock.Lock()
196 defer runner.cStateLock.Unlock()
198 runner.CrunchLog.Printf("caught signal: %v", sig)
200 runner.cCancelled = true
201 runner.CrunchLog.Printf("stopping container")
202 err := runner.executor.Stop()
204 runner.CrunchLog.Printf("error stopping container: %s", err)
208 var errorBlacklist = []string{
209 "(?ms).*[Cc]annot connect to the Docker daemon.*",
210 "(?ms).*oci runtime error.*starting container process.*container init.*mounting.*to rootfs.*no such file or directory.*",
211 "(?ms).*grpc: the connection is unavailable.*",
214 func (runner *ContainerRunner) runBrokenNodeHook() {
215 if runner.brokenNodeHook == "" {
216 path := filepath.Join(lockdir, brokenfile)
217 runner.CrunchLog.Printf("Writing %s to mark node as broken", path)
218 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0700)
220 runner.CrunchLog.Printf("Error writing %s: %s", path, err)
225 runner.CrunchLog.Printf("Running broken node hook %q", runner.brokenNodeHook)
227 c := exec.Command(runner.brokenNodeHook)
228 c.Stdout = runner.CrunchLog
229 c.Stderr = runner.CrunchLog
232 runner.CrunchLog.Printf("Error running broken node hook: %v", err)
237 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
238 for _, d := range errorBlacklist {
239 if m, e := regexp.MatchString(d, goterr.Error()); m && e == nil {
240 runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
241 runner.runBrokenNodeHook()
248 // LoadImage determines the docker image id from the container record and
249 // checks if it is available in the local Docker image store. If not, it loads
250 // the image from Keep.
251 func (runner *ContainerRunner) LoadImage() (string, error) {
252 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
254 d, err := os.Open(runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage)
259 allfiles, err := d.Readdirnames(-1)
263 var tarfiles []string
264 for _, fnm := range allfiles {
265 if strings.HasSuffix(fnm, ".tar") {
266 tarfiles = append(tarfiles, fnm)
269 if len(tarfiles) == 0 {
270 return "", fmt.Errorf("image collection does not include a .tar image file")
272 if len(tarfiles) > 1 {
273 return "", fmt.Errorf("cannot choose from multiple tar files in image collection: %v", tarfiles)
275 imageID := tarfiles[0][:len(tarfiles[0])-4]
276 imageTarballPath := runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage + "/" + imageID + ".tar"
277 runner.CrunchLog.Printf("Using Docker image id %q", imageID)
279 runner.CrunchLog.Print("Loading Docker image from keep")
280 err = runner.executor.LoadImage(imageID, imageTarballPath, runner.Container, runner.ArvMountPoint,
281 runner.containerClient)
289 func (runner *ContainerRunner) ArvMountCmd(cmdline []string, token string) (c *exec.Cmd, err error) {
290 c = exec.Command(cmdline[0], cmdline[1:]...)
292 // Copy our environment, but override ARVADOS_API_TOKEN with
293 // the container auth token.
295 for _, s := range os.Environ() {
296 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
297 c.Env = append(c.Env, s)
300 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
302 runner.arvMountLog, err = runner.openLogFile("arv-mount")
306 scanner := logScanner{
309 "Block not found error",
310 "Unhandled exception during FUSE operation",
312 ReportFunc: func(pattern, text string) {
313 runner.updateRuntimeStatus(arvadosclient.Dict{
314 "warning": "arv-mount: " + pattern,
315 "warningDetail": text,
319 c.Stdout = runner.arvMountLog
320 c.Stderr = io.MultiWriter(runner.arvMountLog, os.Stderr, &scanner)
322 runner.CrunchLog.Printf("Running %v", c.Args)
329 statReadme := make(chan bool)
330 runner.ArvMountExit = make(chan error)
335 time.Sleep(100 * time.Millisecond)
336 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
348 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
350 runner.ArvMountExit <- mnterr
351 close(runner.ArvMountExit)
357 case err := <-runner.ArvMountExit:
358 runner.ArvMount = nil
366 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
367 if runner.ArvMountPoint == "" {
368 runner.ArvMountPoint, err = runner.MkTempDir(runner.parentTemp, prefix)
373 func copyfile(src string, dst string) (err error) {
374 srcfile, err := os.Open(src)
379 os.MkdirAll(path.Dir(dst), 0777)
381 dstfile, err := os.Create(dst)
385 _, err = io.Copy(dstfile, srcfile)
390 err = srcfile.Close()
391 err2 := dstfile.Close()
404 func (runner *ContainerRunner) SetupMounts() (map[string]bindmount, error) {
405 bindmounts := map[string]bindmount{}
406 err := runner.SetupArvMountPoint("keep")
408 return nil, fmt.Errorf("While creating keep mount temp dir: %v", err)
411 token, err := runner.ContainerToken()
413 return nil, fmt.Errorf("could not get container token: %s", err)
415 runner.CrunchLog.Printf("container token %q", token)
419 arvMountCmd := []string{
423 "--storage-classes", strings.Join(runner.Container.OutputStorageClasses, ","),
424 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
426 if _, isdocker := runner.executor.(*dockerExecutor); isdocker {
427 arvMountCmd = append(arvMountCmd, "--allow-other")
430 if runner.Container.RuntimeConstraints.KeepCacheDisk > 0 {
431 keepcachedir, err := runner.MkTempDir(runner.parentTemp, "keepcache")
433 return nil, fmt.Errorf("while creating keep cache temp dir: %v", err)
435 arvMountCmd = append(arvMountCmd, "--disk-cache", "--disk-cache-dir", keepcachedir, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheDisk))
436 } else if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
437 arvMountCmd = append(arvMountCmd, "--ram-cache", "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
440 collectionPaths := []string{}
441 needCertMount := true
442 type copyFile struct {
446 var copyFiles []copyFile
449 for bind := range runner.Container.Mounts {
450 binds = append(binds, bind)
452 for bind := range runner.SecretMounts {
453 if _, ok := runner.Container.Mounts[bind]; ok {
454 return nil, fmt.Errorf("secret mount %q conflicts with regular mount", bind)
456 if runner.SecretMounts[bind].Kind != "json" &&
457 runner.SecretMounts[bind].Kind != "text" {
458 return nil, fmt.Errorf("secret mount %q type is %q but only 'json' and 'text' are permitted",
459 bind, runner.SecretMounts[bind].Kind)
461 binds = append(binds, bind)
465 for _, bind := range binds {
466 mnt, notSecret := runner.Container.Mounts[bind]
468 mnt = runner.SecretMounts[bind]
470 if bind == "stdout" || bind == "stderr" {
471 // Is it a "file" mount kind?
472 if mnt.Kind != "file" {
473 return nil, fmt.Errorf("unsupported mount kind '%s' for %s: only 'file' is supported", mnt.Kind, bind)
476 // Does path start with OutputPath?
477 prefix := runner.Container.OutputPath
478 if !strings.HasSuffix(prefix, "/") {
481 if !strings.HasPrefix(mnt.Path, prefix) {
482 return nil, fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
487 // Is it a "collection" mount kind?
488 if mnt.Kind != "collection" && mnt.Kind != "json" {
489 return nil, fmt.Errorf("unsupported mount kind '%s' for stdin: only 'collection' and 'json' are supported", mnt.Kind)
493 if bind == arvadosCertPath {
494 needCertMount = false
497 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
498 if mnt.Kind != "collection" && mnt.Kind != "text" && mnt.Kind != "json" {
499 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)
504 case mnt.Kind == "collection" && bind != "stdin":
506 if mnt.UUID != "" && mnt.PortableDataHash != "" {
507 return nil, fmt.Errorf("cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
511 return nil, fmt.Errorf("writing to existing collections currently not permitted")
514 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
515 } else if mnt.PortableDataHash != "" {
516 if mnt.Writable && !strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
517 return nil, fmt.Errorf("can never write to a collection specified by portable data hash")
519 idx := strings.Index(mnt.PortableDataHash, "/")
521 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
522 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
523 runner.Container.Mounts[bind] = mnt
525 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
526 if mnt.Path != "" && mnt.Path != "." {
527 if strings.HasPrefix(mnt.Path, "./") {
528 mnt.Path = mnt.Path[2:]
529 } else if strings.HasPrefix(mnt.Path, "/") {
530 mnt.Path = mnt.Path[1:]
532 src += "/" + mnt.Path
535 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
536 arvMountCmd = append(arvMountCmd, "--mount-tmp", fmt.Sprintf("tmp%d", tmpcount))
540 if bind == runner.Container.OutputPath {
541 runner.HostOutputDir = src
542 bindmounts[bind] = bindmount{HostPath: src}
543 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
544 copyFiles = append(copyFiles, copyFile{src, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
546 bindmounts[bind] = bindmount{HostPath: src}
549 bindmounts[bind] = bindmount{HostPath: src, ReadOnly: true}
551 collectionPaths = append(collectionPaths, src)
553 case mnt.Kind == "tmp":
555 tmpdir, err = runner.MkTempDir(runner.parentTemp, "tmp")
557 return nil, fmt.Errorf("while creating mount temp dir: %v", err)
559 st, staterr := os.Stat(tmpdir)
561 return nil, fmt.Errorf("while Stat on temp dir: %v", staterr)
563 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
565 return nil, fmt.Errorf("while Chmod temp dir: %v", err)
567 bindmounts[bind] = bindmount{HostPath: tmpdir}
568 if bind == runner.Container.OutputPath {
569 runner.HostOutputDir = tmpdir
572 case mnt.Kind == "json" || mnt.Kind == "text":
574 if mnt.Kind == "json" {
575 filedata, err = json.Marshal(mnt.Content)
577 return nil, fmt.Errorf("encoding json data: %v", err)
580 text, ok := mnt.Content.(string)
582 return nil, fmt.Errorf("content for mount %q must be a string", bind)
584 filedata = []byte(text)
587 tmpdir, err := runner.MkTempDir(runner.parentTemp, mnt.Kind)
589 return nil, fmt.Errorf("creating temp dir: %v", err)
591 tmpfn := filepath.Join(tmpdir, "mountdata."+mnt.Kind)
592 err = ioutil.WriteFile(tmpfn, filedata, 0444)
594 return nil, fmt.Errorf("writing temp file: %v", err)
596 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && (notSecret || runner.Container.Mounts[runner.Container.OutputPath].Kind != "collection") {
597 // In most cases, if the container
598 // specifies a literal file inside the
599 // output path, we copy it into the
600 // output directory (either a mounted
601 // collection or a staging area on the
602 // host fs). If it's a secret, it will
603 // be skipped when copying output from
604 // staging to Keep later.
605 copyFiles = append(copyFiles, copyFile{tmpfn, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
607 // If a secret is outside OutputPath,
608 // we bind mount the secret file
609 // directly just like other mounts. We
610 // also use this strategy when a
611 // secret is inside OutputPath but
612 // OutputPath is a live collection, to
613 // avoid writing the secret to
614 // Keep. Attempting to remove a
615 // bind-mounted secret file from
616 // inside the container will return a
617 // "Device or resource busy" error
618 // that might not be handled well by
619 // the container, which is why we
620 // don't use this strategy when
621 // OutputPath is a staging directory.
622 bindmounts[bind] = bindmount{HostPath: tmpfn, ReadOnly: true}
627 if runner.HostOutputDir == "" {
628 return nil, fmt.Errorf("output path does not correspond to a writable mount point")
631 if needCertMount && runner.Container.RuntimeConstraints.API {
632 for _, certfile := range []string{
633 // Populated by caller, or sdk/go/arvados init(), or test suite:
634 os.Getenv("SSL_CERT_FILE"),
635 // Copied from Go 1.21 stdlib (src/crypto/x509/root_linux.go):
636 "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu/Gentoo etc.
637 "/etc/pki/tls/certs/ca-bundle.crt", // Fedora/RHEL 6
638 "/etc/ssl/ca-bundle.pem", // OpenSUSE
639 "/etc/pki/tls/cacert.pem", // OpenELEC
640 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", // CentOS/RHEL 7
641 "/etc/ssl/cert.pem", // Alpine Linux
643 if _, err := os.Stat(certfile); err == nil {
644 bindmounts[arvadosCertPath] = bindmount{HostPath: certfile, ReadOnly: true}
651 // If we are only mounting collections by pdh, make
652 // sure we don't subscribe to websocket events to
653 // avoid putting undesired load on the API server
654 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id", "--disable-event-listening")
656 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
658 // the by_uuid mount point is used by singularity when writing
659 // out docker images converted to SIF
660 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_uuid")
661 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
663 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
665 return nil, fmt.Errorf("while trying to start arv-mount: %v", err)
667 if runner.hoststatReporter != nil && runner.ArvMount != nil {
668 runner.hoststatReporter.ReportPID("arv-mount", runner.ArvMount.Process.Pid)
671 for _, p := range collectionPaths {
674 return nil, fmt.Errorf("while checking that input files exist: %v", err)
678 for _, cp := range copyFiles {
679 st, err := os.Stat(cp.src)
681 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
684 err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
688 target := path.Join(cp.bind, walkpath[len(cp.src):])
689 if walkinfo.Mode().IsRegular() {
690 copyerr := copyfile(walkpath, target)
694 return os.Chmod(target, walkinfo.Mode()|0777)
695 } else if walkinfo.Mode().IsDir() {
696 mkerr := os.MkdirAll(target, 0777)
700 return os.Chmod(target, walkinfo.Mode()|os.ModeSetgid|0777)
702 return fmt.Errorf("source %q is not a regular file or directory", cp.src)
705 } else if st.Mode().IsRegular() {
706 err = copyfile(cp.src, cp.bind)
708 err = os.Chmod(cp.bind, st.Mode()|0777)
712 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
716 return bindmounts, nil
719 func (runner *ContainerRunner) stopHoststat() error {
720 if runner.hoststatReporter == nil {
723 runner.hoststatReporter.Stop()
724 runner.hoststatReporter.LogProcessMemMax(runner.CrunchLog)
725 err := runner.hoststatLogger.Close()
727 return fmt.Errorf("error closing hoststat logs: %v", err)
732 func (runner *ContainerRunner) startHoststat() error {
734 runner.hoststatLogger, err = runner.openLogFile("hoststat")
738 runner.hoststatReporter = &crunchstat.Reporter{
739 Logger: newLogWriter(runner.hoststatLogger),
740 // Our own cgroup is the "host" cgroup, in the sense
741 // that it accounts for resource usage outside the
742 // container. It doesn't count _all_ resource usage on
745 // TODO?: Use the furthest ancestor of our own cgroup
746 // that has stats available. (Currently crunchstat
747 // does not have that capability.)
749 PollPeriod: runner.statInterval,
751 runner.hoststatReporter.Start()
752 runner.hoststatReporter.ReportPID("crunch-run", os.Getpid())
756 func (runner *ContainerRunner) startCrunchstat() error {
758 runner.statLogger, err = runner.openLogFile("crunchstat")
762 runner.statReporter = &crunchstat.Reporter{
763 Pid: runner.executor.Pid,
764 FS: runner.crunchstatFakeFS,
765 Logger: newLogWriter(runner.statLogger),
766 MemThresholds: map[string][]crunchstat.Threshold{
767 "rss": crunchstat.NewThresholdsFromPercentages(runner.Container.RuntimeConstraints.RAM, []int64{90, 95, 99}),
769 PollPeriod: runner.statInterval,
770 TempDir: runner.parentTemp,
771 ThresholdLogger: runner.CrunchLog,
773 runner.statReporter.Start()
777 type infoCommand struct {
782 // LogHostInfo logs info about the current host, for debugging and
783 // accounting purposes. Although it's logged as "node-info", this is
784 // about the environment where crunch-run is actually running, which
785 // might differ from what's described in the node record (see
787 func (runner *ContainerRunner) LogHostInfo() (err error) {
788 w, err := runner.openLogFile("node-info")
793 commands := []infoCommand{
795 label: "Host Information",
796 cmd: []string{"uname", "-a"},
799 label: "CPU Information",
800 cmd: []string{"cat", "/proc/cpuinfo"},
803 label: "Memory Information",
804 cmd: []string{"cat", "/proc/meminfo"},
808 cmd: []string{"df", "-m", "/", os.TempDir()},
811 label: "Disk INodes",
812 cmd: []string{"df", "-i", "/", os.TempDir()},
816 // Run commands with informational output to be logged.
817 for _, command := range commands {
818 fmt.Fprintln(w, command.label)
819 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
822 if err := cmd.Run(); err != nil {
823 err = fmt.Errorf("While running command %q: %v", command.cmd, err)
832 return fmt.Errorf("While closing node-info logs: %v", err)
837 // LogContainerRecord gets and saves the raw JSON container record from the API server
838 func (runner *ContainerRunner) LogContainerRecord() error {
839 logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}})
840 if !logged && err == nil {
841 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
846 // LogNodeRecord logs the current host's InstanceType config entry, if
847 // running via arvados-dispatch-cloud.
848 func (runner *ContainerRunner) LogNodeRecord() error {
849 it := os.Getenv("InstanceType")
851 // Not dispatched by arvados-dispatch-cloud.
854 // Save InstanceType config fragment received from dispatcher
856 w, err := runner.LogCollection.OpenFile("node.json", os.O_CREATE|os.O_WRONLY, 0666)
861 _, err = io.WriteString(w, it)
868 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}) (logged bool, err error) {
869 writer, err := runner.LogCollection.OpenFile(label+".json", os.O_CREATE|os.O_WRONLY, 0666)
873 reader, err := runner.DispatcherArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
875 return false, fmt.Errorf("error getting %s record: %v", label, err)
879 dec := json.NewDecoder(reader)
881 var resp map[string]interface{}
882 if err = dec.Decode(&resp); err != nil {
883 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
885 items, ok := resp["items"].([]interface{})
887 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
888 } else if len(items) < 1 {
891 // Re-encode it using indentation to improve readability
892 enc := json.NewEncoder(writer)
893 enc.SetIndent("", " ")
894 if err = enc.Encode(items[0]); err != nil {
895 return false, fmt.Errorf("error logging %s record: %v", label, err)
899 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
904 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
905 stdoutPath := mntPath[len(runner.Container.OutputPath):]
906 index := strings.LastIndex(stdoutPath, "/")
908 subdirs := stdoutPath[:index]
910 st, err := os.Stat(runner.HostOutputDir)
912 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
914 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
915 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
917 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
921 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
923 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
926 return stdoutFile, nil
929 // CreateContainer creates the docker container.
930 func (runner *ContainerRunner) CreateContainer(imageID string, bindmounts map[string]bindmount) error {
932 if mnt, ok := runner.Container.Mounts["stdin"]; ok {
939 collID = mnt.PortableDataHash
941 path := runner.ArvMountPoint + "/by_id/" + collID + "/" + mnt.Path
942 f, err := os.Open(path)
947 runner.executorStdin = f
949 j, err := json.Marshal(mnt.Content)
951 return fmt.Errorf("error encoding stdin json data: %v", err)
953 stdin = bytes.NewReader(j)
954 runner.executorStdin = io.NopCloser(nil)
956 return fmt.Errorf("stdin mount has unsupported kind %q", mnt.Kind)
959 stdin = bytes.NewReader(nil)
960 runner.executorStdin = ioutil.NopCloser(nil)
963 var stdout, stderr io.Writer
964 if mnt, ok := runner.Container.Mounts["stdout"]; ok {
965 f, err := runner.getStdoutFile(mnt.Path)
970 runner.executorStdout = f
971 } else if w, err := runner.openLogFile("stdout"); err != nil {
974 stdout = newTimestamper(w)
975 runner.executorStdout = w
978 if mnt, ok := runner.Container.Mounts["stderr"]; ok {
979 f, err := runner.getStdoutFile(mnt.Path)
984 runner.executorStderr = f
985 } else if w, err := runner.openLogFile("stderr"); err != nil {
988 stderr = newTimestamper(w)
989 runner.executorStderr = w
992 env := runner.Container.Environment
993 enableNetwork := runner.enableNetwork == "always"
994 if runner.Container.RuntimeConstraints.API {
996 tok, err := runner.ContainerToken()
1000 env = map[string]string{}
1001 for k, v := range runner.Container.Environment {
1004 env["ARVADOS_API_TOKEN"] = tok
1005 env["ARVADOS_API_HOST"] = os.Getenv("ARVADOS_API_HOST")
1006 env["ARVADOS_API_HOST_INSECURE"] = os.Getenv("ARVADOS_API_HOST_INSECURE")
1007 env["ARVADOS_KEEP_SERVICES"] = os.Getenv("ARVADOS_KEEP_SERVICES")
1009 workdir := runner.Container.Cwd
1011 // both "" and "." mean default
1014 ram := runner.Container.RuntimeConstraints.RAM
1015 if !runner.enableMemoryLimit {
1019 if runner.Container.RuntimeConstraints.CUDA.DeviceCount > 0 {
1020 nvidiaModprobe(runner.CrunchLog)
1023 return runner.executor.Create(containerSpec{
1025 VCPUs: runner.Container.RuntimeConstraints.VCPUs,
1027 WorkingDir: workdir,
1029 BindMounts: bindmounts,
1030 Command: runner.Container.Command,
1031 EnableNetwork: enableNetwork,
1032 CUDADeviceCount: runner.Container.RuntimeConstraints.CUDA.DeviceCount,
1033 NetworkMode: runner.networkMode,
1034 CgroupParent: runner.setCgroupParent,
1041 // StartContainer starts the docker container created by CreateContainer.
1042 func (runner *ContainerRunner) StartContainer() error {
1043 runner.CrunchLog.Printf("Starting container")
1044 runner.cStateLock.Lock()
1045 defer runner.cStateLock.Unlock()
1046 if runner.cCancelled {
1049 err := runner.executor.Start()
1052 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
1053 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])
1055 return fmt.Errorf("could not start container: %v%s", err, advice)
1060 // WaitFinish waits for the container to terminate, capture the exit code, and
1061 // close the stdout/stderr logging.
1062 func (runner *ContainerRunner) WaitFinish() error {
1063 runner.CrunchLog.Print("Waiting for container to finish")
1064 var timeout <-chan time.Time
1065 if s := runner.Container.SchedulingParameters.MaxRunTime; s > 0 {
1066 timeout = time.After(time.Duration(s) * time.Second)
1068 ctx, cancel := context.WithCancel(context.Background())
1073 runner.CrunchLog.Printf("maximum run time exceeded. Stopping container.")
1075 case <-runner.ArvMountExit:
1076 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
1081 exitcode, err := runner.executor.Wait(ctx)
1083 runner.checkBrokenNode(err)
1086 runner.ExitCode = &exitcode
1089 if exitcode&0x80 != 0 {
1090 // Convert raw exit status (0x80 + signal number) to a
1091 // string to log after the code, like " (signal 101)"
1092 // or " (signal 9, killed)"
1093 sig := syscall.WaitStatus(exitcode).Signal()
1094 if name := unix.SignalName(sig); name != "" {
1095 extra = fmt.Sprintf(" (signal %d, %s)", sig, name)
1097 extra = fmt.Sprintf(" (signal %d)", sig)
1100 runner.CrunchLog.Printf("Container exited with status code %d%s", exitcode, extra)
1101 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1102 "select": []string{"uuid"},
1103 "container": arvadosclient.Dict{"exit_code": exitcode},
1106 runner.CrunchLog.Printf("ignoring error updating exit_code: %s", err)
1110 if err = runner.executorStdin.Close(); err != nil {
1111 err = fmt.Errorf("error closing container stdin: %s", err)
1112 runner.CrunchLog.Printf("%s", err)
1115 if err = runner.executorStdout.Close(); err != nil {
1116 err = fmt.Errorf("error closing container stdout: %s", err)
1117 runner.CrunchLog.Printf("%s", err)
1118 if returnErr == nil {
1122 if err = runner.executorStderr.Close(); err != nil {
1123 err = fmt.Errorf("error closing container stderr: %s", err)
1124 runner.CrunchLog.Printf("%s", err)
1125 if returnErr == nil {
1130 if runner.statReporter != nil {
1131 runner.statReporter.Stop()
1132 runner.statReporter.LogMaxima(runner.CrunchLog, map[string]int64{
1133 "rss": runner.Container.RuntimeConstraints.RAM,
1135 err = runner.statLogger.Close()
1137 runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
1143 func (runner *ContainerRunner) updateLogs() {
1144 ticker := time.NewTicker(crunchLogUpdatePeriod / 360)
1147 sigusr1 := make(chan os.Signal, 1)
1148 signal.Notify(sigusr1, syscall.SIGUSR1)
1149 defer signal.Stop(sigusr1)
1151 saveAtTime := time.Now().Add(crunchLogUpdatePeriod)
1152 saveAtSize := crunchLogUpdateSize
1158 saveAtTime = time.Now()
1160 runner.logMtx.Lock()
1161 done := runner.LogsPDH != nil
1162 runner.logMtx.Unlock()
1166 size := runner.LogCollection.Size()
1167 if size == savedSize || (time.Now().Before(saveAtTime) && size < saveAtSize) {
1170 saveAtTime = time.Now().Add(crunchLogUpdatePeriod)
1171 saveAtSize = runner.LogCollection.Size() + crunchLogUpdateSize
1172 saved, err := runner.saveLogCollection(false)
1174 runner.CrunchLog.Printf("error updating log collection: %s", err)
1178 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1179 "select": []string{"uuid"},
1180 "container": arvadosclient.Dict{
1181 "log": saved.PortableDataHash,
1185 runner.CrunchLog.Printf("error updating container log to %s: %s", saved.PortableDataHash, err)
1193 var spotInterruptionCheckInterval = 5 * time.Second
1194 var ec2MetadataBaseURL = "http://169.254.169.254"
1196 const ec2TokenTTL = time.Second * 21600
1198 func (runner *ContainerRunner) checkSpotInterruptionNotices() {
1199 type ec2metadata struct {
1200 Action string `json:"action"`
1201 Time time.Time `json:"time"`
1203 runner.CrunchLog.Printf("Checking for spot interruptions every %v using instance metadata at %s", spotInterruptionCheckInterval, ec2MetadataBaseURL)
1204 var metadata ec2metadata
1206 var tokenExp time.Time
1207 check := func() error {
1208 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute))
1210 if token == "" || tokenExp.Sub(time.Now()) < time.Minute {
1211 req, err := http.NewRequestWithContext(ctx, http.MethodPut, ec2MetadataBaseURL+"/latest/api/token", nil)
1215 req.Header.Set("X-aws-ec2-metadata-token-ttl-seconds", fmt.Sprintf("%d", int(ec2TokenTTL/time.Second)))
1216 resp, err := http.DefaultClient.Do(req)
1220 defer resp.Body.Close()
1221 if resp.StatusCode != http.StatusOK {
1222 return fmt.Errorf("%s", resp.Status)
1224 newtoken, err := ioutil.ReadAll(resp.Body)
1228 token = strings.TrimSpace(string(newtoken))
1229 tokenExp = time.Now().Add(ec2TokenTTL)
1231 req, err := http.NewRequestWithContext(ctx, http.MethodGet, ec2MetadataBaseURL+"/latest/meta-data/spot/instance-action", nil)
1235 req.Header.Set("X-aws-ec2-metadata-token", token)
1236 resp, err := http.DefaultClient.Do(req)
1240 defer resp.Body.Close()
1241 metadata = ec2metadata{}
1242 switch resp.StatusCode {
1245 case http.StatusNotFound:
1246 // "If Amazon EC2 is not preparing to stop or
1247 // terminate the instance, or if you
1248 // terminated the instance yourself,
1249 // instance-action is not present in the
1250 // instance metadata and you receive an HTTP
1251 // 404 error when you try to retrieve it."
1253 case http.StatusUnauthorized:
1255 return fmt.Errorf("%s", resp.Status)
1257 return fmt.Errorf("%s", resp.Status)
1259 err = json.NewDecoder(resp.Body).Decode(&metadata)
1266 var lastmetadata ec2metadata
1267 for range time.NewTicker(spotInterruptionCheckInterval).C {
1270 runner.CrunchLog.Printf("Error checking spot interruptions: %s", err)
1273 runner.CrunchLog.Printf("Giving up on checking spot interruptions after too many consecutive failures")
1279 if metadata != lastmetadata {
1280 lastmetadata = metadata
1281 text := fmt.Sprintf("Cloud provider scheduled instance %s at %s", metadata.Action, metadata.Time.UTC().Format(time.RFC3339))
1282 runner.CrunchLog.Printf("%s", text)
1283 runner.updateRuntimeStatus(arvadosclient.Dict{
1284 "warning": "preemption notice",
1285 "warningDetail": text,
1286 "preemptionNotice": text,
1288 if proc, err := os.FindProcess(os.Getpid()); err == nil {
1289 // trigger updateLogs
1290 proc.Signal(syscall.SIGUSR1)
1296 func (runner *ContainerRunner) updateRuntimeStatus(status arvadosclient.Dict) {
1297 err := runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1298 "select": []string{"uuid"},
1299 "container": arvadosclient.Dict{
1300 "runtime_status": status,
1304 runner.CrunchLog.Printf("error updating container runtime_status: %s", err)
1308 // CaptureOutput saves data from the container's output directory if
1309 // needed, and updates the container output accordingly.
1310 func (runner *ContainerRunner) CaptureOutput(bindmounts map[string]bindmount) error {
1311 if runner.Container.RuntimeConstraints.API {
1312 // Output may have been set directly by the container, so
1313 // refresh the container record to check.
1314 err := runner.DispatcherArvClient.Get("containers", runner.Container.UUID,
1316 "select": []string{"output"},
1317 }, &runner.Container)
1321 if runner.Container.Output != "" {
1322 // Container output is already set.
1323 runner.OutputPDH = &runner.Container.Output
1328 txt, err := (&copier{
1329 client: runner.containerClient,
1330 keepClient: runner.ContainerKeepClient,
1331 hostOutputDir: runner.HostOutputDir,
1332 ctrOutputDir: runner.Container.OutputPath,
1333 globs: runner.Container.OutputGlob,
1334 bindmounts: bindmounts,
1335 mounts: runner.Container.Mounts,
1336 secretMounts: runner.SecretMounts,
1337 logger: runner.CrunchLog,
1342 if n := len(regexp.MustCompile(` [0-9a-f]+\+\S*\+R`).FindAllStringIndex(txt, -1)); n > 0 {
1343 runner.CrunchLog.Printf("Copying %d data blocks from remote input collections...", n)
1344 fs, err := (&arvados.Collection{ManifestText: txt}).FileSystem(runner.containerClient, runner.ContainerKeepClient)
1348 txt, err = fs.MarshalManifest(".")
1353 var resp arvados.Collection
1354 err = runner.ContainerArvClient.Create("collections", arvadosclient.Dict{
1355 "ensure_unique_name": true,
1356 "select": []string{"portable_data_hash"},
1357 "collection": arvadosclient.Dict{
1359 "name": "output for " + runner.Container.UUID,
1360 "manifest_text": txt,
1364 return fmt.Errorf("error creating output collection: %v", err)
1366 runner.OutputPDH = &resp.PortableDataHash
1370 func (runner *ContainerRunner) CleanupDirs() {
1371 if runner.ArvMount != nil {
1373 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1374 umount.Stdout = runner.CrunchLog
1375 umount.Stderr = runner.CrunchLog
1376 runner.CrunchLog.Printf("Running %v", umount.Args)
1377 umnterr := umount.Start()
1380 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1381 runner.ArvMount.Process.Kill()
1383 // If arv-mount --unmount gets stuck for any reason, we
1384 // don't want to wait for it forever. Do Wait() in a goroutine
1385 // so it doesn't block crunch-run.
1386 umountExit := make(chan error)
1388 mnterr := umount.Wait()
1390 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1392 umountExit <- mnterr
1395 for again := true; again; {
1401 case <-runner.ArvMountExit:
1403 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1404 runner.CrunchLog.Printf("Timed out waiting for unmount")
1406 umount.Process.Kill()
1408 runner.ArvMount.Process.Kill()
1412 runner.ArvMount = nil
1415 if runner.ArvMountPoint != "" {
1416 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1417 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1419 runner.ArvMountPoint = ""
1422 if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1423 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1427 // CommitLogs posts the collection containing the final container logs.
1428 func (runner *ContainerRunner) CommitLogs() error {
1430 // Hold cStateLock to prevent races on CrunchLog (e.g., stop()).
1431 runner.cStateLock.Lock()
1432 defer runner.cStateLock.Unlock()
1434 runner.CrunchLog.Print(runner.finalState)
1436 if runner.arvMountLog != nil {
1437 runner.arvMountLog.Close()
1440 // From now on just log to stderr, in case there are
1441 // any other further errors (such as failing to write
1442 // the log to Keep!) while shutting down
1443 runner.CrunchLog = newLogWriter(newTimestamper(newStringPrefixer(os.Stderr, runner.Container.UUID+" ")))
1446 if runner.keepstoreLogger != nil {
1447 // Flush any buffered logs from our local keepstore
1448 // process. Discard anything logged after this point
1449 // -- it won't end up in the log collection, so
1450 // there's no point writing it to the collectionfs.
1451 runner.keepstoreLogbuf.SetWriter(io.Discard)
1452 runner.keepstoreLogger.Close()
1453 runner.keepstoreLogger = nil
1456 if runner.LogsPDH != nil {
1457 // If we have already assigned something to LogsPDH,
1458 // we must be closing the re-opened log, which won't
1459 // end up getting attached to the container record and
1460 // therefore doesn't need to be saved as a collection
1461 // -- it exists only to send logs to other channels.
1465 saved, err := runner.saveLogCollection(true)
1467 return fmt.Errorf("error saving log collection: %s", err)
1469 runner.logMtx.Lock()
1470 defer runner.logMtx.Unlock()
1471 runner.LogsPDH = &saved.PortableDataHash
1475 // Create/update the log collection. Return value has UUID and
1476 // PortableDataHash fields populated, but others may be blank.
1477 func (runner *ContainerRunner) saveLogCollection(final bool) (response arvados.Collection, err error) {
1478 runner.logMtx.Lock()
1479 defer runner.logMtx.Unlock()
1480 if runner.LogsPDH != nil {
1481 // Already finalized.
1484 updates := arvadosclient.Dict{
1485 "name": "logs for " + runner.Container.UUID,
1487 mt, err1 := runner.LogCollection.MarshalManifest(".")
1489 // Only send updated manifest text if there was no
1491 updates["manifest_text"] = mt
1494 // Even if flushing the manifest had an error, we still want
1495 // to update the log record, if possible, to push the trash_at
1496 // and delete_at times into the future. Details on bug
1499 updates["is_trashed"] = true
1501 // We set trash_at so this collection gets
1502 // automatically cleaned up eventually. It used to be
1503 // 12 hours but we had a situation where the API
1504 // server was down over a weekend but the containers
1505 // kept running such that the log collection got
1506 // trashed, so now we make it 2 weeks. refs #20378
1507 exp := time.Now().Add(time.Duration(24*14) * time.Hour)
1508 updates["trash_at"] = exp
1509 updates["delete_at"] = exp
1511 reqBody := arvadosclient.Dict{
1512 "select": []string{"uuid", "portable_data_hash"},
1513 "collection": updates,
1516 if runner.logUUID == "" {
1517 reqBody["ensure_unique_name"] = true
1518 err2 = runner.DispatcherArvClient.Create("collections", reqBody, &response)
1520 err2 = runner.DispatcherArvClient.Update("collections", runner.logUUID, reqBody, &response)
1523 runner.logUUID = response.UUID
1526 if err1 != nil || err2 != nil {
1527 err = fmt.Errorf("error recording logs: %q, %q", err1, err2)
1532 // UpdateContainerRunning updates the container state to "Running"
1533 func (runner *ContainerRunner) UpdateContainerRunning(logId string) error {
1534 runner.cStateLock.Lock()
1535 defer runner.cStateLock.Unlock()
1536 if runner.cCancelled {
1539 updates := arvadosclient.Dict{
1540 "gateway_address": runner.gateway.Address,
1544 updates["log"] = logId
1546 return runner.DispatcherArvClient.Update(
1548 runner.Container.UUID,
1550 "select": []string{"uuid"},
1551 "container": updates,
1557 // ContainerToken returns the api_token the container (and any
1558 // arv-mount processes) are allowed to use.
1559 func (runner *ContainerRunner) ContainerToken() (string, error) {
1560 if runner.token != "" {
1561 return runner.token, nil
1564 var auth arvados.APIClientAuthorization
1565 err := runner.DispatcherArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1569 runner.token = fmt.Sprintf("v2/%s/%s/%s", auth.UUID, auth.APIToken, runner.Container.UUID)
1570 return runner.token, nil
1573 // UpdateContainerFinal updates the container record state on API
1574 // server to "Complete" or "Cancelled"
1575 func (runner *ContainerRunner) UpdateContainerFinal() error {
1576 update := arvadosclient.Dict{}
1577 update["state"] = runner.finalState
1578 if runner.LogsPDH != nil {
1579 update["log"] = *runner.LogsPDH
1581 if runner.ExitCode != nil {
1582 update["exit_code"] = *runner.ExitCode
1584 update["exit_code"] = nil
1586 if runner.finalState == "Complete" && runner.OutputPDH != nil {
1587 update["output"] = *runner.OutputPDH
1589 update["cost"] = runner.calculateCost(time.Now())
1590 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1591 "select": []string{"uuid"},
1592 "container": update,
1596 // IsCancelled returns the value of Cancelled, with goroutine safety.
1597 func (runner *ContainerRunner) IsCancelled() bool {
1598 runner.cStateLock.Lock()
1599 defer runner.cStateLock.Unlock()
1600 return runner.cCancelled
1603 func (runner *ContainerRunner) openLogFile(name string) (io.WriteCloser, error) {
1604 return runner.LogCollection.OpenFile(name+".txt", os.O_CREATE|os.O_WRONLY, 0666)
1607 // Run the full container lifecycle.
1608 func (runner *ContainerRunner) Run() (err error) {
1609 runner.CrunchLog.Printf("crunch-run %s started", cmd.Version.String())
1610 runner.CrunchLog.Printf("%s", currentUserAndGroups())
1611 v, _ := exec.Command("arv-mount", "--version").CombinedOutput()
1612 runner.CrunchLog.Printf("Using FUSE mount: %s", v)
1613 runner.CrunchLog.Printf("Using container runtime: %s", runner.executor.Runtime())
1614 runner.CrunchLog.Printf("Executing container: %s", runner.Container.UUID)
1615 runner.costStartTime = time.Now()
1617 hostname, hosterr := os.Hostname()
1619 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1621 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1624 sigusr2 := make(chan os.Signal, 1)
1625 signal.Notify(sigusr2, syscall.SIGUSR2)
1626 defer signal.Stop(sigusr2)
1628 go runner.handleSIGUSR2(sigusr2)
1630 runner.finalState = "Queued"
1633 runner.CleanupDirs()
1634 runner.CrunchLog.Printf("crunch-run finished")
1637 err = runner.fetchContainerRecord()
1641 if runner.Container.State != "Locked" {
1642 return fmt.Errorf("dispatch error detected: container %q has state %q", runner.Container.UUID, runner.Container.State)
1645 var bindmounts map[string]bindmount
1647 // checkErr prints e (unless it's nil) and sets err to
1648 // e (unless err is already non-nil). Thus, if err
1649 // hasn't already been assigned when Run() returns,
1650 // this cleanup func will cause Run() to return the
1651 // first non-nil error that is passed to checkErr().
1652 checkErr := func(errorIn string, e error) {
1656 runner.CrunchLog.Printf("error in %s: %v", errorIn, e)
1660 if runner.finalState == "Complete" {
1661 // There was an error in the finalization.
1662 runner.finalState = "Cancelled"
1666 // Log the error encountered in Run(), if any
1667 checkErr("Run", err)
1669 if runner.finalState == "Queued" {
1670 runner.UpdateContainerFinal()
1674 if runner.IsCancelled() {
1675 runner.finalState = "Cancelled"
1676 // but don't return yet -- we still want to
1677 // capture partial output and write logs
1680 if bindmounts != nil {
1681 checkErr("CaptureOutput", runner.CaptureOutput(bindmounts))
1683 checkErr("stopHoststat", runner.stopHoststat())
1684 checkErr("CommitLogs", runner.CommitLogs())
1685 runner.CleanupDirs()
1686 checkErr("UpdateContainerFinal", runner.UpdateContainerFinal())
1689 runner.setupSignals()
1690 err = runner.startHoststat()
1694 if runner.keepstore != nil {
1695 runner.hoststatReporter.ReportPID("keepstore", runner.keepstore.Process.Pid)
1698 // set up FUSE mount and binds
1699 bindmounts, err = runner.SetupMounts()
1701 runner.finalState = "Cancelled"
1702 err = fmt.Errorf("While setting up mounts: %v", err)
1706 // check for and/or load image
1707 imageID, err := runner.LoadImage()
1709 if !runner.checkBrokenNode(err) {
1710 // Failed to load image but not due to a "broken node"
1711 // condition, probably user error.
1712 runner.finalState = "Cancelled"
1714 err = fmt.Errorf("While loading container image: %v", err)
1718 err = runner.CreateContainer(imageID, bindmounts)
1722 err = runner.LogHostInfo()
1726 err = runner.LogNodeRecord()
1730 err = runner.LogContainerRecord()
1735 if runner.IsCancelled() {
1739 logCollection, err := runner.saveLogCollection(false)
1742 logId = logCollection.PortableDataHash
1744 runner.CrunchLog.Printf("Error committing initial log collection: %v", err)
1746 err = runner.UpdateContainerRunning(logId)
1750 runner.finalState = "Cancelled"
1752 err = runner.startCrunchstat()
1757 err = runner.StartContainer()
1759 runner.checkBrokenNode(err)
1763 err = runner.WaitFinish()
1764 if err == nil && !runner.IsCancelled() {
1765 runner.finalState = "Complete"
1770 // Fetch the current container record (uuid = runner.Container.UUID)
1771 // into runner.Container.
1772 func (runner *ContainerRunner) fetchContainerRecord() error {
1773 reader, err := runner.DispatcherArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1775 return fmt.Errorf("error fetching container record: %v", err)
1777 defer reader.Close()
1779 dec := json.NewDecoder(reader)
1781 err = dec.Decode(&runner.Container)
1783 return fmt.Errorf("error decoding container record: %v", err)
1787 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
1790 containerToken, err := runner.ContainerToken()
1792 return fmt.Errorf("error getting container token: %v", err)
1795 runner.ContainerArvClient, runner.ContainerKeepClient,
1796 runner.containerClient, err = runner.MkArvClient(containerToken)
1798 return fmt.Errorf("error creating container API client: %v", err)
1801 runner.ContainerKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1802 runner.DispatcherKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1804 err = runner.ContainerArvClient.Call("GET", "containers", runner.Container.UUID, "secret_mounts", nil, &sm)
1806 if apierr, ok := err.(arvadosclient.APIServerError); !ok || apierr.HttpStatusCode != 404 {
1807 return fmt.Errorf("error fetching secret_mounts: %v", err)
1809 // ok && apierr.HttpStatusCode == 404, which means
1810 // secret_mounts isn't supported by this API server.
1812 runner.SecretMounts = sm.SecretMounts
1817 // NewContainerRunner creates a new container runner.
1818 func NewContainerRunner(dispatcherClient *arvados.Client,
1819 dispatcherArvClient IArvadosClient,
1820 dispatcherKeepClient IKeepClient,
1821 containerUUID string) (*ContainerRunner, error) {
1823 cr := &ContainerRunner{
1824 dispatcherClient: dispatcherClient,
1825 DispatcherArvClient: dispatcherArvClient,
1826 DispatcherKeepClient: dispatcherKeepClient,
1828 cr.RunArvMount = cr.ArvMountCmd
1829 cr.MkTempDir = ioutil.TempDir
1830 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1831 cl, err := arvadosclient.MakeArvadosClient()
1833 return nil, nil, nil, err
1836 kc, err := keepclient.MakeKeepClient(cl)
1838 return nil, nil, nil, err
1840 c2 := arvados.NewClientFromEnv()
1841 c2.AuthToken = token
1842 return cl, kc, c2, nil
1845 cr.LogCollection, err = (&arvados.Collection{}).FileSystem(cr.dispatcherClient, cr.DispatcherKeepClient)
1849 cr.Container.UUID = containerUUID
1850 f, err := cr.openLogFile("crunch-run")
1854 cr.CrunchLog = newLogWriter(newTimestamper(io.MultiWriter(f, newStringPrefixer(os.Stderr, cr.Container.UUID+" "))))
1861 func (command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
1862 log := log.New(stderr, "", 0)
1863 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
1864 statInterval := flags.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1865 flags.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree (obsolete, ignored)")
1866 flags.String("cgroup-parent", "docker", "name of container's parent cgroup (obsolete, ignored)")
1867 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")
1868 caCertsPath := flags.String("ca-certs", "", "Path to TLS root certificates")
1869 detach := flags.Bool("detach", false, "Detach from parent process and run in the background")
1870 stdinConfig := flags.Bool("stdin-config", false, "Load config and environment variables from JSON message on stdin")
1871 configFile := flags.String("config", arvados.DefaultConfigFile, "filename of cluster config file to try loading if -stdin-config=false (default is $ARVADOS_CONFIG)")
1872 sleep := flags.Duration("sleep", 0, "Delay before starting (testing use only)")
1873 kill := flags.Int("kill", -1, "Send signal to an existing crunch-run process for given UUID")
1874 list := flags.Bool("list", false, "List UUIDs of existing crunch-run processes (and notify them to use price data passed on stdin)")
1875 enableMemoryLimit := flags.Bool("enable-memory-limit", true, "tell container runtime to limit container's memory usage")
1876 enableNetwork := flags.String("container-enable-networking", "default", "enable networking \"always\" (for all containers) or \"default\" (for containers that request it)")
1877 networkMode := flags.String("container-network-mode", "default", `Docker network mode for container (use any argument valid for docker --net)`)
1878 memprofile := flags.String("memprofile", "", "write memory profile to `file` after running container")
1879 runtimeEngine := flags.String("runtime-engine", "docker", "container runtime: docker or singularity")
1880 brokenNodeHook := flags.String("broken-node-hook", "", "script to run if node is detected to be broken (for example, Docker daemon is not running)")
1881 flags.Duration("check-containerd", 0, "Ignored. Exists for compatibility with older versions.")
1882 version := flags.Bool("version", false, "Write version information to stdout and exit 0.")
1884 ignoreDetachFlag := false
1885 if len(args) > 0 && args[0] == "-no-detach" {
1886 // This process was invoked by a parent process, which
1887 // has passed along its own arguments, including
1888 // -detach, after the leading -no-detach flag. Strip
1889 // the leading -no-detach flag (it's not recognized by
1890 // flags.Parse()) and ignore the -detach flag that
1893 ignoreDetachFlag = true
1896 if ok, code := cmd.ParseFlags(flags, prog, args, "container-uuid", stderr); !ok {
1898 } else if *version {
1899 fmt.Fprintln(stdout, prog, cmd.Version.String())
1901 } else if !*list && flags.NArg() != 1 {
1902 fmt.Fprintf(stderr, "missing required argument: container-uuid (try -help)\n")
1906 containerUUID := flags.Arg(0)
1909 case *detach && !ignoreDetachFlag:
1910 return Detach(containerUUID, prog, args, stdin, stdout, stderr)
1912 return KillProcess(containerUUID, syscall.Signal(*kill), stdout, stderr)
1914 return ListProcesses(stdin, stdout, stderr)
1917 if len(containerUUID) != 27 {
1918 log.Printf("usage: %s [options] UUID", prog)
1922 var keepstoreLogbuf bufThenWrite
1925 err := json.NewDecoder(stdin).Decode(&conf)
1927 log.Printf("decode stdin: %s", err)
1930 for k, v := range conf.Env {
1931 err = os.Setenv(k, v)
1933 log.Printf("setenv(%q): %s", k, err)
1937 if conf.Cluster != nil {
1938 // ClusterID is missing from the JSON
1939 // representation, but we need it to generate
1940 // a valid config file for keepstore, so we
1941 // fill it using the container UUID prefix.
1942 conf.Cluster.ClusterID = containerUUID[:5]
1945 conf = hpcConfData(containerUUID, *configFile, io.MultiWriter(&keepstoreLogbuf, stderr))
1948 log.Printf("crunch-run %s started", cmd.Version.String())
1951 if *caCertsPath != "" {
1952 os.Setenv("SSL_CERT_FILE", *caCertsPath)
1955 keepstore, err := startLocalKeepstore(conf, io.MultiWriter(&keepstoreLogbuf, stderr))
1960 if keepstore != nil {
1961 defer keepstore.Process.Kill()
1964 api, err := arvadosclient.MakeArvadosClient()
1966 log.Printf("%s: %v", containerUUID, err)
1969 // arvadosclient now interprets Retries=10 to mean
1970 // Timeout=10m, retrying with exponential backoff + jitter.
1973 kc, err := keepclient.MakeKeepClient(api)
1975 log.Printf("%s: %v", containerUUID, err)
1980 cr, err := NewContainerRunner(arvados.NewClientFromEnv(), api, kc, containerUUID)
1986 cr.keepstore = keepstore
1987 if keepstore == nil {
1988 // Log explanation (if any) for why we're not running
1989 // a local keepstore.
1990 var buf bytes.Buffer
1991 keepstoreLogbuf.SetWriter(&buf)
1993 cr.CrunchLog.Printf("%s", strings.TrimSpace(buf.String()))
1995 } else if logWhat := conf.Cluster.Containers.LocalKeepLogsToContainerLog; logWhat == "none" {
1996 cr.CrunchLog.Printf("using local keepstore process (pid %d) at %s", keepstore.Process.Pid, os.Getenv("ARVADOS_KEEP_SERVICES"))
1997 keepstoreLogbuf.SetWriter(io.Discard)
1999 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"))
2000 cr.keepstoreLogger, err = cr.openLogFile("keepstore")
2006 var writer io.WriteCloser = cr.keepstoreLogger
2007 if logWhat == "errors" {
2008 writer = &filterKeepstoreErrorsOnly{WriteCloser: writer}
2009 } else if logWhat != "all" {
2010 // should have been caught earlier by
2011 // dispatcher's config loader
2012 log.Printf("invalid value for Containers.LocalKeepLogsToContainerLog: %q", logWhat)
2015 err = keepstoreLogbuf.SetWriter(writer)
2020 cr.keepstoreLogbuf = &keepstoreLogbuf
2023 switch *runtimeEngine {
2025 cr.executor, err = newDockerExecutor(containerUUID, cr.CrunchLog.Printf, cr.containerWatchdogInterval)
2027 cr.executor, err = newSingularityExecutor(cr.CrunchLog.Printf)
2029 cr.CrunchLog.Printf("%s: unsupported RuntimeEngine %q", containerUUID, *runtimeEngine)
2033 cr.CrunchLog.Printf("%s: %v", containerUUID, err)
2034 cr.checkBrokenNode(err)
2037 defer cr.executor.Close()
2039 cr.brokenNodeHook = *brokenNodeHook
2041 gwAuthSecret := os.Getenv("GatewayAuthSecret")
2042 os.Unsetenv("GatewayAuthSecret")
2043 if gwAuthSecret == "" {
2044 // not safe to run a gateway service without an auth
2046 cr.CrunchLog.Printf("Not starting a gateway server (GatewayAuthSecret was not provided by dispatcher)")
2048 gwListen := os.Getenv("GatewayAddress")
2049 cr.gateway = Gateway{
2051 AuthSecret: gwAuthSecret,
2052 ContainerUUID: containerUUID,
2053 Target: cr.executor,
2055 LogCollection: cr.LogCollection,
2058 // Direct connection won't work, so we use the
2059 // gateway_address field to indicate the
2060 // internalURL of the controller process that
2061 // has the current tunnel connection.
2062 cr.gateway.ArvadosClient = cr.dispatcherClient
2063 cr.gateway.UpdateTunnelURL = func(url string) {
2064 cr.gateway.Address = "tunnel " + url
2065 cr.DispatcherArvClient.Update("containers", containerUUID,
2067 "select": []string{"uuid"},
2068 "container": arvadosclient.Dict{"gateway_address": cr.gateway.Address},
2072 err = cr.gateway.Start()
2074 log.Printf("error starting gateway server: %s", err)
2079 parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerUUID+".")
2081 log.Printf("%s: %v", containerUUID, tmperr)
2085 cr.parentTemp = parentTemp
2086 cr.statInterval = *statInterval
2087 cr.enableMemoryLimit = *enableMemoryLimit
2088 cr.enableNetwork = *enableNetwork
2089 cr.networkMode = *networkMode
2090 if *cgroupParentSubsystem != "" {
2091 p, err := findCgroup(os.DirFS("/"), *cgroupParentSubsystem)
2093 log.Printf("fatal: cgroup parent subsystem: %s", err)
2096 cr.setCgroupParent = p
2099 if conf.EC2SpotCheck {
2100 go cr.checkSpotInterruptionNotices()
2105 if *memprofile != "" {
2106 f, err := os.Create(*memprofile)
2108 log.Printf("could not create memory profile: %s", err)
2110 runtime.GC() // get up-to-date statistics
2111 if err := pprof.WriteHeapProfile(f); err != nil {
2112 log.Printf("could not write memory profile: %s", err)
2114 closeerr := f.Close()
2115 if closeerr != nil {
2116 log.Printf("closing memprofile file: %s", err)
2121 log.Printf("%s: %v", containerUUID, runerr)
2127 // Try to load ConfigData in hpc (slurm/lsf) environment. This means
2128 // loading the cluster config from the specified file and (if that
2129 // works) getting the runtime_constraints container field from
2130 // controller to determine # VCPUs so we can calculate KeepBuffers.
2131 func hpcConfData(uuid string, configFile string, stderr io.Writer) ConfigData {
2133 conf.Cluster = loadClusterConfigFile(configFile, stderr)
2134 if conf.Cluster == nil {
2135 // skip loading the container record -- we won't be
2136 // able to start local keepstore anyway.
2139 arv, err := arvadosclient.MakeArvadosClient()
2141 fmt.Fprintf(stderr, "error setting up arvadosclient: %s\n", err)
2144 // arvadosclient now interprets Retries=10 to mean
2145 // Timeout=10m, retrying with exponential backoff + jitter.
2147 var ctr arvados.Container
2148 err = arv.Call("GET", "containers", uuid, "", arvadosclient.Dict{"select": []string{"runtime_constraints"}}, &ctr)
2150 fmt.Fprintf(stderr, "error getting container record: %s\n", err)
2153 if ctr.RuntimeConstraints.VCPUs > 0 {
2154 conf.KeepBuffers = ctr.RuntimeConstraints.VCPUs * conf.Cluster.Containers.LocalKeepBlobBuffersPerVCPU
2159 // Load cluster config file from given path. If an error occurs, log
2160 // the error to stderr and return nil.
2161 func loadClusterConfigFile(path string, stderr io.Writer) *arvados.Cluster {
2162 ldr := config.NewLoader(&bytes.Buffer{}, ctxlog.New(stderr, "plain", "info"))
2164 cfg, err := ldr.Load()
2166 fmt.Fprintf(stderr, "could not load config file %s: %s\n", path, err)
2169 cluster, err := cfg.GetCluster("")
2171 fmt.Fprintf(stderr, "could not use config file %s: %s\n", path, err)
2174 fmt.Fprintf(stderr, "loaded config file %s\n", path)
2178 func startLocalKeepstore(configData ConfigData, logbuf io.Writer) (*exec.Cmd, error) {
2179 if configData.KeepBuffers < 1 {
2180 fmt.Fprintf(logbuf, "not starting a local keepstore process because KeepBuffers=%v in config\n", configData.KeepBuffers)
2183 if configData.Cluster == nil {
2184 fmt.Fprint(logbuf, "not starting a local keepstore process because cluster config file was not loaded\n")
2187 for uuid, vol := range configData.Cluster.Volumes {
2188 if len(vol.AccessViaHosts) > 0 {
2189 fmt.Fprintf(logbuf, "not starting a local keepstore process because a volume (%s) uses AccessViaHosts\n", uuid)
2192 if !vol.ReadOnly && vol.Replication < configData.Cluster.Collections.DefaultReplication {
2193 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)
2198 // Rather than have an alternate way to tell keepstore how
2199 // many buffers to use, etc., when starting it this way, we
2200 // just modify the cluster configuration that we feed it on
2202 ccfg := *configData.Cluster
2203 ccfg.API.MaxKeepBlobBuffers = configData.KeepBuffers
2204 ccfg.Collections.BlobTrash = false
2205 ccfg.Collections.BlobTrashConcurrency = 0
2206 ccfg.Collections.BlobDeleteConcurrency = 0
2208 localaddr := localKeepstoreAddr()
2209 ln, err := net.Listen("tcp", net.JoinHostPort(localaddr, "0"))
2213 _, port, err := net.SplitHostPort(ln.Addr().String())
2219 url := "http://" + net.JoinHostPort(localaddr, port)
2221 fmt.Fprintf(logbuf, "starting keepstore on %s\n", url)
2223 var confJSON bytes.Buffer
2224 err = json.NewEncoder(&confJSON).Encode(arvados.Config{
2225 Clusters: map[string]arvados.Cluster{
2226 ccfg.ClusterID: ccfg,
2232 cmd := exec.Command("/proc/self/exe", "keepstore", "-config=-")
2233 if target, err := os.Readlink(cmd.Path); err == nil && strings.HasSuffix(target, ".test") {
2234 // If we're a 'go test' process, running
2235 // /proc/self/exe would start the test suite in a
2236 // child process, which is not what we want.
2237 cmd.Path, _ = exec.LookPath("go")
2238 cmd.Args = append([]string{"go", "run", "../../cmd/arvados-server"}, cmd.Args[1:]...)
2239 cmd.Env = os.Environ()
2241 cmd.Stdin = &confJSON
2244 cmd.Env = append(cmd.Env,
2246 "ARVADOS_SERVICE_INTERNAL_URL="+url)
2249 return nil, fmt.Errorf("error starting keepstore process: %w", err)
2256 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*10))
2258 poll := time.NewTicker(time.Second / 10)
2260 client := http.Client{}
2262 testReq, err := http.NewRequestWithContext(ctx, "GET", url+"/_health/ping", nil)
2263 testReq.Header.Set("Authorization", "Bearer "+configData.Cluster.ManagementToken)
2267 resp, err := client.Do(testReq)
2270 if resp.StatusCode == http.StatusOK {
2275 return nil, fmt.Errorf("keepstore child process exited")
2277 if ctx.Err() != nil {
2278 return nil, fmt.Errorf("timed out waiting for new keepstore process to report healthy")
2281 os.Setenv("ARVADOS_KEEP_SERVICES", url)
2285 // return current uid, gid, groups in a format suitable for logging:
2286 // "crunch-run process has uid=1234(arvados) gid=1234(arvados)
2287 // groups=1234(arvados),114(fuse)"
2288 func currentUserAndGroups() string {
2289 u, err := user.Current()
2291 return fmt.Sprintf("error getting current user ID: %s", err)
2293 s := fmt.Sprintf("crunch-run process has uid=%s(%s) gid=%s", u.Uid, u.Username, u.Gid)
2294 if g, err := user.LookupGroupId(u.Gid); err == nil {
2295 s += fmt.Sprintf("(%s)", g.Name)
2298 if gids, err := u.GroupIds(); err == nil {
2299 for i, gid := range gids {
2304 if g, err := user.LookupGroupId(gid); err == nil {
2305 s += fmt.Sprintf("(%s)", g.Name)
2312 // Return a suitable local interface address for a local keepstore
2313 // service. Currently this is the numerically lowest non-loopback ipv4
2314 // address assigned to a local interface that is not in any of the
2315 // link-local/vpn/loopback ranges 169.254/16, 100.64/10, or 127/8.
2316 func localKeepstoreAddr() string {
2318 // Ignore error (proceed with zero IPs)
2319 addrs, _ := processIPs(os.Getpid())
2320 for addr := range addrs {
2321 ip := net.ParseIP(addr)
2326 if ip.Mask(net.CIDRMask(8, 32)).Equal(net.IPv4(127, 0, 0, 0)) ||
2327 ip.Mask(net.CIDRMask(10, 32)).Equal(net.IPv4(100, 64, 0, 0)) ||
2328 ip.Mask(net.CIDRMask(16, 32)).Equal(net.IPv4(169, 254, 0, 0)) {
2332 ips = append(ips, ip)
2337 sort.Slice(ips, func(ii, jj int) bool {
2338 i, j := ips[ii], ips[jj]
2339 if len(i) != len(j) {
2340 return len(i) < len(j)
2349 return ips[0].String()
2352 func (cr *ContainerRunner) loadPrices() {
2353 buf, err := os.ReadFile(filepath.Join(lockdir, pricesfile))
2355 if !os.IsNotExist(err) {
2356 cr.CrunchLog.Printf("loadPrices: read: %s", err)
2360 var prices []cloud.InstancePrice
2361 err = json.Unmarshal(buf, &prices)
2363 cr.CrunchLog.Printf("loadPrices: decode: %s", err)
2366 cr.pricesLock.Lock()
2367 defer cr.pricesLock.Unlock()
2368 var lastKnown time.Time
2369 if len(cr.prices) > 0 {
2370 lastKnown = cr.prices[0].StartTime
2372 cr.prices = cloud.NormalizePriceHistory(append(prices, cr.prices...))
2373 for i := len(cr.prices) - 1; i >= 0; i-- {
2374 price := cr.prices[i]
2375 if price.StartTime.After(lastKnown) {
2376 cr.CrunchLog.Printf("Instance price changed to %#.3g at %s", price.Price, price.StartTime.UTC())
2381 func (cr *ContainerRunner) calculateCost(now time.Time) float64 {
2382 cr.pricesLock.Lock()
2383 defer cr.pricesLock.Unlock()
2385 // First, make a "prices" slice with the real data as far back
2386 // as it goes, and (if needed) a "since the beginning of time"
2387 // placeholder containing a reasonable guess about what the
2388 // price was between cr.costStartTime and the earliest real
2391 if len(prices) == 0 {
2392 // use price info in InstanceType record initially
2393 // provided by cloud dispatcher
2395 var it arvados.InstanceType
2396 if j := os.Getenv("InstanceType"); j != "" && json.Unmarshal([]byte(j), &it) == nil && it.Price > 0 {
2399 prices = []cloud.InstancePrice{{Price: p}}
2400 } else if prices[len(prices)-1].StartTime.After(cr.costStartTime) {
2401 // guess earlier pricing was the same as the earliest
2402 // price we know about
2403 filler := prices[len(prices)-1]
2404 filler.StartTime = time.Time{}
2405 prices = append(prices, filler)
2408 // Now that our history of price changes goes back at least as
2409 // far as cr.costStartTime, add up the costs for each
2413 for _, ip := range prices {
2414 spanStart := ip.StartTime
2415 if spanStart.After(now) {
2416 // pricing information from the future -- not
2417 // expected from AWS, but possible in
2418 // principle, and exercised by tests.
2422 if spanStart.Before(cr.costStartTime) {
2423 spanStart = cr.costStartTime
2426 cost += ip.Price * spanEnd.Sub(spanStart).Seconds() / 3600
2436 func (runner *ContainerRunner) handleSIGUSR2(sigchan chan os.Signal) {
2439 update := arvadosclient.Dict{
2440 "select": []string{"uuid"},
2441 "container": arvadosclient.Dict{
2442 "cost": runner.calculateCost(time.Now()),
2445 runner.DispatcherArvClient.Update("containers", runner.Container.UUID, update, nil)