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 Command = command{}
51 // ConfigData contains environment variables and (when needed) cluster
52 // configuration, passed from dispatchcloud to crunch-run on stdin.
53 type ConfigData struct {
57 Cluster *arvados.Cluster
60 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
61 type IArvadosClient interface {
62 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
63 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
64 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
65 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
66 CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
67 Discovery(key string) (interface{}, error)
70 // ErrCancelled is the error returned when the container is cancelled.
71 var ErrCancelled = errors.New("Cancelled")
73 // IKeepClient is the minimal Keep API methods used by crunch-run.
74 type IKeepClient interface {
75 BlockWrite(context.Context, arvados.BlockWriteOptions) (arvados.BlockWriteResponse, error)
76 ReadAt(locator string, p []byte, off int) (int, error)
77 ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error)
78 LocalLocator(locator string) (string, error)
80 SetStorageClasses(sc []string)
83 // NewLogWriter is a factory function to create a new log writer.
84 type NewLogWriter func(name string) (io.WriteCloser, error)
86 type RunArvMount func(cmdline []string, tok string) (*exec.Cmd, error)
88 type MkTempDir func(string, string) (string, error)
90 type PsProcess interface {
91 CmdlineSlice() ([]string, error)
94 // ContainerRunner is the main stateful struct used for a single execution of a
96 type ContainerRunner struct {
97 executor containerExecutor
98 executorStdin io.Closer
99 executorStdout io.Closer
100 executorStderr io.Closer
102 // Dispatcher client is initialized with the Dispatcher token.
103 // This is a privileged token used to manage container status
106 // We have both dispatcherClient and DispatcherArvClient
107 // because there are two different incompatible Arvados Go
108 // SDKs and we have to use both (hopefully this gets fixed in
110 dispatcherClient *arvados.Client
111 DispatcherArvClient IArvadosClient
112 DispatcherKeepClient IKeepClient
114 // Container client is initialized with the Container token
115 // This token controls the permissions of the container, and
116 // must be used for operations such as reading collections.
118 // Same comment as above applies to
119 // containerClient/ContainerArvClient.
120 containerClient *arvados.Client
121 ContainerArvClient IArvadosClient
122 ContainerKeepClient IKeepClient
124 Container arvados.Container
127 NewLogWriter NewLogWriter
128 CrunchLog *ThrottledLogger
131 LogCollection arvados.CollectionFileSystem
133 RunArvMount RunArvMount
138 Volumes map[string]struct{}
140 SigChan chan os.Signal
141 ArvMountExit chan error
142 SecretMounts map[string]arvados.Mount
143 MkArvClient func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error)
146 costStartTime time.Time
149 keepstoreLogger io.WriteCloser
150 keepstoreLogbuf *bufThenWrite
151 statLogger io.WriteCloser
152 statReporter *crunchstat.Reporter
153 hoststatLogger io.WriteCloser
154 hoststatReporter *crunchstat.Reporter
155 statInterval time.Duration
156 // What we tell docker to use as the container's cgroup
158 setCgroupParent string
159 // Fake root dir where crunchstat.Reporter should read OS
160 // files, for testing.
161 crunchstatFakeFS fs.FS
163 cStateLock sync.Mutex
164 cCancelled bool // StopContainer() invoked
166 enableMemoryLimit bool
167 enableNetwork string // one of "default" or "always"
168 networkMode string // "none", "host", or "" -- passed through to executor
169 brokenNodeHook string // script to run if node appears to be broken
170 arvMountLog *ThrottledLogger
172 containerWatchdogInterval time.Duration
176 prices []cloud.InstancePrice
177 pricesLock sync.Mutex
180 // setupSignals sets up signal handling to gracefully terminate the
181 // underlying container and update state when receiving a TERM, INT or
183 func (runner *ContainerRunner) setupSignals() {
184 runner.SigChan = make(chan os.Signal, 1)
185 signal.Notify(runner.SigChan, syscall.SIGTERM)
186 signal.Notify(runner.SigChan, syscall.SIGINT)
187 signal.Notify(runner.SigChan, syscall.SIGQUIT)
189 go func(sig chan os.Signal) {
196 // stop the underlying container.
197 func (runner *ContainerRunner) stop(sig os.Signal) {
198 runner.cStateLock.Lock()
199 defer runner.cStateLock.Unlock()
201 runner.CrunchLog.Printf("caught signal: %v", sig)
203 runner.cCancelled = true
204 runner.CrunchLog.Printf("stopping container")
205 err := runner.executor.Stop()
207 runner.CrunchLog.Printf("error stopping container: %s", err)
211 var errorBlacklist = []string{
212 "(?ms).*[Cc]annot connect to the Docker daemon.*",
213 "(?ms).*oci runtime error.*starting container process.*container init.*mounting.*to rootfs.*no such file or directory.*",
214 "(?ms).*grpc: the connection is unavailable.*",
217 func (runner *ContainerRunner) runBrokenNodeHook() {
218 if runner.brokenNodeHook == "" {
219 path := filepath.Join(lockdir, brokenfile)
220 runner.CrunchLog.Printf("Writing %s to mark node as broken", path)
221 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0700)
223 runner.CrunchLog.Printf("Error writing %s: %s", path, err)
228 runner.CrunchLog.Printf("Running broken node hook %q", runner.brokenNodeHook)
230 c := exec.Command(runner.brokenNodeHook)
231 c.Stdout = runner.CrunchLog
232 c.Stderr = runner.CrunchLog
235 runner.CrunchLog.Printf("Error running broken node hook: %v", err)
240 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
241 for _, d := range errorBlacklist {
242 if m, e := regexp.MatchString(d, goterr.Error()); m && e == nil {
243 runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
244 runner.runBrokenNodeHook()
251 // LoadImage determines the docker image id from the container record and
252 // checks if it is available in the local Docker image store. If not, it loads
253 // the image from Keep.
254 func (runner *ContainerRunner) LoadImage() (string, error) {
255 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
257 d, err := os.Open(runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage)
262 allfiles, err := d.Readdirnames(-1)
266 var tarfiles []string
267 for _, fnm := range allfiles {
268 if strings.HasSuffix(fnm, ".tar") {
269 tarfiles = append(tarfiles, fnm)
272 if len(tarfiles) == 0 {
273 return "", fmt.Errorf("image collection does not include a .tar image file")
275 if len(tarfiles) > 1 {
276 return "", fmt.Errorf("cannot choose from multiple tar files in image collection: %v", tarfiles)
278 imageID := tarfiles[0][:len(tarfiles[0])-4]
279 imageTarballPath := runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage + "/" + imageID + ".tar"
280 runner.CrunchLog.Printf("Using Docker image id %q", imageID)
282 runner.CrunchLog.Print("Loading Docker image from keep")
283 err = runner.executor.LoadImage(imageID, imageTarballPath, runner.Container, runner.ArvMountPoint,
284 runner.containerClient)
292 func (runner *ContainerRunner) ArvMountCmd(cmdline []string, token string) (c *exec.Cmd, err error) {
293 c = exec.Command(cmdline[0], cmdline[1:]...)
295 // Copy our environment, but override ARVADOS_API_TOKEN with
296 // the container auth token.
298 for _, s := range os.Environ() {
299 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
300 c.Env = append(c.Env, s)
303 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
305 w, err := runner.NewLogWriter("arv-mount")
309 runner.arvMountLog = NewThrottledLogger(w)
310 scanner := logScanner{
313 "Block not found error",
314 "Unhandled exception during FUSE operation",
316 ReportFunc: func(pattern, text string) {
317 runner.updateRuntimeStatus(arvadosclient.Dict{
318 "warning": "arv-mount: " + pattern,
319 "warningDetail": text,
323 c.Stdout = runner.arvMountLog
324 c.Stderr = io.MultiWriter(runner.arvMountLog, os.Stderr, &scanner)
326 runner.CrunchLog.Printf("Running %v", c.Args)
333 statReadme := make(chan bool)
334 runner.ArvMountExit = make(chan error)
339 time.Sleep(100 * time.Millisecond)
340 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
352 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
354 runner.ArvMountExit <- mnterr
355 close(runner.ArvMountExit)
361 case err := <-runner.ArvMountExit:
362 runner.ArvMount = nil
370 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
371 if runner.ArvMountPoint == "" {
372 runner.ArvMountPoint, err = runner.MkTempDir(runner.parentTemp, prefix)
377 func copyfile(src string, dst string) (err error) {
378 srcfile, err := os.Open(src)
383 os.MkdirAll(path.Dir(dst), 0777)
385 dstfile, err := os.Create(dst)
389 _, err = io.Copy(dstfile, srcfile)
394 err = srcfile.Close()
395 err2 := dstfile.Close()
408 func (runner *ContainerRunner) SetupMounts() (map[string]bindmount, error) {
409 bindmounts := map[string]bindmount{}
410 err := runner.SetupArvMountPoint("keep")
412 return nil, fmt.Errorf("While creating keep mount temp dir: %v", err)
415 token, err := runner.ContainerToken()
417 return nil, fmt.Errorf("could not get container token: %s", err)
419 runner.CrunchLog.Printf("container token %q", token)
423 arvMountCmd := []string{
427 "--storage-classes", strings.Join(runner.Container.OutputStorageClasses, ","),
428 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
430 if _, isdocker := runner.executor.(*dockerExecutor); isdocker {
431 arvMountCmd = append(arvMountCmd, "--allow-other")
434 if runner.Container.RuntimeConstraints.KeepCacheDisk > 0 {
435 keepcachedir, err := runner.MkTempDir(runner.parentTemp, "keepcache")
437 return nil, fmt.Errorf("while creating keep cache temp dir: %v", err)
439 arvMountCmd = append(arvMountCmd, "--disk-cache", "--disk-cache-dir", keepcachedir, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheDisk))
440 } else if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
441 arvMountCmd = append(arvMountCmd, "--ram-cache", "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
444 collectionPaths := []string{}
445 needCertMount := true
446 type copyFile struct {
450 var copyFiles []copyFile
453 for bind := range runner.Container.Mounts {
454 binds = append(binds, bind)
456 for bind := range runner.SecretMounts {
457 if _, ok := runner.Container.Mounts[bind]; ok {
458 return nil, fmt.Errorf("secret mount %q conflicts with regular mount", bind)
460 if runner.SecretMounts[bind].Kind != "json" &&
461 runner.SecretMounts[bind].Kind != "text" {
462 return nil, fmt.Errorf("secret mount %q type is %q but only 'json' and 'text' are permitted",
463 bind, runner.SecretMounts[bind].Kind)
465 binds = append(binds, bind)
469 for _, bind := range binds {
470 mnt, notSecret := runner.Container.Mounts[bind]
472 mnt = runner.SecretMounts[bind]
474 if bind == "stdout" || bind == "stderr" {
475 // Is it a "file" mount kind?
476 if mnt.Kind != "file" {
477 return nil, fmt.Errorf("unsupported mount kind '%s' for %s: only 'file' is supported", mnt.Kind, bind)
480 // Does path start with OutputPath?
481 prefix := runner.Container.OutputPath
482 if !strings.HasSuffix(prefix, "/") {
485 if !strings.HasPrefix(mnt.Path, prefix) {
486 return nil, fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
491 // Is it a "collection" mount kind?
492 if mnt.Kind != "collection" && mnt.Kind != "json" {
493 return nil, fmt.Errorf("unsupported mount kind '%s' for stdin: only 'collection' and 'json' are supported", mnt.Kind)
497 if bind == "/etc/arvados/ca-certificates.crt" {
498 needCertMount = false
501 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
502 if mnt.Kind != "collection" && mnt.Kind != "text" && mnt.Kind != "json" {
503 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)
508 case mnt.Kind == "collection" && bind != "stdin":
510 if mnt.UUID != "" && mnt.PortableDataHash != "" {
511 return nil, fmt.Errorf("cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
515 return nil, fmt.Errorf("writing to existing collections currently not permitted")
518 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
519 } else if mnt.PortableDataHash != "" {
520 if mnt.Writable && !strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
521 return nil, fmt.Errorf("can never write to a collection specified by portable data hash")
523 idx := strings.Index(mnt.PortableDataHash, "/")
525 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
526 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
527 runner.Container.Mounts[bind] = mnt
529 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
530 if mnt.Path != "" && mnt.Path != "." {
531 if strings.HasPrefix(mnt.Path, "./") {
532 mnt.Path = mnt.Path[2:]
533 } else if strings.HasPrefix(mnt.Path, "/") {
534 mnt.Path = mnt.Path[1:]
536 src += "/" + mnt.Path
539 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
540 arvMountCmd = append(arvMountCmd, "--mount-tmp", fmt.Sprintf("tmp%d", tmpcount))
544 if bind == runner.Container.OutputPath {
545 runner.HostOutputDir = src
546 bindmounts[bind] = bindmount{HostPath: src}
547 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
548 copyFiles = append(copyFiles, copyFile{src, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
550 bindmounts[bind] = bindmount{HostPath: src}
553 bindmounts[bind] = bindmount{HostPath: src, ReadOnly: true}
555 collectionPaths = append(collectionPaths, src)
557 case mnt.Kind == "tmp":
559 tmpdir, err = runner.MkTempDir(runner.parentTemp, "tmp")
561 return nil, fmt.Errorf("while creating mount temp dir: %v", err)
563 st, staterr := os.Stat(tmpdir)
565 return nil, fmt.Errorf("while Stat on temp dir: %v", staterr)
567 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
569 return nil, fmt.Errorf("while Chmod temp dir: %v", err)
571 bindmounts[bind] = bindmount{HostPath: tmpdir}
572 if bind == runner.Container.OutputPath {
573 runner.HostOutputDir = tmpdir
576 case mnt.Kind == "json" || mnt.Kind == "text":
578 if mnt.Kind == "json" {
579 filedata, err = json.Marshal(mnt.Content)
581 return nil, fmt.Errorf("encoding json data: %v", err)
584 text, ok := mnt.Content.(string)
586 return nil, fmt.Errorf("content for mount %q must be a string", bind)
588 filedata = []byte(text)
591 tmpdir, err := runner.MkTempDir(runner.parentTemp, mnt.Kind)
593 return nil, fmt.Errorf("creating temp dir: %v", err)
595 tmpfn := filepath.Join(tmpdir, "mountdata."+mnt.Kind)
596 err = ioutil.WriteFile(tmpfn, filedata, 0444)
598 return nil, fmt.Errorf("writing temp file: %v", err)
600 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && (notSecret || runner.Container.Mounts[runner.Container.OutputPath].Kind != "collection") {
601 // In most cases, if the container
602 // specifies a literal file inside the
603 // output path, we copy it into the
604 // output directory (either a mounted
605 // collection or a staging area on the
606 // host fs). If it's a secret, it will
607 // be skipped when copying output from
608 // staging to Keep later.
609 copyFiles = append(copyFiles, copyFile{tmpfn, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
611 // If a secret is outside OutputPath,
612 // we bind mount the secret file
613 // directly just like other mounts. We
614 // also use this strategy when a
615 // secret is inside OutputPath but
616 // OutputPath is a live collection, to
617 // avoid writing the secret to
618 // Keep. Attempting to remove a
619 // bind-mounted secret file from
620 // inside the container will return a
621 // "Device or resource busy" error
622 // that might not be handled well by
623 // the container, which is why we
624 // don't use this strategy when
625 // OutputPath is a staging directory.
626 bindmounts[bind] = bindmount{HostPath: tmpfn, ReadOnly: true}
629 case mnt.Kind == "git_tree":
630 tmpdir, err := runner.MkTempDir(runner.parentTemp, "git_tree")
632 return nil, fmt.Errorf("creating temp dir: %v", err)
634 err = gitMount(mnt).extractTree(runner.containerClient, tmpdir, token)
638 bindmounts[bind] = bindmount{HostPath: tmpdir, ReadOnly: true}
642 if runner.HostOutputDir == "" {
643 return nil, fmt.Errorf("output path does not correspond to a writable mount point")
646 if needCertMount && runner.Container.RuntimeConstraints.API {
647 for _, certfile := range arvadosclient.CertFiles {
648 _, err := os.Stat(certfile)
650 bindmounts["/etc/arvados/ca-certificates.crt"] = bindmount{HostPath: certfile, ReadOnly: true}
657 // If we are only mounting collections by pdh, make
658 // sure we don't subscribe to websocket events to
659 // avoid putting undesired load on the API server
660 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id", "--disable-event-listening")
662 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
664 // the by_uuid mount point is used by singularity when writing
665 // out docker images converted to SIF
666 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_uuid")
667 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
669 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
671 return nil, fmt.Errorf("while trying to start arv-mount: %v", err)
673 if runner.hoststatReporter != nil && runner.ArvMount != nil {
674 runner.hoststatReporter.ReportPID("arv-mount", runner.ArvMount.Process.Pid)
677 for _, p := range collectionPaths {
680 return nil, fmt.Errorf("while checking that input files exist: %v", err)
684 for _, cp := range copyFiles {
685 st, err := os.Stat(cp.src)
687 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
690 err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
694 target := path.Join(cp.bind, walkpath[len(cp.src):])
695 if walkinfo.Mode().IsRegular() {
696 copyerr := copyfile(walkpath, target)
700 return os.Chmod(target, walkinfo.Mode()|0777)
701 } else if walkinfo.Mode().IsDir() {
702 mkerr := os.MkdirAll(target, 0777)
706 return os.Chmod(target, walkinfo.Mode()|os.ModeSetgid|0777)
708 return fmt.Errorf("source %q is not a regular file or directory", cp.src)
711 } else if st.Mode().IsRegular() {
712 err = copyfile(cp.src, cp.bind)
714 err = os.Chmod(cp.bind, st.Mode()|0777)
718 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
722 return bindmounts, nil
725 func (runner *ContainerRunner) stopHoststat() error {
726 if runner.hoststatReporter == nil {
729 runner.hoststatReporter.Stop()
730 runner.hoststatReporter.LogProcessMemMax(runner.CrunchLog)
731 err := runner.hoststatLogger.Close()
733 return fmt.Errorf("error closing hoststat logs: %v", err)
738 func (runner *ContainerRunner) startHoststat() error {
739 w, err := runner.NewLogWriter("hoststat")
743 runner.hoststatLogger = NewThrottledLogger(w)
744 runner.hoststatReporter = &crunchstat.Reporter{
745 Logger: log.New(runner.hoststatLogger, "", 0),
746 // Our own cgroup is the "host" cgroup, in the sense
747 // that it accounts for resource usage outside the
748 // container. It doesn't count _all_ resource usage on
751 // TODO?: Use the furthest ancestor of our own cgroup
752 // that has stats available. (Currently crunchstat
753 // does not have that capability.)
755 PollPeriod: runner.statInterval,
757 runner.hoststatReporter.Start()
758 runner.hoststatReporter.ReportPID("crunch-run", os.Getpid())
762 func (runner *ContainerRunner) startCrunchstat() error {
763 w, err := runner.NewLogWriter("crunchstat")
767 runner.statLogger = NewThrottledLogger(w)
768 runner.statReporter = &crunchstat.Reporter{
769 Pid: runner.executor.Pid,
770 FS: runner.crunchstatFakeFS,
771 Logger: log.New(runner.statLogger, "", 0),
772 MemThresholds: map[string][]crunchstat.Threshold{
773 "rss": crunchstat.NewThresholdsFromPercentages(runner.Container.RuntimeConstraints.RAM, []int64{90, 95, 99}),
775 PollPeriod: runner.statInterval,
776 TempDir: runner.parentTemp,
777 ThresholdLogger: runner.CrunchLog,
779 runner.statReporter.Start()
783 type infoCommand struct {
788 // LogHostInfo logs info about the current host, for debugging and
789 // accounting purposes. Although it's logged as "node-info", this is
790 // about the environment where crunch-run is actually running, which
791 // might differ from what's described in the node record (see
793 func (runner *ContainerRunner) LogHostInfo() (err error) {
794 w, err := runner.NewLogWriter("node-info")
799 commands := []infoCommand{
801 label: "Host Information",
802 cmd: []string{"uname", "-a"},
805 label: "CPU Information",
806 cmd: []string{"cat", "/proc/cpuinfo"},
809 label: "Memory Information",
810 cmd: []string{"cat", "/proc/meminfo"},
814 cmd: []string{"df", "-m", "/", os.TempDir()},
817 label: "Disk INodes",
818 cmd: []string{"df", "-i", "/", os.TempDir()},
822 // Run commands with informational output to be logged.
823 for _, command := range commands {
824 fmt.Fprintln(w, command.label)
825 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
828 if err := cmd.Run(); err != nil {
829 err = fmt.Errorf("While running command %q: %v", command.cmd, err)
838 return fmt.Errorf("While closing node-info logs: %v", err)
843 // LogContainerRecord gets and saves the raw JSON container record from the API server
844 func (runner *ContainerRunner) LogContainerRecord() error {
845 logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
846 if !logged && err == nil {
847 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
852 // LogNodeRecord logs the current host's InstanceType config entry (or
853 // the arvados#node record, if running via crunch-dispatch-slurm).
854 func (runner *ContainerRunner) LogNodeRecord() error {
855 if it := os.Getenv("InstanceType"); it != "" {
856 // Dispatched via arvados-dispatch-cloud. Save
857 // InstanceType config fragment received from
858 // dispatcher on stdin.
859 w, err := runner.LogCollection.OpenFile("node.json", os.O_CREATE|os.O_WRONLY, 0666)
864 _, err = io.WriteString(w, it)
870 // Dispatched via crunch-dispatch-slurm. Look up
871 // apiserver's node record corresponding to
873 hostname := os.Getenv("SLURMD_NODENAME")
875 hostname, _ = os.Hostname()
877 _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
878 // The "info" field has admin-only info when
879 // obtained with a privileged token, and
880 // should not be logged.
881 node, ok := resp.(map[string]interface{})
889 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
890 writer, err := runner.LogCollection.OpenFile(label+".json", os.O_CREATE|os.O_WRONLY, 0666)
895 ArvClient: runner.DispatcherArvClient,
896 UUID: runner.Container.UUID,
897 loggingStream: label,
901 reader, err := runner.DispatcherArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
903 return false, fmt.Errorf("error getting %s record: %v", label, err)
907 dec := json.NewDecoder(reader)
909 var resp map[string]interface{}
910 if err = dec.Decode(&resp); err != nil {
911 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
913 items, ok := resp["items"].([]interface{})
915 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
916 } else if len(items) < 1 {
922 // Re-encode it using indentation to improve readability
923 enc := json.NewEncoder(w)
924 enc.SetIndent("", " ")
925 if err = enc.Encode(items[0]); err != nil {
926 return false, fmt.Errorf("error logging %s record: %v", label, err)
930 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
935 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
936 stdoutPath := mntPath[len(runner.Container.OutputPath):]
937 index := strings.LastIndex(stdoutPath, "/")
939 subdirs := stdoutPath[:index]
941 st, err := os.Stat(runner.HostOutputDir)
943 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
945 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
946 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
948 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
952 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
954 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
957 return stdoutFile, nil
960 // CreateContainer creates the docker container.
961 func (runner *ContainerRunner) CreateContainer(imageID string, bindmounts map[string]bindmount) error {
962 var stdin io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
963 if mnt, ok := runner.Container.Mounts["stdin"]; ok {
970 collID = mnt.PortableDataHash
972 path := runner.ArvMountPoint + "/by_id/" + collID + "/" + mnt.Path
973 f, err := os.Open(path)
979 j, err := json.Marshal(mnt.Content)
981 return fmt.Errorf("error encoding stdin json data: %v", err)
983 stdin = ioutil.NopCloser(bytes.NewReader(j))
985 return fmt.Errorf("stdin mount has unsupported kind %q", mnt.Kind)
989 var stdout, stderr io.WriteCloser
990 if mnt, ok := runner.Container.Mounts["stdout"]; ok {
991 f, err := runner.getStdoutFile(mnt.Path)
996 } else if w, err := runner.NewLogWriter("stdout"); err != nil {
999 stdout = NewThrottledLogger(w)
1002 if mnt, ok := runner.Container.Mounts["stderr"]; ok {
1003 f, err := runner.getStdoutFile(mnt.Path)
1008 } else if w, err := runner.NewLogWriter("stderr"); err != nil {
1011 stderr = NewThrottledLogger(w)
1014 env := runner.Container.Environment
1015 enableNetwork := runner.enableNetwork == "always"
1016 if runner.Container.RuntimeConstraints.API {
1017 enableNetwork = true
1018 tok, err := runner.ContainerToken()
1022 env = map[string]string{}
1023 for k, v := range runner.Container.Environment {
1026 env["ARVADOS_API_TOKEN"] = tok
1027 env["ARVADOS_API_HOST"] = os.Getenv("ARVADOS_API_HOST")
1028 env["ARVADOS_API_HOST_INSECURE"] = os.Getenv("ARVADOS_API_HOST_INSECURE")
1029 env["ARVADOS_KEEP_SERVICES"] = os.Getenv("ARVADOS_KEEP_SERVICES")
1031 workdir := runner.Container.Cwd
1033 // both "" and "." mean default
1036 ram := runner.Container.RuntimeConstraints.RAM
1037 if !runner.enableMemoryLimit {
1040 runner.executorStdin = stdin
1041 runner.executorStdout = stdout
1042 runner.executorStderr = stderr
1044 if runner.Container.RuntimeConstraints.CUDA.DeviceCount > 0 {
1045 nvidiaModprobe(runner.CrunchLog)
1048 return runner.executor.Create(containerSpec{
1050 VCPUs: runner.Container.RuntimeConstraints.VCPUs,
1052 WorkingDir: workdir,
1054 BindMounts: bindmounts,
1055 Command: runner.Container.Command,
1056 EnableNetwork: enableNetwork,
1057 CUDADeviceCount: runner.Container.RuntimeConstraints.CUDA.DeviceCount,
1058 NetworkMode: runner.networkMode,
1059 CgroupParent: runner.setCgroupParent,
1066 // StartContainer starts the docker container created by CreateContainer.
1067 func (runner *ContainerRunner) StartContainer() error {
1068 runner.CrunchLog.Printf("Starting container")
1069 runner.cStateLock.Lock()
1070 defer runner.cStateLock.Unlock()
1071 if runner.cCancelled {
1074 err := runner.executor.Start()
1077 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
1078 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])
1080 return fmt.Errorf("could not start container: %v%s", err, advice)
1085 // WaitFinish waits for the container to terminate, capture the exit code, and
1086 // close the stdout/stderr logging.
1087 func (runner *ContainerRunner) WaitFinish() error {
1088 runner.CrunchLog.Print("Waiting for container to finish")
1089 var timeout <-chan time.Time
1090 if s := runner.Container.SchedulingParameters.MaxRunTime; s > 0 {
1091 timeout = time.After(time.Duration(s) * time.Second)
1093 ctx, cancel := context.WithCancel(context.Background())
1098 runner.CrunchLog.Printf("maximum run time exceeded. Stopping container.")
1100 case <-runner.ArvMountExit:
1101 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
1106 exitcode, err := runner.executor.Wait(ctx)
1108 runner.checkBrokenNode(err)
1111 runner.ExitCode = &exitcode
1114 if exitcode&0x80 != 0 {
1115 // Convert raw exit status (0x80 + signal number) to a
1116 // string to log after the code, like " (signal 101)"
1117 // or " (signal 9, killed)"
1118 sig := syscall.WaitStatus(exitcode).Signal()
1119 if name := unix.SignalName(sig); name != "" {
1120 extra = fmt.Sprintf(" (signal %d, %s)", sig, name)
1122 extra = fmt.Sprintf(" (signal %d)", sig)
1125 runner.CrunchLog.Printf("Container exited with status code %d%s", exitcode, extra)
1126 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1127 "select": []string{"uuid"},
1128 "container": arvadosclient.Dict{"exit_code": exitcode},
1131 runner.CrunchLog.Printf("ignoring error updating exit_code: %s", err)
1135 if err = runner.executorStdin.Close(); err != nil {
1136 err = fmt.Errorf("error closing container stdin: %s", err)
1137 runner.CrunchLog.Printf("%s", err)
1140 if err = runner.executorStdout.Close(); err != nil {
1141 err = fmt.Errorf("error closing container stdout: %s", err)
1142 runner.CrunchLog.Printf("%s", err)
1143 if returnErr == nil {
1147 if err = runner.executorStderr.Close(); err != nil {
1148 err = fmt.Errorf("error closing container stderr: %s", err)
1149 runner.CrunchLog.Printf("%s", err)
1150 if returnErr == nil {
1155 if runner.statReporter != nil {
1156 runner.statReporter.Stop()
1157 runner.statReporter.LogMaxima(runner.CrunchLog, map[string]int64{
1158 "rss": runner.Container.RuntimeConstraints.RAM,
1160 err = runner.statLogger.Close()
1162 runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
1168 func (runner *ContainerRunner) updateLogs() {
1169 ticker := time.NewTicker(crunchLogUpdatePeriod / 360)
1172 sigusr1 := make(chan os.Signal, 1)
1173 signal.Notify(sigusr1, syscall.SIGUSR1)
1174 defer signal.Stop(sigusr1)
1176 saveAtTime := time.Now().Add(crunchLogUpdatePeriod)
1177 saveAtSize := crunchLogUpdateSize
1183 saveAtTime = time.Now()
1185 runner.logMtx.Lock()
1186 done := runner.LogsPDH != nil
1187 runner.logMtx.Unlock()
1191 size := runner.LogCollection.Size()
1192 if size == savedSize || (time.Now().Before(saveAtTime) && size < saveAtSize) {
1195 saveAtTime = time.Now().Add(crunchLogUpdatePeriod)
1196 saveAtSize = runner.LogCollection.Size() + crunchLogUpdateSize
1197 saved, err := runner.saveLogCollection(false)
1199 runner.CrunchLog.Printf("error updating log collection: %s", err)
1203 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1204 "select": []string{"uuid"},
1205 "container": arvadosclient.Dict{
1206 "log": saved.PortableDataHash,
1210 runner.CrunchLog.Printf("error updating container log to %s: %s", saved.PortableDataHash, err)
1218 var spotInterruptionCheckInterval = 5 * time.Second
1219 var ec2MetadataBaseURL = "http://169.254.169.254"
1221 const ec2TokenTTL = time.Second * 21600
1223 func (runner *ContainerRunner) checkSpotInterruptionNotices() {
1224 type ec2metadata struct {
1225 Action string `json:"action"`
1226 Time time.Time `json:"time"`
1228 runner.CrunchLog.Printf("Checking for spot interruptions every %v using instance metadata at %s", spotInterruptionCheckInterval, ec2MetadataBaseURL)
1229 var metadata ec2metadata
1231 var tokenExp time.Time
1232 check := func() error {
1233 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute))
1235 if token == "" || tokenExp.Sub(time.Now()) < time.Minute {
1236 req, err := http.NewRequestWithContext(ctx, http.MethodPut, ec2MetadataBaseURL+"/latest/api/token", nil)
1240 req.Header.Set("X-aws-ec2-metadata-token-ttl-seconds", fmt.Sprintf("%d", int(ec2TokenTTL/time.Second)))
1241 resp, err := http.DefaultClient.Do(req)
1245 defer resp.Body.Close()
1246 if resp.StatusCode != http.StatusOK {
1247 return fmt.Errorf("%s", resp.Status)
1249 newtoken, err := ioutil.ReadAll(resp.Body)
1253 token = strings.TrimSpace(string(newtoken))
1254 tokenExp = time.Now().Add(ec2TokenTTL)
1256 req, err := http.NewRequestWithContext(ctx, http.MethodGet, ec2MetadataBaseURL+"/latest/meta-data/spot/instance-action", nil)
1260 req.Header.Set("X-aws-ec2-metadata-token", token)
1261 resp, err := http.DefaultClient.Do(req)
1265 defer resp.Body.Close()
1266 metadata = ec2metadata{}
1267 switch resp.StatusCode {
1270 case http.StatusNotFound:
1271 // "If Amazon EC2 is not preparing to stop or
1272 // terminate the instance, or if you
1273 // terminated the instance yourself,
1274 // instance-action is not present in the
1275 // instance metadata and you receive an HTTP
1276 // 404 error when you try to retrieve it."
1278 case http.StatusUnauthorized:
1280 return fmt.Errorf("%s", resp.Status)
1282 return fmt.Errorf("%s", resp.Status)
1284 err = json.NewDecoder(resp.Body).Decode(&metadata)
1291 var lastmetadata ec2metadata
1292 for range time.NewTicker(spotInterruptionCheckInterval).C {
1295 runner.CrunchLog.Printf("Error checking spot interruptions: %s", err)
1298 runner.CrunchLog.Printf("Giving up on checking spot interruptions after too many consecutive failures")
1304 if metadata != lastmetadata {
1305 lastmetadata = metadata
1306 text := fmt.Sprintf("Cloud provider scheduled instance %s at %s", metadata.Action, metadata.Time.UTC().Format(time.RFC3339))
1307 runner.CrunchLog.Printf("%s", text)
1308 runner.updateRuntimeStatus(arvadosclient.Dict{
1309 "warning": "preemption notice",
1310 "warningDetail": text,
1311 "preemptionNotice": text,
1313 if proc, err := os.FindProcess(os.Getpid()); err == nil {
1314 // trigger updateLogs
1315 proc.Signal(syscall.SIGUSR1)
1321 func (runner *ContainerRunner) updateRuntimeStatus(status arvadosclient.Dict) {
1322 err := runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1323 "select": []string{"uuid"},
1324 "container": arvadosclient.Dict{
1325 "runtime_status": status,
1329 runner.CrunchLog.Printf("error updating container runtime_status: %s", err)
1333 // CaptureOutput saves data from the container's output directory if
1334 // needed, and updates the container output accordingly.
1335 func (runner *ContainerRunner) CaptureOutput(bindmounts map[string]bindmount) error {
1336 if runner.Container.RuntimeConstraints.API {
1337 // Output may have been set directly by the container, so
1338 // refresh the container record to check.
1339 err := runner.DispatcherArvClient.Get("containers", runner.Container.UUID,
1341 "select": []string{"output"},
1342 }, &runner.Container)
1346 if runner.Container.Output != "" {
1347 // Container output is already set.
1348 runner.OutputPDH = &runner.Container.Output
1353 txt, err := (&copier{
1354 client: runner.containerClient,
1355 keepClient: runner.ContainerKeepClient,
1356 hostOutputDir: runner.HostOutputDir,
1357 ctrOutputDir: runner.Container.OutputPath,
1358 bindmounts: bindmounts,
1359 mounts: runner.Container.Mounts,
1360 secretMounts: runner.SecretMounts,
1361 logger: runner.CrunchLog,
1366 if n := len(regexp.MustCompile(` [0-9a-f]+\+\S*\+R`).FindAllStringIndex(txt, -1)); n > 0 {
1367 runner.CrunchLog.Printf("Copying %d data blocks from remote input collections...", n)
1368 fs, err := (&arvados.Collection{ManifestText: txt}).FileSystem(runner.containerClient, runner.ContainerKeepClient)
1372 txt, err = fs.MarshalManifest(".")
1377 var resp arvados.Collection
1378 err = runner.ContainerArvClient.Create("collections", arvadosclient.Dict{
1379 "ensure_unique_name": true,
1380 "select": []string{"portable_data_hash"},
1381 "collection": arvadosclient.Dict{
1383 "name": "output for " + runner.Container.UUID,
1384 "manifest_text": txt,
1388 return fmt.Errorf("error creating output collection: %v", err)
1390 runner.OutputPDH = &resp.PortableDataHash
1394 func (runner *ContainerRunner) CleanupDirs() {
1395 if runner.ArvMount != nil {
1397 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1398 umount.Stdout = runner.CrunchLog
1399 umount.Stderr = runner.CrunchLog
1400 runner.CrunchLog.Printf("Running %v", umount.Args)
1401 umnterr := umount.Start()
1404 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1405 runner.ArvMount.Process.Kill()
1407 // If arv-mount --unmount gets stuck for any reason, we
1408 // don't want to wait for it forever. Do Wait() in a goroutine
1409 // so it doesn't block crunch-run.
1410 umountExit := make(chan error)
1412 mnterr := umount.Wait()
1414 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1416 umountExit <- mnterr
1419 for again := true; again; {
1425 case <-runner.ArvMountExit:
1427 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1428 runner.CrunchLog.Printf("Timed out waiting for unmount")
1430 umount.Process.Kill()
1432 runner.ArvMount.Process.Kill()
1436 runner.ArvMount = nil
1439 if runner.ArvMountPoint != "" {
1440 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1441 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1443 runner.ArvMountPoint = ""
1446 if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1447 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1451 // CommitLogs posts the collection containing the final container logs.
1452 func (runner *ContainerRunner) CommitLogs() error {
1454 // Hold cStateLock to prevent races on CrunchLog (e.g., stop()).
1455 runner.cStateLock.Lock()
1456 defer runner.cStateLock.Unlock()
1458 runner.CrunchLog.Print(runner.finalState)
1460 if runner.arvMountLog != nil {
1461 runner.arvMountLog.Close()
1463 runner.CrunchLog.Close()
1465 // Closing CrunchLog above allows them to be committed to Keep at this
1466 // point, but re-open crunch log with ArvClient in case there are any
1467 // other further errors (such as failing to write the log to Keep!)
1468 // while shutting down
1469 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{
1470 ArvClient: runner.DispatcherArvClient,
1471 UUID: runner.Container.UUID,
1472 loggingStream: "crunch-run",
1475 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1478 if runner.keepstoreLogger != nil {
1479 // Flush any buffered logs from our local keepstore
1480 // process. Discard anything logged after this point
1481 // -- it won't end up in the log collection, so
1482 // there's no point writing it to the collectionfs.
1483 runner.keepstoreLogbuf.SetWriter(io.Discard)
1484 runner.keepstoreLogger.Close()
1485 runner.keepstoreLogger = nil
1488 if runner.LogsPDH != nil {
1489 // If we have already assigned something to LogsPDH,
1490 // we must be closing the re-opened log, which won't
1491 // end up getting attached to the container record and
1492 // therefore doesn't need to be saved as a collection
1493 // -- it exists only to send logs to other channels.
1497 saved, err := runner.saveLogCollection(true)
1499 return fmt.Errorf("error saving log collection: %s", err)
1501 runner.logMtx.Lock()
1502 defer runner.logMtx.Unlock()
1503 runner.LogsPDH = &saved.PortableDataHash
1507 // Create/update the log collection. Return value has UUID and
1508 // PortableDataHash fields populated, but others may be blank.
1509 func (runner *ContainerRunner) saveLogCollection(final bool) (response arvados.Collection, err error) {
1510 runner.logMtx.Lock()
1511 defer runner.logMtx.Unlock()
1512 if runner.LogsPDH != nil {
1513 // Already finalized.
1516 updates := arvadosclient.Dict{
1517 "name": "logs for " + runner.Container.UUID,
1519 mt, err1 := runner.LogCollection.MarshalManifest(".")
1521 // Only send updated manifest text if there was no
1523 updates["manifest_text"] = mt
1526 // Even if flushing the manifest had an error, we still want
1527 // to update the log record, if possible, to push the trash_at
1528 // and delete_at times into the future. Details on bug
1531 updates["is_trashed"] = true
1533 // We set trash_at so this collection gets
1534 // automatically cleaned up eventually. It used to be
1535 // 12 hours but we had a situation where the API
1536 // server was down over a weekend but the containers
1537 // kept running such that the log collection got
1538 // trashed, so now we make it 2 weeks. refs #20378
1539 exp := time.Now().Add(time.Duration(24*14) * time.Hour)
1540 updates["trash_at"] = exp
1541 updates["delete_at"] = exp
1543 reqBody := arvadosclient.Dict{
1544 "select": []string{"uuid", "portable_data_hash"},
1545 "collection": updates,
1548 if runner.logUUID == "" {
1549 reqBody["ensure_unique_name"] = true
1550 err2 = runner.DispatcherArvClient.Create("collections", reqBody, &response)
1552 err2 = runner.DispatcherArvClient.Update("collections", runner.logUUID, reqBody, &response)
1555 runner.logUUID = response.UUID
1558 if err1 != nil || err2 != nil {
1559 err = fmt.Errorf("error recording logs: %q, %q", err1, err2)
1564 // UpdateContainerRunning updates the container state to "Running"
1565 func (runner *ContainerRunner) UpdateContainerRunning(logId string) error {
1566 runner.cStateLock.Lock()
1567 defer runner.cStateLock.Unlock()
1568 if runner.cCancelled {
1571 updates := arvadosclient.Dict{
1572 "gateway_address": runner.gateway.Address,
1576 updates["log"] = logId
1578 return runner.DispatcherArvClient.Update(
1580 runner.Container.UUID,
1582 "select": []string{"uuid"},
1583 "container": updates,
1589 // ContainerToken returns the api_token the container (and any
1590 // arv-mount processes) are allowed to use.
1591 func (runner *ContainerRunner) ContainerToken() (string, error) {
1592 if runner.token != "" {
1593 return runner.token, nil
1596 var auth arvados.APIClientAuthorization
1597 err := runner.DispatcherArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1601 runner.token = fmt.Sprintf("v2/%s/%s/%s", auth.UUID, auth.APIToken, runner.Container.UUID)
1602 return runner.token, nil
1605 // UpdateContainerFinal updates the container record state on API
1606 // server to "Complete" or "Cancelled"
1607 func (runner *ContainerRunner) UpdateContainerFinal() error {
1608 update := arvadosclient.Dict{}
1609 update["state"] = runner.finalState
1610 if runner.LogsPDH != nil {
1611 update["log"] = *runner.LogsPDH
1613 if runner.ExitCode != nil {
1614 update["exit_code"] = *runner.ExitCode
1616 update["exit_code"] = nil
1618 if runner.finalState == "Complete" && runner.OutputPDH != nil {
1619 update["output"] = *runner.OutputPDH
1621 update["cost"] = runner.calculateCost(time.Now())
1622 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1623 "select": []string{"uuid"},
1624 "container": update,
1628 // IsCancelled returns the value of Cancelled, with goroutine safety.
1629 func (runner *ContainerRunner) IsCancelled() bool {
1630 runner.cStateLock.Lock()
1631 defer runner.cStateLock.Unlock()
1632 return runner.cCancelled
1635 // NewArvLogWriter creates an ArvLogWriter
1636 func (runner *ContainerRunner) NewArvLogWriter(name string) (io.WriteCloser, error) {
1637 writer, err := runner.LogCollection.OpenFile(name+".txt", os.O_CREATE|os.O_WRONLY, 0666)
1641 return &ArvLogWriter{
1642 ArvClient: runner.DispatcherArvClient,
1643 UUID: runner.Container.UUID,
1644 loggingStream: name,
1645 writeCloser: writer,
1649 // Run the full container lifecycle.
1650 func (runner *ContainerRunner) Run() (err error) {
1651 runner.CrunchLog.Printf("crunch-run %s started", cmd.Version.String())
1652 runner.CrunchLog.Printf("%s", currentUserAndGroups())
1653 v, _ := exec.Command("arv-mount", "--version").CombinedOutput()
1654 runner.CrunchLog.Printf("Using FUSE mount: %s", v)
1655 runner.CrunchLog.Printf("Using container runtime: %s", runner.executor.Runtime())
1656 runner.CrunchLog.Printf("Executing container: %s", runner.Container.UUID)
1657 runner.costStartTime = time.Now()
1659 hostname, hosterr := os.Hostname()
1661 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1663 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1666 sigusr2 := make(chan os.Signal, 1)
1667 signal.Notify(sigusr2, syscall.SIGUSR2)
1668 defer signal.Stop(sigusr2)
1670 go runner.handleSIGUSR2(sigusr2)
1672 runner.finalState = "Queued"
1675 runner.CleanupDirs()
1677 runner.CrunchLog.Printf("crunch-run finished")
1678 runner.CrunchLog.Close()
1681 err = runner.fetchContainerRecord()
1685 if runner.Container.State != "Locked" {
1686 return fmt.Errorf("dispatch error detected: container %q has state %q", runner.Container.UUID, runner.Container.State)
1689 var bindmounts map[string]bindmount
1691 // checkErr prints e (unless it's nil) and sets err to
1692 // e (unless err is already non-nil). Thus, if err
1693 // hasn't already been assigned when Run() returns,
1694 // this cleanup func will cause Run() to return the
1695 // first non-nil error that is passed to checkErr().
1696 checkErr := func(errorIn string, e error) {
1700 runner.CrunchLog.Printf("error in %s: %v", errorIn, e)
1704 if runner.finalState == "Complete" {
1705 // There was an error in the finalization.
1706 runner.finalState = "Cancelled"
1710 // Log the error encountered in Run(), if any
1711 checkErr("Run", err)
1713 if runner.finalState == "Queued" {
1714 runner.UpdateContainerFinal()
1718 if runner.IsCancelled() {
1719 runner.finalState = "Cancelled"
1720 // but don't return yet -- we still want to
1721 // capture partial output and write logs
1724 if bindmounts != nil {
1725 checkErr("CaptureOutput", runner.CaptureOutput(bindmounts))
1727 checkErr("stopHoststat", runner.stopHoststat())
1728 checkErr("CommitLogs", runner.CommitLogs())
1729 runner.CleanupDirs()
1730 checkErr("UpdateContainerFinal", runner.UpdateContainerFinal())
1733 runner.setupSignals()
1734 err = runner.startHoststat()
1738 if runner.keepstore != nil {
1739 runner.hoststatReporter.ReportPID("keepstore", runner.keepstore.Process.Pid)
1742 // set up FUSE mount and binds
1743 bindmounts, err = runner.SetupMounts()
1745 runner.finalState = "Cancelled"
1746 err = fmt.Errorf("While setting up mounts: %v", err)
1750 // check for and/or load image
1751 imageID, err := runner.LoadImage()
1753 if !runner.checkBrokenNode(err) {
1754 // Failed to load image but not due to a "broken node"
1755 // condition, probably user error.
1756 runner.finalState = "Cancelled"
1758 err = fmt.Errorf("While loading container image: %v", err)
1762 err = runner.CreateContainer(imageID, bindmounts)
1766 err = runner.LogHostInfo()
1770 err = runner.LogNodeRecord()
1774 err = runner.LogContainerRecord()
1779 if runner.IsCancelled() {
1783 logCollection, err := runner.saveLogCollection(false)
1786 logId = logCollection.PortableDataHash
1788 runner.CrunchLog.Printf("Error committing initial log collection: %v", err)
1790 err = runner.UpdateContainerRunning(logId)
1794 runner.finalState = "Cancelled"
1796 err = runner.startCrunchstat()
1801 err = runner.StartContainer()
1803 runner.checkBrokenNode(err)
1807 err = runner.WaitFinish()
1808 if err == nil && !runner.IsCancelled() {
1809 runner.finalState = "Complete"
1814 // Fetch the current container record (uuid = runner.Container.UUID)
1815 // into runner.Container.
1816 func (runner *ContainerRunner) fetchContainerRecord() error {
1817 reader, err := runner.DispatcherArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1819 return fmt.Errorf("error fetching container record: %v", err)
1821 defer reader.Close()
1823 dec := json.NewDecoder(reader)
1825 err = dec.Decode(&runner.Container)
1827 return fmt.Errorf("error decoding container record: %v", err)
1831 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
1834 containerToken, err := runner.ContainerToken()
1836 return fmt.Errorf("error getting container token: %v", err)
1839 runner.ContainerArvClient, runner.ContainerKeepClient,
1840 runner.containerClient, err = runner.MkArvClient(containerToken)
1842 return fmt.Errorf("error creating container API client: %v", err)
1845 runner.ContainerKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1846 runner.DispatcherKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1848 err = runner.ContainerArvClient.Call("GET", "containers", runner.Container.UUID, "secret_mounts", nil, &sm)
1850 if apierr, ok := err.(arvadosclient.APIServerError); !ok || apierr.HttpStatusCode != 404 {
1851 return fmt.Errorf("error fetching secret_mounts: %v", err)
1853 // ok && apierr.HttpStatusCode == 404, which means
1854 // secret_mounts isn't supported by this API server.
1856 runner.SecretMounts = sm.SecretMounts
1861 // NewContainerRunner creates a new container runner.
1862 func NewContainerRunner(dispatcherClient *arvados.Client,
1863 dispatcherArvClient IArvadosClient,
1864 dispatcherKeepClient IKeepClient,
1865 containerUUID string) (*ContainerRunner, error) {
1867 cr := &ContainerRunner{
1868 dispatcherClient: dispatcherClient,
1869 DispatcherArvClient: dispatcherArvClient,
1870 DispatcherKeepClient: dispatcherKeepClient,
1872 cr.NewLogWriter = cr.NewArvLogWriter
1873 cr.RunArvMount = cr.ArvMountCmd
1874 cr.MkTempDir = ioutil.TempDir
1875 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1876 cl, err := arvadosclient.MakeArvadosClient()
1878 return nil, nil, nil, err
1881 kc, err := keepclient.MakeKeepClient(cl)
1883 return nil, nil, nil, err
1885 c2 := arvados.NewClientFromEnv()
1886 c2.AuthToken = token
1887 return cl, kc, c2, nil
1890 cr.LogCollection, err = (&arvados.Collection{}).FileSystem(cr.dispatcherClient, cr.DispatcherKeepClient)
1894 cr.Container.UUID = containerUUID
1895 w, err := cr.NewLogWriter("crunch-run")
1899 cr.CrunchLog = NewThrottledLogger(w)
1900 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1902 loadLogThrottleParams(dispatcherArvClient)
1908 func (command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
1909 log := log.New(stderr, "", 0)
1910 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
1911 statInterval := flags.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1912 flags.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree (obsolete, ignored)")
1913 flags.String("cgroup-parent", "docker", "name of container's parent cgroup (obsolete, ignored)")
1914 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")
1915 caCertsPath := flags.String("ca-certs", "", "Path to TLS root certificates")
1916 detach := flags.Bool("detach", false, "Detach from parent process and run in the background")
1917 stdinConfig := flags.Bool("stdin-config", false, "Load config and environment variables from JSON message on stdin")
1918 configFile := flags.String("config", arvados.DefaultConfigFile, "filename of cluster config file to try loading if -stdin-config=false (default is $ARVADOS_CONFIG)")
1919 sleep := flags.Duration("sleep", 0, "Delay before starting (testing use only)")
1920 kill := flags.Int("kill", -1, "Send signal to an existing crunch-run process for given UUID")
1921 list := flags.Bool("list", false, "List UUIDs of existing crunch-run processes (and notify them to use price data passed on stdin)")
1922 enableMemoryLimit := flags.Bool("enable-memory-limit", true, "tell container runtime to limit container's memory usage")
1923 enableNetwork := flags.String("container-enable-networking", "default", "enable networking \"always\" (for all containers) or \"default\" (for containers that request it)")
1924 networkMode := flags.String("container-network-mode", "default", `Docker network mode for container (use any argument valid for docker --net)`)
1925 memprofile := flags.String("memprofile", "", "write memory profile to `file` after running container")
1926 runtimeEngine := flags.String("runtime-engine", "docker", "container runtime: docker or singularity")
1927 brokenNodeHook := flags.String("broken-node-hook", "", "script to run if node is detected to be broken (for example, Docker daemon is not running)")
1928 flags.Duration("check-containerd", 0, "Ignored. Exists for compatibility with older versions.")
1929 version := flags.Bool("version", false, "Write version information to stdout and exit 0.")
1931 ignoreDetachFlag := false
1932 if len(args) > 0 && args[0] == "-no-detach" {
1933 // This process was invoked by a parent process, which
1934 // has passed along its own arguments, including
1935 // -detach, after the leading -no-detach flag. Strip
1936 // the leading -no-detach flag (it's not recognized by
1937 // flags.Parse()) and ignore the -detach flag that
1940 ignoreDetachFlag = true
1943 if ok, code := cmd.ParseFlags(flags, prog, args, "container-uuid", stderr); !ok {
1945 } else if *version {
1946 fmt.Fprintln(stdout, prog, cmd.Version.String())
1948 } else if !*list && flags.NArg() != 1 {
1949 fmt.Fprintf(stderr, "missing required argument: container-uuid (try -help)\n")
1953 containerUUID := flags.Arg(0)
1956 case *detach && !ignoreDetachFlag:
1957 return Detach(containerUUID, prog, args, stdin, stdout, stderr)
1959 return KillProcess(containerUUID, syscall.Signal(*kill), stdout, stderr)
1961 return ListProcesses(stdin, stdout, stderr)
1964 if len(containerUUID) != 27 {
1965 log.Printf("usage: %s [options] UUID", prog)
1969 var keepstoreLogbuf bufThenWrite
1972 err := json.NewDecoder(stdin).Decode(&conf)
1974 log.Printf("decode stdin: %s", err)
1977 for k, v := range conf.Env {
1978 err = os.Setenv(k, v)
1980 log.Printf("setenv(%q): %s", k, err)
1984 if conf.Cluster != nil {
1985 // ClusterID is missing from the JSON
1986 // representation, but we need it to generate
1987 // a valid config file for keepstore, so we
1988 // fill it using the container UUID prefix.
1989 conf.Cluster.ClusterID = containerUUID[:5]
1992 conf = hpcConfData(containerUUID, *configFile, io.MultiWriter(&keepstoreLogbuf, stderr))
1995 log.Printf("crunch-run %s started", cmd.Version.String())
1998 if *caCertsPath != "" {
1999 arvadosclient.CertFiles = []string{*caCertsPath}
2002 keepstore, err := startLocalKeepstore(conf, io.MultiWriter(&keepstoreLogbuf, stderr))
2007 if keepstore != nil {
2008 defer keepstore.Process.Kill()
2011 api, err := arvadosclient.MakeArvadosClient()
2013 log.Printf("%s: %v", containerUUID, err)
2016 // arvadosclient now interprets Retries=10 to mean
2017 // Timeout=10m, retrying with exponential backoff + jitter.
2020 kc, err := keepclient.MakeKeepClient(api)
2022 log.Printf("%s: %v", containerUUID, err)
2025 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
2028 cr, err := NewContainerRunner(arvados.NewClientFromEnv(), api, kc, containerUUID)
2034 cr.keepstore = keepstore
2035 if keepstore == nil {
2036 // Log explanation (if any) for why we're not running
2037 // a local keepstore.
2038 var buf bytes.Buffer
2039 keepstoreLogbuf.SetWriter(&buf)
2041 cr.CrunchLog.Printf("%s", strings.TrimSpace(buf.String()))
2043 } else if logWhat := conf.Cluster.Containers.LocalKeepLogsToContainerLog; logWhat == "none" {
2044 cr.CrunchLog.Printf("using local keepstore process (pid %d) at %s", keepstore.Process.Pid, os.Getenv("ARVADOS_KEEP_SERVICES"))
2045 keepstoreLogbuf.SetWriter(io.Discard)
2047 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"))
2048 logwriter, err := cr.NewLogWriter("keepstore")
2053 cr.keepstoreLogger = NewThrottledLogger(logwriter)
2055 var writer io.WriteCloser = cr.keepstoreLogger
2056 if logWhat == "errors" {
2057 writer = &filterKeepstoreErrorsOnly{WriteCloser: writer}
2058 } else if logWhat != "all" {
2059 // should have been caught earlier by
2060 // dispatcher's config loader
2061 log.Printf("invalid value for Containers.LocalKeepLogsToContainerLog: %q", logWhat)
2064 err = keepstoreLogbuf.SetWriter(writer)
2069 cr.keepstoreLogbuf = &keepstoreLogbuf
2072 switch *runtimeEngine {
2074 cr.executor, err = newDockerExecutor(containerUUID, cr.CrunchLog.Printf, cr.containerWatchdogInterval)
2076 cr.executor, err = newSingularityExecutor(cr.CrunchLog.Printf)
2078 cr.CrunchLog.Printf("%s: unsupported RuntimeEngine %q", containerUUID, *runtimeEngine)
2079 cr.CrunchLog.Close()
2083 cr.CrunchLog.Printf("%s: %v", containerUUID, err)
2084 cr.checkBrokenNode(err)
2085 cr.CrunchLog.Close()
2088 defer cr.executor.Close()
2090 cr.brokenNodeHook = *brokenNodeHook
2092 gwAuthSecret := os.Getenv("GatewayAuthSecret")
2093 os.Unsetenv("GatewayAuthSecret")
2094 if gwAuthSecret == "" {
2095 // not safe to run a gateway service without an auth
2097 cr.CrunchLog.Printf("Not starting a gateway server (GatewayAuthSecret was not provided by dispatcher)")
2099 gwListen := os.Getenv("GatewayAddress")
2100 cr.gateway = Gateway{
2102 AuthSecret: gwAuthSecret,
2103 ContainerUUID: containerUUID,
2104 Target: cr.executor,
2106 LogCollection: cr.LogCollection,
2109 // Direct connection won't work, so we use the
2110 // gateway_address field to indicate the
2111 // internalURL of the controller process that
2112 // has the current tunnel connection.
2113 cr.gateway.ArvadosClient = cr.dispatcherClient
2114 cr.gateway.UpdateTunnelURL = func(url string) {
2115 cr.gateway.Address = "tunnel " + url
2116 cr.DispatcherArvClient.Update("containers", containerUUID,
2118 "select": []string{"uuid"},
2119 "container": arvadosclient.Dict{"gateway_address": cr.gateway.Address},
2123 err = cr.gateway.Start()
2125 log.Printf("error starting gateway server: %s", err)
2130 parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerUUID+".")
2132 log.Printf("%s: %v", containerUUID, tmperr)
2136 cr.parentTemp = parentTemp
2137 cr.statInterval = *statInterval
2138 cr.enableMemoryLimit = *enableMemoryLimit
2139 cr.enableNetwork = *enableNetwork
2140 cr.networkMode = *networkMode
2141 if *cgroupParentSubsystem != "" {
2142 p, err := findCgroup(os.DirFS("/"), *cgroupParentSubsystem)
2144 log.Printf("fatal: cgroup parent subsystem: %s", err)
2147 cr.setCgroupParent = p
2150 if conf.EC2SpotCheck {
2151 go cr.checkSpotInterruptionNotices()
2156 if *memprofile != "" {
2157 f, err := os.Create(*memprofile)
2159 log.Printf("could not create memory profile: %s", err)
2161 runtime.GC() // get up-to-date statistics
2162 if err := pprof.WriteHeapProfile(f); err != nil {
2163 log.Printf("could not write memory profile: %s", err)
2165 closeerr := f.Close()
2166 if closeerr != nil {
2167 log.Printf("closing memprofile file: %s", err)
2172 log.Printf("%s: %v", containerUUID, runerr)
2178 // Try to load ConfigData in hpc (slurm/lsf) environment. This means
2179 // loading the cluster config from the specified file and (if that
2180 // works) getting the runtime_constraints container field from
2181 // controller to determine # VCPUs so we can calculate KeepBuffers.
2182 func hpcConfData(uuid string, configFile string, stderr io.Writer) ConfigData {
2184 conf.Cluster = loadClusterConfigFile(configFile, stderr)
2185 if conf.Cluster == nil {
2186 // skip loading the container record -- we won't be
2187 // able to start local keepstore anyway.
2190 arv, err := arvadosclient.MakeArvadosClient()
2192 fmt.Fprintf(stderr, "error setting up arvadosclient: %s\n", err)
2195 // arvadosclient now interprets Retries=10 to mean
2196 // Timeout=10m, retrying with exponential backoff + jitter.
2198 var ctr arvados.Container
2199 err = arv.Call("GET", "containers", uuid, "", arvadosclient.Dict{"select": []string{"runtime_constraints"}}, &ctr)
2201 fmt.Fprintf(stderr, "error getting container record: %s\n", err)
2204 if ctr.RuntimeConstraints.VCPUs > 0 {
2205 conf.KeepBuffers = ctr.RuntimeConstraints.VCPUs * conf.Cluster.Containers.LocalKeepBlobBuffersPerVCPU
2210 // Load cluster config file from given path. If an error occurs, log
2211 // the error to stderr and return nil.
2212 func loadClusterConfigFile(path string, stderr io.Writer) *arvados.Cluster {
2213 ldr := config.NewLoader(&bytes.Buffer{}, ctxlog.New(stderr, "plain", "info"))
2215 cfg, err := ldr.Load()
2217 fmt.Fprintf(stderr, "could not load config file %s: %s\n", path, err)
2220 cluster, err := cfg.GetCluster("")
2222 fmt.Fprintf(stderr, "could not use config file %s: %s\n", path, err)
2225 fmt.Fprintf(stderr, "loaded config file %s\n", path)
2229 func startLocalKeepstore(configData ConfigData, logbuf io.Writer) (*exec.Cmd, error) {
2230 if configData.KeepBuffers < 1 {
2231 fmt.Fprintf(logbuf, "not starting a local keepstore process because KeepBuffers=%v in config\n", configData.KeepBuffers)
2234 if configData.Cluster == nil {
2235 fmt.Fprint(logbuf, "not starting a local keepstore process because cluster config file was not loaded\n")
2238 for uuid, vol := range configData.Cluster.Volumes {
2239 if len(vol.AccessViaHosts) > 0 {
2240 fmt.Fprintf(logbuf, "not starting a local keepstore process because a volume (%s) uses AccessViaHosts\n", uuid)
2243 if !vol.ReadOnly && vol.Replication < configData.Cluster.Collections.DefaultReplication {
2244 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)
2249 // Rather than have an alternate way to tell keepstore how
2250 // many buffers to use when starting it this way, we just
2251 // modify the cluster configuration that we feed it on stdin.
2252 configData.Cluster.API.MaxKeepBlobBuffers = configData.KeepBuffers
2254 localaddr := localKeepstoreAddr()
2255 ln, err := net.Listen("tcp", net.JoinHostPort(localaddr, "0"))
2259 _, port, err := net.SplitHostPort(ln.Addr().String())
2265 url := "http://" + net.JoinHostPort(localaddr, port)
2267 fmt.Fprintf(logbuf, "starting keepstore on %s\n", url)
2269 var confJSON bytes.Buffer
2270 err = json.NewEncoder(&confJSON).Encode(arvados.Config{
2271 Clusters: map[string]arvados.Cluster{
2272 configData.Cluster.ClusterID: *configData.Cluster,
2278 cmd := exec.Command("/proc/self/exe", "keepstore", "-config=-")
2279 if target, err := os.Readlink(cmd.Path); err == nil && strings.HasSuffix(target, ".test") {
2280 // If we're a 'go test' process, running
2281 // /proc/self/exe would start the test suite in a
2282 // child process, which is not what we want.
2283 cmd.Path, _ = exec.LookPath("go")
2284 cmd.Args = append([]string{"go", "run", "../../cmd/arvados-server"}, cmd.Args[1:]...)
2285 cmd.Env = os.Environ()
2287 cmd.Stdin = &confJSON
2290 cmd.Env = append(cmd.Env,
2292 "ARVADOS_SERVICE_INTERNAL_URL="+url)
2295 return nil, fmt.Errorf("error starting keepstore process: %w", err)
2302 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*10))
2304 poll := time.NewTicker(time.Second / 10)
2306 client := http.Client{}
2308 testReq, err := http.NewRequestWithContext(ctx, "GET", url+"/_health/ping", nil)
2309 testReq.Header.Set("Authorization", "Bearer "+configData.Cluster.ManagementToken)
2313 resp, err := client.Do(testReq)
2316 if resp.StatusCode == http.StatusOK {
2321 return nil, fmt.Errorf("keepstore child process exited")
2323 if ctx.Err() != nil {
2324 return nil, fmt.Errorf("timed out waiting for new keepstore process to report healthy")
2327 os.Setenv("ARVADOS_KEEP_SERVICES", url)
2331 // return current uid, gid, groups in a format suitable for logging:
2332 // "crunch-run process has uid=1234(arvados) gid=1234(arvados)
2333 // groups=1234(arvados),114(fuse)"
2334 func currentUserAndGroups() string {
2335 u, err := user.Current()
2337 return fmt.Sprintf("error getting current user ID: %s", err)
2339 s := fmt.Sprintf("crunch-run process has uid=%s(%s) gid=%s", u.Uid, u.Username, u.Gid)
2340 if g, err := user.LookupGroupId(u.Gid); err == nil {
2341 s += fmt.Sprintf("(%s)", g.Name)
2344 if gids, err := u.GroupIds(); err == nil {
2345 for i, gid := range gids {
2350 if g, err := user.LookupGroupId(gid); err == nil {
2351 s += fmt.Sprintf("(%s)", g.Name)
2358 // Return a suitable local interface address for a local keepstore
2359 // service. Currently this is the numerically lowest non-loopback ipv4
2360 // address assigned to a local interface that is not in any of the
2361 // link-local/vpn/loopback ranges 169.254/16, 100.64/10, or 127/8.
2362 func localKeepstoreAddr() string {
2364 // Ignore error (proceed with zero IPs)
2365 addrs, _ := processIPs(os.Getpid())
2366 for addr := range addrs {
2367 ip := net.ParseIP(addr)
2372 if ip.Mask(net.CIDRMask(8, 32)).Equal(net.IPv4(127, 0, 0, 0)) ||
2373 ip.Mask(net.CIDRMask(10, 32)).Equal(net.IPv4(100, 64, 0, 0)) ||
2374 ip.Mask(net.CIDRMask(16, 32)).Equal(net.IPv4(169, 254, 0, 0)) {
2378 ips = append(ips, ip)
2383 sort.Slice(ips, func(ii, jj int) bool {
2384 i, j := ips[ii], ips[jj]
2385 if len(i) != len(j) {
2386 return len(i) < len(j)
2395 return ips[0].String()
2398 func (cr *ContainerRunner) loadPrices() {
2399 buf, err := os.ReadFile(filepath.Join(lockdir, pricesfile))
2401 if !os.IsNotExist(err) {
2402 cr.CrunchLog.Printf("loadPrices: read: %s", err)
2406 var prices []cloud.InstancePrice
2407 err = json.Unmarshal(buf, &prices)
2409 cr.CrunchLog.Printf("loadPrices: decode: %s", err)
2412 cr.pricesLock.Lock()
2413 defer cr.pricesLock.Unlock()
2414 var lastKnown time.Time
2415 if len(cr.prices) > 0 {
2416 lastKnown = cr.prices[0].StartTime
2418 cr.prices = cloud.NormalizePriceHistory(append(prices, cr.prices...))
2419 for i := len(cr.prices) - 1; i >= 0; i-- {
2420 price := cr.prices[i]
2421 if price.StartTime.After(lastKnown) {
2422 cr.CrunchLog.Printf("Instance price changed to %#.3g at %s", price.Price, price.StartTime.UTC())
2427 func (cr *ContainerRunner) calculateCost(now time.Time) float64 {
2428 cr.pricesLock.Lock()
2429 defer cr.pricesLock.Unlock()
2431 // First, make a "prices" slice with the real data as far back
2432 // as it goes, and (if needed) a "since the beginning of time"
2433 // placeholder containing a reasonable guess about what the
2434 // price was between cr.costStartTime and the earliest real
2437 if len(prices) == 0 {
2438 // use price info in InstanceType record initially
2439 // provided by cloud dispatcher
2441 var it arvados.InstanceType
2442 if j := os.Getenv("InstanceType"); j != "" && json.Unmarshal([]byte(j), &it) == nil && it.Price > 0 {
2445 prices = []cloud.InstancePrice{{Price: p}}
2446 } else if prices[len(prices)-1].StartTime.After(cr.costStartTime) {
2447 // guess earlier pricing was the same as the earliest
2448 // price we know about
2449 filler := prices[len(prices)-1]
2450 filler.StartTime = time.Time{}
2451 prices = append(prices, filler)
2454 // Now that our history of price changes goes back at least as
2455 // far as cr.costStartTime, add up the costs for each
2459 for _, ip := range prices {
2460 spanStart := ip.StartTime
2461 if spanStart.After(now) {
2462 // pricing information from the future -- not
2463 // expected from AWS, but possible in
2464 // principle, and exercised by tests.
2468 if spanStart.Before(cr.costStartTime) {
2469 spanStart = cr.costStartTime
2472 cost += ip.Price * spanEnd.Sub(spanStart).Seconds() / 3600
2482 func (runner *ContainerRunner) handleSIGUSR2(sigchan chan os.Signal) {
2485 update := arvadosclient.Dict{
2486 "select": []string{"uuid"},
2487 "container": arvadosclient.Dict{
2488 "cost": runner.calculateCost(time.Now()),
2491 runner.DispatcherArvClient.Update("containers", runner.Container.UUID, update, nil)