21700: Install Bundler system-wide in Rails postinst
[arvados.git] / lib / crunchrun / crunchrun.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package crunchrun
6
7 import (
8         "bytes"
9         "context"
10         "encoding/json"
11         "errors"
12         "flag"
13         "fmt"
14         "io"
15         "io/fs"
16         "io/ioutil"
17         "log"
18         "net"
19         "net/http"
20         "os"
21         "os/exec"
22         "os/signal"
23         "os/user"
24         "path"
25         "path/filepath"
26         "regexp"
27         "runtime"
28         "runtime/pprof"
29         "sort"
30         "strings"
31         "sync"
32         "syscall"
33         "time"
34
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"
45 )
46
47 type command struct{}
48
49 var arvadosCertPath = "/etc/arvados/ca-certificates.crt"
50
51 var Command = command{}
52
53 // ConfigData contains environment variables and (when needed) cluster
54 // configuration, passed from dispatchcloud to crunch-run on stdin.
55 type ConfigData struct {
56         Env          map[string]string
57         KeepBuffers  int
58         EC2SpotCheck bool
59         Cluster      *arvados.Cluster
60 }
61
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)
70 }
71
72 // ErrCancelled is the error returned when the container is cancelled.
73 var ErrCancelled = errors.New("Cancelled")
74
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)
82 }
83
84 // NewLogWriter is a factory function to create a new log writer.
85 type NewLogWriter func(name string) (io.WriteCloser, error)
86
87 type RunArvMount func(cmdline []string, tok string) (*exec.Cmd, error)
88
89 type MkTempDir func(string, string) (string, error)
90
91 type PsProcess interface {
92         CmdlineSlice() ([]string, error)
93 }
94
95 // ContainerRunner is the main stateful struct used for a single execution of a
96 // container.
97 type ContainerRunner struct {
98         executor       containerExecutor
99         executorStdin  io.Closer
100         executorStdout io.Closer
101         executorStderr io.Closer
102
103         // Dispatcher client is initialized with the Dispatcher token.
104         // This is a privileged token used to manage container status
105         // and logs.
106         //
107         // We have both dispatcherClient and DispatcherArvClient
108         // because there are two different incompatible Arvados Go
109         // SDKs and we have to use both (hopefully this gets fixed in
110         // #14467)
111         dispatcherClient     *arvados.Client
112         DispatcherArvClient  IArvadosClient
113         DispatcherKeepClient IKeepClient
114
115         // Container client is initialized with the Container token
116         // This token controls the permissions of the container, and
117         // must be used for operations such as reading collections.
118         //
119         // Same comment as above applies to
120         // containerClient/ContainerArvClient.
121         containerClient     *arvados.Client
122         ContainerArvClient  IArvadosClient
123         ContainerKeepClient IKeepClient
124
125         Container     arvados.Container
126         token         string
127         ExitCode      *int
128         NewLogWriter  NewLogWriter
129         CrunchLog     *ThrottledLogger
130         logUUID       string
131         logMtx        sync.Mutex
132         LogCollection arvados.CollectionFileSystem
133         LogsPDH       *string
134         RunArvMount   RunArvMount
135         MkTempDir     MkTempDir
136         ArvMount      *exec.Cmd
137         ArvMountPoint string
138         HostOutputDir string
139         Volumes       map[string]struct{}
140         OutputPDH     *string
141         SigChan       chan os.Signal
142         ArvMountExit  chan error
143         SecretMounts  map[string]arvados.Mount
144         MkArvClient   func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error)
145         finalState    string
146         parentTemp    string
147         costStartTime time.Time
148
149         keepstore        *exec.Cmd
150         keepstoreLogger  io.WriteCloser
151         keepstoreLogbuf  *bufThenWrite
152         statLogger       io.WriteCloser
153         statReporter     *crunchstat.Reporter
154         hoststatLogger   io.WriteCloser
155         hoststatReporter *crunchstat.Reporter
156         statInterval     time.Duration
157         // What we tell docker to use as the container's cgroup
158         // parent.
159         setCgroupParent string
160         // Fake root dir where crunchstat.Reporter should read OS
161         // files, for testing.
162         crunchstatFakeFS fs.FS
163
164         cStateLock sync.Mutex
165         cCancelled bool // StopContainer() invoked
166
167         enableMemoryLimit bool
168         enableNetwork     string // one of "default" or "always"
169         networkMode       string // "none", "host", or "" -- passed through to executor
170         brokenNodeHook    string // script to run if node appears to be broken
171         arvMountLog       *ThrottledLogger
172
173         containerWatchdogInterval time.Duration
174
175         gateway Gateway
176
177         prices     []cloud.InstancePrice
178         pricesLock sync.Mutex
179 }
180
181 // setupSignals sets up signal handling to gracefully terminate the
182 // underlying container and update state when receiving a TERM, INT or
183 // QUIT signal.
184 func (runner *ContainerRunner) setupSignals() {
185         runner.SigChan = make(chan os.Signal, 1)
186         signal.Notify(runner.SigChan, syscall.SIGTERM)
187         signal.Notify(runner.SigChan, syscall.SIGINT)
188         signal.Notify(runner.SigChan, syscall.SIGQUIT)
189
190         go func(sig chan os.Signal) {
191                 for s := range sig {
192                         runner.stop(s)
193                 }
194         }(runner.SigChan)
195 }
196
197 // stop the underlying container.
198 func (runner *ContainerRunner) stop(sig os.Signal) {
199         runner.cStateLock.Lock()
200         defer runner.cStateLock.Unlock()
201         if sig != nil {
202                 runner.CrunchLog.Printf("caught signal: %v", sig)
203         }
204         runner.cCancelled = true
205         runner.CrunchLog.Printf("stopping container")
206         err := runner.executor.Stop()
207         if err != nil {
208                 runner.CrunchLog.Printf("error stopping container: %s", err)
209         }
210 }
211
212 var errorBlacklist = []string{
213         "(?ms).*[Cc]annot connect to the Docker daemon.*",
214         "(?ms).*oci runtime error.*starting container process.*container init.*mounting.*to rootfs.*no such file or directory.*",
215         "(?ms).*grpc: the connection is unavailable.*",
216 }
217
218 func (runner *ContainerRunner) runBrokenNodeHook() {
219         if runner.brokenNodeHook == "" {
220                 path := filepath.Join(lockdir, brokenfile)
221                 runner.CrunchLog.Printf("Writing %s to mark node as broken", path)
222                 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0700)
223                 if err != nil {
224                         runner.CrunchLog.Printf("Error writing %s: %s", path, err)
225                         return
226                 }
227                 f.Close()
228         } else {
229                 runner.CrunchLog.Printf("Running broken node hook %q", runner.brokenNodeHook)
230                 // run killme script
231                 c := exec.Command(runner.brokenNodeHook)
232                 c.Stdout = runner.CrunchLog
233                 c.Stderr = runner.CrunchLog
234                 err := c.Run()
235                 if err != nil {
236                         runner.CrunchLog.Printf("Error running broken node hook: %v", err)
237                 }
238         }
239 }
240
241 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
242         for _, d := range errorBlacklist {
243                 if m, e := regexp.MatchString(d, goterr.Error()); m && e == nil {
244                         runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
245                         runner.runBrokenNodeHook()
246                         return true
247                 }
248         }
249         return false
250 }
251
252 // LoadImage determines the docker image id from the container record and
253 // checks if it is available in the local Docker image store.  If not, it loads
254 // the image from Keep.
255 func (runner *ContainerRunner) LoadImage() (string, error) {
256         runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
257
258         d, err := os.Open(runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage)
259         if err != nil {
260                 return "", err
261         }
262         defer d.Close()
263         allfiles, err := d.Readdirnames(-1)
264         if err != nil {
265                 return "", err
266         }
267         var tarfiles []string
268         for _, fnm := range allfiles {
269                 if strings.HasSuffix(fnm, ".tar") {
270                         tarfiles = append(tarfiles, fnm)
271                 }
272         }
273         if len(tarfiles) == 0 {
274                 return "", fmt.Errorf("image collection does not include a .tar image file")
275         }
276         if len(tarfiles) > 1 {
277                 return "", fmt.Errorf("cannot choose from multiple tar files in image collection: %v", tarfiles)
278         }
279         imageID := tarfiles[0][:len(tarfiles[0])-4]
280         imageTarballPath := runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage + "/" + imageID + ".tar"
281         runner.CrunchLog.Printf("Using Docker image id %q", imageID)
282
283         runner.CrunchLog.Print("Loading Docker image from keep")
284         err = runner.executor.LoadImage(imageID, imageTarballPath, runner.Container, runner.ArvMountPoint,
285                 runner.containerClient)
286         if err != nil {
287                 return "", err
288         }
289
290         return imageID, nil
291 }
292
293 func (runner *ContainerRunner) ArvMountCmd(cmdline []string, token string) (c *exec.Cmd, err error) {
294         c = exec.Command(cmdline[0], cmdline[1:]...)
295
296         // Copy our environment, but override ARVADOS_API_TOKEN with
297         // the container auth token.
298         c.Env = nil
299         for _, s := range os.Environ() {
300                 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
301                         c.Env = append(c.Env, s)
302                 }
303         }
304         c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
305
306         w, err := runner.NewLogWriter("arv-mount")
307         if err != nil {
308                 return nil, err
309         }
310         runner.arvMountLog = NewThrottledLogger(w)
311         scanner := logScanner{
312                 Patterns: []string{
313                         "Keep write error",
314                         "Block not found error",
315                         "Unhandled exception during FUSE operation",
316                 },
317                 ReportFunc: func(pattern, text string) {
318                         runner.updateRuntimeStatus(arvadosclient.Dict{
319                                 "warning":       "arv-mount: " + pattern,
320                                 "warningDetail": text,
321                         })
322                 },
323         }
324         c.Stdout = runner.arvMountLog
325         c.Stderr = io.MultiWriter(runner.arvMountLog, os.Stderr, &scanner)
326
327         runner.CrunchLog.Printf("Running %v", c.Args)
328
329         err = c.Start()
330         if err != nil {
331                 return nil, err
332         }
333
334         statReadme := make(chan bool)
335         runner.ArvMountExit = make(chan error)
336
337         keepStatting := true
338         go func() {
339                 for keepStatting {
340                         time.Sleep(100 * time.Millisecond)
341                         _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
342                         if err == nil {
343                                 keepStatting = false
344                                 statReadme <- true
345                         }
346                 }
347                 close(statReadme)
348         }()
349
350         go func() {
351                 mnterr := c.Wait()
352                 if mnterr != nil {
353                         runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
354                 }
355                 runner.ArvMountExit <- mnterr
356                 close(runner.ArvMountExit)
357         }()
358
359         select {
360         case <-statReadme:
361                 break
362         case err := <-runner.ArvMountExit:
363                 runner.ArvMount = nil
364                 keepStatting = false
365                 return nil, err
366         }
367
368         return c, nil
369 }
370
371 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
372         if runner.ArvMountPoint == "" {
373                 runner.ArvMountPoint, err = runner.MkTempDir(runner.parentTemp, prefix)
374         }
375         return
376 }
377
378 func copyfile(src string, dst string) (err error) {
379         srcfile, err := os.Open(src)
380         if err != nil {
381                 return
382         }
383
384         os.MkdirAll(path.Dir(dst), 0777)
385
386         dstfile, err := os.Create(dst)
387         if err != nil {
388                 return
389         }
390         _, err = io.Copy(dstfile, srcfile)
391         if err != nil {
392                 return
393         }
394
395         err = srcfile.Close()
396         err2 := dstfile.Close()
397
398         if err != nil {
399                 return
400         }
401
402         if err2 != nil {
403                 return err2
404         }
405
406         return nil
407 }
408
409 func (runner *ContainerRunner) SetupMounts() (map[string]bindmount, error) {
410         bindmounts := map[string]bindmount{}
411         err := runner.SetupArvMountPoint("keep")
412         if err != nil {
413                 return nil, fmt.Errorf("While creating keep mount temp dir: %v", err)
414         }
415
416         token, err := runner.ContainerToken()
417         if err != nil {
418                 return nil, fmt.Errorf("could not get container token: %s", err)
419         }
420         runner.CrunchLog.Printf("container token %q", token)
421
422         pdhOnly := true
423         tmpcount := 0
424         arvMountCmd := []string{
425                 "arv-mount",
426                 "--foreground",
427                 "--read-write",
428                 "--storage-classes", strings.Join(runner.Container.OutputStorageClasses, ","),
429                 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
430
431         if _, isdocker := runner.executor.(*dockerExecutor); isdocker {
432                 arvMountCmd = append(arvMountCmd, "--allow-other")
433         }
434
435         if runner.Container.RuntimeConstraints.KeepCacheDisk > 0 {
436                 keepcachedir, err := runner.MkTempDir(runner.parentTemp, "keepcache")
437                 if err != nil {
438                         return nil, fmt.Errorf("while creating keep cache temp dir: %v", err)
439                 }
440                 arvMountCmd = append(arvMountCmd, "--disk-cache", "--disk-cache-dir", keepcachedir, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheDisk))
441         } else if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
442                 arvMountCmd = append(arvMountCmd, "--ram-cache", "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
443         }
444
445         collectionPaths := []string{}
446         needCertMount := true
447         type copyFile struct {
448                 src  string
449                 bind string
450         }
451         var copyFiles []copyFile
452
453         var binds []string
454         for bind := range runner.Container.Mounts {
455                 binds = append(binds, bind)
456         }
457         for bind := range runner.SecretMounts {
458                 if _, ok := runner.Container.Mounts[bind]; ok {
459                         return nil, fmt.Errorf("secret mount %q conflicts with regular mount", bind)
460                 }
461                 if runner.SecretMounts[bind].Kind != "json" &&
462                         runner.SecretMounts[bind].Kind != "text" {
463                         return nil, fmt.Errorf("secret mount %q type is %q but only 'json' and 'text' are permitted",
464                                 bind, runner.SecretMounts[bind].Kind)
465                 }
466                 binds = append(binds, bind)
467         }
468         sort.Strings(binds)
469
470         for _, bind := range binds {
471                 mnt, notSecret := runner.Container.Mounts[bind]
472                 if !notSecret {
473                         mnt = runner.SecretMounts[bind]
474                 }
475                 if bind == "stdout" || bind == "stderr" {
476                         // Is it a "file" mount kind?
477                         if mnt.Kind != "file" {
478                                 return nil, fmt.Errorf("unsupported mount kind '%s' for %s: only 'file' is supported", mnt.Kind, bind)
479                         }
480
481                         // Does path start with OutputPath?
482                         prefix := runner.Container.OutputPath
483                         if !strings.HasSuffix(prefix, "/") {
484                                 prefix += "/"
485                         }
486                         if !strings.HasPrefix(mnt.Path, prefix) {
487                                 return nil, fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
488                         }
489                 }
490
491                 if bind == "stdin" {
492                         // Is it a "collection" mount kind?
493                         if mnt.Kind != "collection" && mnt.Kind != "json" {
494                                 return nil, fmt.Errorf("unsupported mount kind '%s' for stdin: only 'collection' and 'json' are supported", mnt.Kind)
495                         }
496                 }
497
498                 if bind == arvadosCertPath {
499                         needCertMount = false
500                 }
501
502                 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
503                         if mnt.Kind != "collection" && mnt.Kind != "text" && mnt.Kind != "json" {
504                                 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)
505                         }
506                 }
507
508                 switch {
509                 case mnt.Kind == "collection" && bind != "stdin":
510                         var src string
511                         if mnt.UUID != "" && mnt.PortableDataHash != "" {
512                                 return nil, fmt.Errorf("cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
513                         }
514                         if mnt.UUID != "" {
515                                 if mnt.Writable {
516                                         return nil, fmt.Errorf("writing to existing collections currently not permitted")
517                                 }
518                                 pdhOnly = false
519                                 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
520                         } else if mnt.PortableDataHash != "" {
521                                 if mnt.Writable && !strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
522                                         return nil, fmt.Errorf("can never write to a collection specified by portable data hash")
523                                 }
524                                 idx := strings.Index(mnt.PortableDataHash, "/")
525                                 if idx > 0 {
526                                         mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
527                                         mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
528                                         runner.Container.Mounts[bind] = mnt
529                                 }
530                                 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
531                                 if mnt.Path != "" && mnt.Path != "." {
532                                         if strings.HasPrefix(mnt.Path, "./") {
533                                                 mnt.Path = mnt.Path[2:]
534                                         } else if strings.HasPrefix(mnt.Path, "/") {
535                                                 mnt.Path = mnt.Path[1:]
536                                         }
537                                         src += "/" + mnt.Path
538                                 }
539                         } else {
540                                 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
541                                 arvMountCmd = append(arvMountCmd, "--mount-tmp", fmt.Sprintf("tmp%d", tmpcount))
542                                 tmpcount++
543                         }
544                         if mnt.Writable {
545                                 if bind == runner.Container.OutputPath {
546                                         runner.HostOutputDir = src
547                                         bindmounts[bind] = bindmount{HostPath: src}
548                                 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
549                                         copyFiles = append(copyFiles, copyFile{src, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
550                                 } else {
551                                         bindmounts[bind] = bindmount{HostPath: src}
552                                 }
553                         } else {
554                                 bindmounts[bind] = bindmount{HostPath: src, ReadOnly: true}
555                         }
556                         collectionPaths = append(collectionPaths, src)
557
558                 case mnt.Kind == "tmp":
559                         var tmpdir string
560                         tmpdir, err = runner.MkTempDir(runner.parentTemp, "tmp")
561                         if err != nil {
562                                 return nil, fmt.Errorf("while creating mount temp dir: %v", err)
563                         }
564                         st, staterr := os.Stat(tmpdir)
565                         if staterr != nil {
566                                 return nil, fmt.Errorf("while Stat on temp dir: %v", staterr)
567                         }
568                         err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
569                         if staterr != nil {
570                                 return nil, fmt.Errorf("while Chmod temp dir: %v", err)
571                         }
572                         bindmounts[bind] = bindmount{HostPath: tmpdir}
573                         if bind == runner.Container.OutputPath {
574                                 runner.HostOutputDir = tmpdir
575                         }
576
577                 case mnt.Kind == "json" || mnt.Kind == "text":
578                         var filedata []byte
579                         if mnt.Kind == "json" {
580                                 filedata, err = json.Marshal(mnt.Content)
581                                 if err != nil {
582                                         return nil, fmt.Errorf("encoding json data: %v", err)
583                                 }
584                         } else {
585                                 text, ok := mnt.Content.(string)
586                                 if !ok {
587                                         return nil, fmt.Errorf("content for mount %q must be a string", bind)
588                                 }
589                                 filedata = []byte(text)
590                         }
591
592                         tmpdir, err := runner.MkTempDir(runner.parentTemp, mnt.Kind)
593                         if err != nil {
594                                 return nil, fmt.Errorf("creating temp dir: %v", err)
595                         }
596                         tmpfn := filepath.Join(tmpdir, "mountdata."+mnt.Kind)
597                         err = ioutil.WriteFile(tmpfn, filedata, 0444)
598                         if err != nil {
599                                 return nil, fmt.Errorf("writing temp file: %v", err)
600                         }
601                         if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && (notSecret || runner.Container.Mounts[runner.Container.OutputPath].Kind != "collection") {
602                                 // In most cases, if the container
603                                 // specifies a literal file inside the
604                                 // output path, we copy it into the
605                                 // output directory (either a mounted
606                                 // collection or a staging area on the
607                                 // host fs). If it's a secret, it will
608                                 // be skipped when copying output from
609                                 // staging to Keep later.
610                                 copyFiles = append(copyFiles, copyFile{tmpfn, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
611                         } else {
612                                 // If a secret is outside OutputPath,
613                                 // we bind mount the secret file
614                                 // directly just like other mounts. We
615                                 // also use this strategy when a
616                                 // secret is inside OutputPath but
617                                 // OutputPath is a live collection, to
618                                 // avoid writing the secret to
619                                 // Keep. Attempting to remove a
620                                 // bind-mounted secret file from
621                                 // inside the container will return a
622                                 // "Device or resource busy" error
623                                 // that might not be handled well by
624                                 // the container, which is why we
625                                 // don't use this strategy when
626                                 // OutputPath is a staging directory.
627                                 bindmounts[bind] = bindmount{HostPath: tmpfn, ReadOnly: true}
628                         }
629
630                 case mnt.Kind == "git_tree":
631                         tmpdir, err := runner.MkTempDir(runner.parentTemp, "git_tree")
632                         if err != nil {
633                                 return nil, fmt.Errorf("creating temp dir: %v", err)
634                         }
635                         err = gitMount(mnt).extractTree(runner.containerClient, tmpdir, token)
636                         if err != nil {
637                                 return nil, err
638                         }
639                         bindmounts[bind] = bindmount{HostPath: tmpdir, ReadOnly: true}
640                 }
641         }
642
643         if runner.HostOutputDir == "" {
644                 return nil, fmt.Errorf("output path does not correspond to a writable mount point")
645         }
646
647         if needCertMount && runner.Container.RuntimeConstraints.API {
648                 for _, certfile := range []string{
649                         // Populated by caller, or sdk/go/arvados init(), or test suite:
650                         os.Getenv("SSL_CERT_FILE"),
651                         // Copied from Go 1.21 stdlib (src/crypto/x509/root_linux.go):
652                         "/etc/ssl/certs/ca-certificates.crt",                // Debian/Ubuntu/Gentoo etc.
653                         "/etc/pki/tls/certs/ca-bundle.crt",                  // Fedora/RHEL 6
654                         "/etc/ssl/ca-bundle.pem",                            // OpenSUSE
655                         "/etc/pki/tls/cacert.pem",                           // OpenELEC
656                         "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", // CentOS/RHEL 7
657                         "/etc/ssl/cert.pem",                                 // Alpine Linux
658                 } {
659                         if _, err := os.Stat(certfile); err == nil {
660                                 bindmounts[arvadosCertPath] = bindmount{HostPath: certfile, ReadOnly: true}
661                                 break
662                         }
663                 }
664         }
665
666         if pdhOnly {
667                 // If we are only mounting collections by pdh, make
668                 // sure we don't subscribe to websocket events to
669                 // avoid putting undesired load on the API server
670                 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id", "--disable-event-listening")
671         } else {
672                 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
673         }
674         // the by_uuid mount point is used by singularity when writing
675         // out docker images converted to SIF
676         arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_uuid")
677         arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
678
679         runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
680         if err != nil {
681                 return nil, fmt.Errorf("while trying to start arv-mount: %v", err)
682         }
683         if runner.hoststatReporter != nil && runner.ArvMount != nil {
684                 runner.hoststatReporter.ReportPID("arv-mount", runner.ArvMount.Process.Pid)
685         }
686
687         for _, p := range collectionPaths {
688                 _, err = os.Stat(p)
689                 if err != nil {
690                         return nil, fmt.Errorf("while checking that input files exist: %v", err)
691                 }
692         }
693
694         for _, cp := range copyFiles {
695                 st, err := os.Stat(cp.src)
696                 if err != nil {
697                         return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
698                 }
699                 if st.IsDir() {
700                         err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
701                                 if walkerr != nil {
702                                         return walkerr
703                                 }
704                                 target := path.Join(cp.bind, walkpath[len(cp.src):])
705                                 if walkinfo.Mode().IsRegular() {
706                                         copyerr := copyfile(walkpath, target)
707                                         if copyerr != nil {
708                                                 return copyerr
709                                         }
710                                         return os.Chmod(target, walkinfo.Mode()|0777)
711                                 } else if walkinfo.Mode().IsDir() {
712                                         mkerr := os.MkdirAll(target, 0777)
713                                         if mkerr != nil {
714                                                 return mkerr
715                                         }
716                                         return os.Chmod(target, walkinfo.Mode()|os.ModeSetgid|0777)
717                                 } else {
718                                         return fmt.Errorf("source %q is not a regular file or directory", cp.src)
719                                 }
720                         })
721                 } else if st.Mode().IsRegular() {
722                         err = copyfile(cp.src, cp.bind)
723                         if err == nil {
724                                 err = os.Chmod(cp.bind, st.Mode()|0777)
725                         }
726                 }
727                 if err != nil {
728                         return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
729                 }
730         }
731
732         return bindmounts, nil
733 }
734
735 func (runner *ContainerRunner) stopHoststat() error {
736         if runner.hoststatReporter == nil {
737                 return nil
738         }
739         runner.hoststatReporter.Stop()
740         runner.hoststatReporter.LogProcessMemMax(runner.CrunchLog)
741         err := runner.hoststatLogger.Close()
742         if err != nil {
743                 return fmt.Errorf("error closing hoststat logs: %v", err)
744         }
745         return nil
746 }
747
748 func (runner *ContainerRunner) startHoststat() error {
749         w, err := runner.NewLogWriter("hoststat")
750         if err != nil {
751                 return err
752         }
753         runner.hoststatLogger = NewThrottledLogger(w)
754         runner.hoststatReporter = &crunchstat.Reporter{
755                 Logger: log.New(runner.hoststatLogger, "", 0),
756                 // Our own cgroup is the "host" cgroup, in the sense
757                 // that it accounts for resource usage outside the
758                 // container. It doesn't count _all_ resource usage on
759                 // the system.
760                 //
761                 // TODO?: Use the furthest ancestor of our own cgroup
762                 // that has stats available. (Currently crunchstat
763                 // does not have that capability.)
764                 Pid:        os.Getpid,
765                 PollPeriod: runner.statInterval,
766         }
767         runner.hoststatReporter.Start()
768         runner.hoststatReporter.ReportPID("crunch-run", os.Getpid())
769         return nil
770 }
771
772 func (runner *ContainerRunner) startCrunchstat() error {
773         w, err := runner.NewLogWriter("crunchstat")
774         if err != nil {
775                 return err
776         }
777         runner.statLogger = NewThrottledLogger(w)
778         runner.statReporter = &crunchstat.Reporter{
779                 Pid:    runner.executor.Pid,
780                 FS:     runner.crunchstatFakeFS,
781                 Logger: log.New(runner.statLogger, "", 0),
782                 MemThresholds: map[string][]crunchstat.Threshold{
783                         "rss": crunchstat.NewThresholdsFromPercentages(runner.Container.RuntimeConstraints.RAM, []int64{90, 95, 99}),
784                 },
785                 PollPeriod:      runner.statInterval,
786                 TempDir:         runner.parentTemp,
787                 ThresholdLogger: runner.CrunchLog,
788         }
789         runner.statReporter.Start()
790         return nil
791 }
792
793 type infoCommand struct {
794         label string
795         cmd   []string
796 }
797
798 // LogHostInfo logs info about the current host, for debugging and
799 // accounting purposes. Although it's logged as "node-info", this is
800 // about the environment where crunch-run is actually running, which
801 // might differ from what's described in the node record (see
802 // LogNodeRecord).
803 func (runner *ContainerRunner) LogHostInfo() (err error) {
804         w, err := runner.NewLogWriter("node-info")
805         if err != nil {
806                 return
807         }
808
809         commands := []infoCommand{
810                 {
811                         label: "Host Information",
812                         cmd:   []string{"uname", "-a"},
813                 },
814                 {
815                         label: "CPU Information",
816                         cmd:   []string{"cat", "/proc/cpuinfo"},
817                 },
818                 {
819                         label: "Memory Information",
820                         cmd:   []string{"cat", "/proc/meminfo"},
821                 },
822                 {
823                         label: "Disk Space",
824                         cmd:   []string{"df", "-m", "/", os.TempDir()},
825                 },
826                 {
827                         label: "Disk INodes",
828                         cmd:   []string{"df", "-i", "/", os.TempDir()},
829                 },
830         }
831
832         // Run commands with informational output to be logged.
833         for _, command := range commands {
834                 fmt.Fprintln(w, command.label)
835                 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
836                 cmd.Stdout = w
837                 cmd.Stderr = w
838                 if err := cmd.Run(); err != nil {
839                         err = fmt.Errorf("While running command %q: %v", command.cmd, err)
840                         fmt.Fprintln(w, err)
841                         return err
842                 }
843                 fmt.Fprintln(w, "")
844         }
845
846         err = w.Close()
847         if err != nil {
848                 return fmt.Errorf("While closing node-info logs: %v", err)
849         }
850         return nil
851 }
852
853 // LogContainerRecord gets and saves the raw JSON container record from the API server
854 func (runner *ContainerRunner) LogContainerRecord() error {
855         logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
856         if !logged && err == nil {
857                 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
858         }
859         return err
860 }
861
862 // LogNodeRecord logs the current host's InstanceType config entry (or
863 // the arvados#node record, if running via crunch-dispatch-slurm).
864 func (runner *ContainerRunner) LogNodeRecord() error {
865         if it := os.Getenv("InstanceType"); it != "" {
866                 // Dispatched via arvados-dispatch-cloud. Save
867                 // InstanceType config fragment received from
868                 // dispatcher on stdin.
869                 w, err := runner.LogCollection.OpenFile("node.json", os.O_CREATE|os.O_WRONLY, 0666)
870                 if err != nil {
871                         return err
872                 }
873                 defer w.Close()
874                 _, err = io.WriteString(w, it)
875                 if err != nil {
876                         return err
877                 }
878                 return w.Close()
879         }
880         // Dispatched via crunch-dispatch-slurm. Look up
881         // apiserver's node record corresponding to
882         // $SLURMD_NODENAME.
883         hostname := os.Getenv("SLURMD_NODENAME")
884         if hostname == "" {
885                 hostname, _ = os.Hostname()
886         }
887         _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
888                 // The "info" field has admin-only info when
889                 // obtained with a privileged token, and
890                 // should not be logged.
891                 node, ok := resp.(map[string]interface{})
892                 if ok {
893                         delete(node, "info")
894                 }
895         })
896         return err
897 }
898
899 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
900         writer, err := runner.LogCollection.OpenFile(label+".json", os.O_CREATE|os.O_WRONLY, 0666)
901         if err != nil {
902                 return false, err
903         }
904         w := &ArvLogWriter{
905                 ArvClient:     runner.DispatcherArvClient,
906                 UUID:          runner.Container.UUID,
907                 loggingStream: label,
908                 writeCloser:   writer,
909         }
910
911         reader, err := runner.DispatcherArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
912         if err != nil {
913                 return false, fmt.Errorf("error getting %s record: %v", label, err)
914         }
915         defer reader.Close()
916
917         dec := json.NewDecoder(reader)
918         dec.UseNumber()
919         var resp map[string]interface{}
920         if err = dec.Decode(&resp); err != nil {
921                 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
922         }
923         items, ok := resp["items"].([]interface{})
924         if !ok {
925                 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
926         } else if len(items) < 1 {
927                 return false, nil
928         }
929         if munge != nil {
930                 munge(items[0])
931         }
932         // Re-encode it using indentation to improve readability
933         enc := json.NewEncoder(w)
934         enc.SetIndent("", "    ")
935         if err = enc.Encode(items[0]); err != nil {
936                 return false, fmt.Errorf("error logging %s record: %v", label, err)
937         }
938         err = w.Close()
939         if err != nil {
940                 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
941         }
942         return true, nil
943 }
944
945 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
946         stdoutPath := mntPath[len(runner.Container.OutputPath):]
947         index := strings.LastIndex(stdoutPath, "/")
948         if index > 0 {
949                 subdirs := stdoutPath[:index]
950                 if subdirs != "" {
951                         st, err := os.Stat(runner.HostOutputDir)
952                         if err != nil {
953                                 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
954                         }
955                         stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
956                         err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
957                         if err != nil {
958                                 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
959                         }
960                 }
961         }
962         stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
963         if err != nil {
964                 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
965         }
966
967         return stdoutFile, nil
968 }
969
970 // CreateContainer creates the docker container.
971 func (runner *ContainerRunner) CreateContainer(imageID string, bindmounts map[string]bindmount) error {
972         var stdin io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
973         if mnt, ok := runner.Container.Mounts["stdin"]; ok {
974                 switch mnt.Kind {
975                 case "collection":
976                         var collID string
977                         if mnt.UUID != "" {
978                                 collID = mnt.UUID
979                         } else {
980                                 collID = mnt.PortableDataHash
981                         }
982                         path := runner.ArvMountPoint + "/by_id/" + collID + "/" + mnt.Path
983                         f, err := os.Open(path)
984                         if err != nil {
985                                 return err
986                         }
987                         stdin = f
988                 case "json":
989                         j, err := json.Marshal(mnt.Content)
990                         if err != nil {
991                                 return fmt.Errorf("error encoding stdin json data: %v", err)
992                         }
993                         stdin = ioutil.NopCloser(bytes.NewReader(j))
994                 default:
995                         return fmt.Errorf("stdin mount has unsupported kind %q", mnt.Kind)
996                 }
997         }
998
999         var stdout, stderr io.WriteCloser
1000         if mnt, ok := runner.Container.Mounts["stdout"]; ok {
1001                 f, err := runner.getStdoutFile(mnt.Path)
1002                 if err != nil {
1003                         return err
1004                 }
1005                 stdout = f
1006         } else if w, err := runner.NewLogWriter("stdout"); err != nil {
1007                 return err
1008         } else {
1009                 stdout = NewThrottledLogger(w)
1010         }
1011
1012         if mnt, ok := runner.Container.Mounts["stderr"]; ok {
1013                 f, err := runner.getStdoutFile(mnt.Path)
1014                 if err != nil {
1015                         return err
1016                 }
1017                 stderr = f
1018         } else if w, err := runner.NewLogWriter("stderr"); err != nil {
1019                 return err
1020         } else {
1021                 stderr = NewThrottledLogger(w)
1022         }
1023
1024         env := runner.Container.Environment
1025         enableNetwork := runner.enableNetwork == "always"
1026         if runner.Container.RuntimeConstraints.API {
1027                 enableNetwork = true
1028                 tok, err := runner.ContainerToken()
1029                 if err != nil {
1030                         return err
1031                 }
1032                 env = map[string]string{}
1033                 for k, v := range runner.Container.Environment {
1034                         env[k] = v
1035                 }
1036                 env["ARVADOS_API_TOKEN"] = tok
1037                 env["ARVADOS_API_HOST"] = os.Getenv("ARVADOS_API_HOST")
1038                 env["ARVADOS_API_HOST_INSECURE"] = os.Getenv("ARVADOS_API_HOST_INSECURE")
1039                 env["ARVADOS_KEEP_SERVICES"] = os.Getenv("ARVADOS_KEEP_SERVICES")
1040         }
1041         workdir := runner.Container.Cwd
1042         if workdir == "." {
1043                 // both "" and "." mean default
1044                 workdir = ""
1045         }
1046         ram := runner.Container.RuntimeConstraints.RAM
1047         if !runner.enableMemoryLimit {
1048                 ram = 0
1049         }
1050         runner.executorStdin = stdin
1051         runner.executorStdout = stdout
1052         runner.executorStderr = stderr
1053
1054         if runner.Container.RuntimeConstraints.CUDA.DeviceCount > 0 {
1055                 nvidiaModprobe(runner.CrunchLog)
1056         }
1057
1058         return runner.executor.Create(containerSpec{
1059                 Image:           imageID,
1060                 VCPUs:           runner.Container.RuntimeConstraints.VCPUs,
1061                 RAM:             ram,
1062                 WorkingDir:      workdir,
1063                 Env:             env,
1064                 BindMounts:      bindmounts,
1065                 Command:         runner.Container.Command,
1066                 EnableNetwork:   enableNetwork,
1067                 CUDADeviceCount: runner.Container.RuntimeConstraints.CUDA.DeviceCount,
1068                 NetworkMode:     runner.networkMode,
1069                 CgroupParent:    runner.setCgroupParent,
1070                 Stdin:           stdin,
1071                 Stdout:          stdout,
1072                 Stderr:          stderr,
1073         })
1074 }
1075
1076 // StartContainer starts the docker container created by CreateContainer.
1077 func (runner *ContainerRunner) StartContainer() error {
1078         runner.CrunchLog.Printf("Starting container")
1079         runner.cStateLock.Lock()
1080         defer runner.cStateLock.Unlock()
1081         if runner.cCancelled {
1082                 return ErrCancelled
1083         }
1084         err := runner.executor.Start()
1085         if err != nil {
1086                 var advice string
1087                 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
1088                         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])
1089                 }
1090                 return fmt.Errorf("could not start container: %v%s", err, advice)
1091         }
1092         return nil
1093 }
1094
1095 // WaitFinish waits for the container to terminate, capture the exit code, and
1096 // close the stdout/stderr logging.
1097 func (runner *ContainerRunner) WaitFinish() error {
1098         runner.CrunchLog.Print("Waiting for container to finish")
1099         var timeout <-chan time.Time
1100         if s := runner.Container.SchedulingParameters.MaxRunTime; s > 0 {
1101                 timeout = time.After(time.Duration(s) * time.Second)
1102         }
1103         ctx, cancel := context.WithCancel(context.Background())
1104         defer cancel()
1105         go func() {
1106                 select {
1107                 case <-timeout:
1108                         runner.CrunchLog.Printf("maximum run time exceeded. Stopping container.")
1109                         runner.stop(nil)
1110                 case <-runner.ArvMountExit:
1111                         runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
1112                         runner.stop(nil)
1113                 case <-ctx.Done():
1114                 }
1115         }()
1116         exitcode, err := runner.executor.Wait(ctx)
1117         if err != nil {
1118                 runner.checkBrokenNode(err)
1119                 return err
1120         }
1121         runner.ExitCode = &exitcode
1122
1123         extra := ""
1124         if exitcode&0x80 != 0 {
1125                 // Convert raw exit status (0x80 + signal number) to a
1126                 // string to log after the code, like " (signal 101)"
1127                 // or " (signal 9, killed)"
1128                 sig := syscall.WaitStatus(exitcode).Signal()
1129                 if name := unix.SignalName(sig); name != "" {
1130                         extra = fmt.Sprintf(" (signal %d, %s)", sig, name)
1131                 } else {
1132                         extra = fmt.Sprintf(" (signal %d)", sig)
1133                 }
1134         }
1135         runner.CrunchLog.Printf("Container exited with status code %d%s", exitcode, extra)
1136         err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1137                 "select":    []string{"uuid"},
1138                 "container": arvadosclient.Dict{"exit_code": exitcode},
1139         }, nil)
1140         if err != nil {
1141                 runner.CrunchLog.Printf("ignoring error updating exit_code: %s", err)
1142         }
1143
1144         var returnErr error
1145         if err = runner.executorStdin.Close(); err != nil {
1146                 err = fmt.Errorf("error closing container stdin: %s", err)
1147                 runner.CrunchLog.Printf("%s", err)
1148                 returnErr = err
1149         }
1150         if err = runner.executorStdout.Close(); err != nil {
1151                 err = fmt.Errorf("error closing container stdout: %s", err)
1152                 runner.CrunchLog.Printf("%s", err)
1153                 if returnErr == nil {
1154                         returnErr = err
1155                 }
1156         }
1157         if err = runner.executorStderr.Close(); err != nil {
1158                 err = fmt.Errorf("error closing container stderr: %s", err)
1159                 runner.CrunchLog.Printf("%s", err)
1160                 if returnErr == nil {
1161                         returnErr = err
1162                 }
1163         }
1164
1165         if runner.statReporter != nil {
1166                 runner.statReporter.Stop()
1167                 runner.statReporter.LogMaxima(runner.CrunchLog, map[string]int64{
1168                         "rss": runner.Container.RuntimeConstraints.RAM,
1169                 })
1170                 err = runner.statLogger.Close()
1171                 if err != nil {
1172                         runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
1173                 }
1174         }
1175         return returnErr
1176 }
1177
1178 func (runner *ContainerRunner) updateLogs() {
1179         ticker := time.NewTicker(crunchLogUpdatePeriod / 360)
1180         defer ticker.Stop()
1181
1182         sigusr1 := make(chan os.Signal, 1)
1183         signal.Notify(sigusr1, syscall.SIGUSR1)
1184         defer signal.Stop(sigusr1)
1185
1186         saveAtTime := time.Now().Add(crunchLogUpdatePeriod)
1187         saveAtSize := crunchLogUpdateSize
1188         var savedSize int64
1189         for {
1190                 select {
1191                 case <-ticker.C:
1192                 case <-sigusr1:
1193                         saveAtTime = time.Now()
1194                 }
1195                 runner.logMtx.Lock()
1196                 done := runner.LogsPDH != nil
1197                 runner.logMtx.Unlock()
1198                 if done {
1199                         return
1200                 }
1201                 size := runner.LogCollection.Size()
1202                 if size == savedSize || (time.Now().Before(saveAtTime) && size < saveAtSize) {
1203                         continue
1204                 }
1205                 saveAtTime = time.Now().Add(crunchLogUpdatePeriod)
1206                 saveAtSize = runner.LogCollection.Size() + crunchLogUpdateSize
1207                 saved, err := runner.saveLogCollection(false)
1208                 if err != nil {
1209                         runner.CrunchLog.Printf("error updating log collection: %s", err)
1210                         continue
1211                 }
1212
1213                 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1214                         "select": []string{"uuid"},
1215                         "container": arvadosclient.Dict{
1216                                 "log": saved.PortableDataHash,
1217                         },
1218                 }, nil)
1219                 if err != nil {
1220                         runner.CrunchLog.Printf("error updating container log to %s: %s", saved.PortableDataHash, err)
1221                         continue
1222                 }
1223
1224                 savedSize = size
1225         }
1226 }
1227
1228 var spotInterruptionCheckInterval = 5 * time.Second
1229 var ec2MetadataBaseURL = "http://169.254.169.254"
1230
1231 const ec2TokenTTL = time.Second * 21600
1232
1233 func (runner *ContainerRunner) checkSpotInterruptionNotices() {
1234         type ec2metadata struct {
1235                 Action string    `json:"action"`
1236                 Time   time.Time `json:"time"`
1237         }
1238         runner.CrunchLog.Printf("Checking for spot interruptions every %v using instance metadata at %s", spotInterruptionCheckInterval, ec2MetadataBaseURL)
1239         var metadata ec2metadata
1240         var token string
1241         var tokenExp time.Time
1242         check := func() error {
1243                 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute))
1244                 defer cancel()
1245                 if token == "" || tokenExp.Sub(time.Now()) < time.Minute {
1246                         req, err := http.NewRequestWithContext(ctx, http.MethodPut, ec2MetadataBaseURL+"/latest/api/token", nil)
1247                         if err != nil {
1248                                 return err
1249                         }
1250                         req.Header.Set("X-aws-ec2-metadata-token-ttl-seconds", fmt.Sprintf("%d", int(ec2TokenTTL/time.Second)))
1251                         resp, err := http.DefaultClient.Do(req)
1252                         if err != nil {
1253                                 return err
1254                         }
1255                         defer resp.Body.Close()
1256                         if resp.StatusCode != http.StatusOK {
1257                                 return fmt.Errorf("%s", resp.Status)
1258                         }
1259                         newtoken, err := ioutil.ReadAll(resp.Body)
1260                         if err != nil {
1261                                 return err
1262                         }
1263                         token = strings.TrimSpace(string(newtoken))
1264                         tokenExp = time.Now().Add(ec2TokenTTL)
1265                 }
1266                 req, err := http.NewRequestWithContext(ctx, http.MethodGet, ec2MetadataBaseURL+"/latest/meta-data/spot/instance-action", nil)
1267                 if err != nil {
1268                         return err
1269                 }
1270                 req.Header.Set("X-aws-ec2-metadata-token", token)
1271                 resp, err := http.DefaultClient.Do(req)
1272                 if err != nil {
1273                         return err
1274                 }
1275                 defer resp.Body.Close()
1276                 metadata = ec2metadata{}
1277                 switch resp.StatusCode {
1278                 case http.StatusOK:
1279                         break
1280                 case http.StatusNotFound:
1281                         // "If Amazon EC2 is not preparing to stop or
1282                         // terminate the instance, or if you
1283                         // terminated the instance yourself,
1284                         // instance-action is not present in the
1285                         // instance metadata and you receive an HTTP
1286                         // 404 error when you try to retrieve it."
1287                         return nil
1288                 case http.StatusUnauthorized:
1289                         token = ""
1290                         return fmt.Errorf("%s", resp.Status)
1291                 default:
1292                         return fmt.Errorf("%s", resp.Status)
1293                 }
1294                 err = json.NewDecoder(resp.Body).Decode(&metadata)
1295                 if err != nil {
1296                         return err
1297                 }
1298                 return nil
1299         }
1300         failures := 0
1301         var lastmetadata ec2metadata
1302         for range time.NewTicker(spotInterruptionCheckInterval).C {
1303                 err := check()
1304                 if err != nil {
1305                         runner.CrunchLog.Printf("Error checking spot interruptions: %s", err)
1306                         failures++
1307                         if failures > 5 {
1308                                 runner.CrunchLog.Printf("Giving up on checking spot interruptions after too many consecutive failures")
1309                                 return
1310                         }
1311                         continue
1312                 }
1313                 failures = 0
1314                 if metadata != lastmetadata {
1315                         lastmetadata = metadata
1316                         text := fmt.Sprintf("Cloud provider scheduled instance %s at %s", metadata.Action, metadata.Time.UTC().Format(time.RFC3339))
1317                         runner.CrunchLog.Printf("%s", text)
1318                         runner.updateRuntimeStatus(arvadosclient.Dict{
1319                                 "warning":          "preemption notice",
1320                                 "warningDetail":    text,
1321                                 "preemptionNotice": text,
1322                         })
1323                         if proc, err := os.FindProcess(os.Getpid()); err == nil {
1324                                 // trigger updateLogs
1325                                 proc.Signal(syscall.SIGUSR1)
1326                         }
1327                 }
1328         }
1329 }
1330
1331 func (runner *ContainerRunner) updateRuntimeStatus(status arvadosclient.Dict) {
1332         err := runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1333                 "select": []string{"uuid"},
1334                 "container": arvadosclient.Dict{
1335                         "runtime_status": status,
1336                 },
1337         }, nil)
1338         if err != nil {
1339                 runner.CrunchLog.Printf("error updating container runtime_status: %s", err)
1340         }
1341 }
1342
1343 // CaptureOutput saves data from the container's output directory if
1344 // needed, and updates the container output accordingly.
1345 func (runner *ContainerRunner) CaptureOutput(bindmounts map[string]bindmount) error {
1346         if runner.Container.RuntimeConstraints.API {
1347                 // Output may have been set directly by the container, so
1348                 // refresh the container record to check.
1349                 err := runner.DispatcherArvClient.Get("containers", runner.Container.UUID,
1350                         arvadosclient.Dict{
1351                                 "select": []string{"output"},
1352                         }, &runner.Container)
1353                 if err != nil {
1354                         return err
1355                 }
1356                 if runner.Container.Output != "" {
1357                         // Container output is already set.
1358                         runner.OutputPDH = &runner.Container.Output
1359                         return nil
1360                 }
1361         }
1362
1363         txt, err := (&copier{
1364                 client:        runner.containerClient,
1365                 keepClient:    runner.ContainerKeepClient,
1366                 hostOutputDir: runner.HostOutputDir,
1367                 ctrOutputDir:  runner.Container.OutputPath,
1368                 bindmounts:    bindmounts,
1369                 mounts:        runner.Container.Mounts,
1370                 secretMounts:  runner.SecretMounts,
1371                 logger:        runner.CrunchLog,
1372         }).Copy()
1373         if err != nil {
1374                 return err
1375         }
1376         if n := len(regexp.MustCompile(` [0-9a-f]+\+\S*\+R`).FindAllStringIndex(txt, -1)); n > 0 {
1377                 runner.CrunchLog.Printf("Copying %d data blocks from remote input collections...", n)
1378                 fs, err := (&arvados.Collection{ManifestText: txt}).FileSystem(runner.containerClient, runner.ContainerKeepClient)
1379                 if err != nil {
1380                         return err
1381                 }
1382                 txt, err = fs.MarshalManifest(".")
1383                 if err != nil {
1384                         return err
1385                 }
1386         }
1387         var resp arvados.Collection
1388         err = runner.ContainerArvClient.Create("collections", arvadosclient.Dict{
1389                 "ensure_unique_name": true,
1390                 "select":             []string{"portable_data_hash"},
1391                 "collection": arvadosclient.Dict{
1392                         "is_trashed":    true,
1393                         "name":          "output for " + runner.Container.UUID,
1394                         "manifest_text": txt,
1395                 },
1396         }, &resp)
1397         if err != nil {
1398                 return fmt.Errorf("error creating output collection: %v", err)
1399         }
1400         runner.OutputPDH = &resp.PortableDataHash
1401         return nil
1402 }
1403
1404 func (runner *ContainerRunner) CleanupDirs() {
1405         if runner.ArvMount != nil {
1406                 var delay int64 = 8
1407                 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1408                 umount.Stdout = runner.CrunchLog
1409                 umount.Stderr = runner.CrunchLog
1410                 runner.CrunchLog.Printf("Running %v", umount.Args)
1411                 umnterr := umount.Start()
1412
1413                 if umnterr != nil {
1414                         runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1415                         runner.ArvMount.Process.Kill()
1416                 } else {
1417                         // If arv-mount --unmount gets stuck for any reason, we
1418                         // don't want to wait for it forever.  Do Wait() in a goroutine
1419                         // so it doesn't block crunch-run.
1420                         umountExit := make(chan error)
1421                         go func() {
1422                                 mnterr := umount.Wait()
1423                                 if mnterr != nil {
1424                                         runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1425                                 }
1426                                 umountExit <- mnterr
1427                         }()
1428
1429                         for again := true; again; {
1430                                 again = false
1431                                 select {
1432                                 case <-umountExit:
1433                                         umount = nil
1434                                         again = true
1435                                 case <-runner.ArvMountExit:
1436                                         break
1437                                 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1438                                         runner.CrunchLog.Printf("Timed out waiting for unmount")
1439                                         if umount != nil {
1440                                                 umount.Process.Kill()
1441                                         }
1442                                         runner.ArvMount.Process.Kill()
1443                                 }
1444                         }
1445                 }
1446                 runner.ArvMount = nil
1447         }
1448
1449         if runner.ArvMountPoint != "" {
1450                 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1451                         runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1452                 }
1453                 runner.ArvMountPoint = ""
1454         }
1455
1456         if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1457                 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1458         }
1459 }
1460
1461 // CommitLogs posts the collection containing the final container logs.
1462 func (runner *ContainerRunner) CommitLogs() error {
1463         func() {
1464                 // Hold cStateLock to prevent races on CrunchLog (e.g., stop()).
1465                 runner.cStateLock.Lock()
1466                 defer runner.cStateLock.Unlock()
1467
1468                 runner.CrunchLog.Print(runner.finalState)
1469
1470                 if runner.arvMountLog != nil {
1471                         runner.arvMountLog.Close()
1472                 }
1473                 runner.CrunchLog.Close()
1474
1475                 // Closing CrunchLog above allows them to be committed to Keep at this
1476                 // point, but re-open crunch log with ArvClient in case there are any
1477                 // other further errors (such as failing to write the log to Keep!)
1478                 // while shutting down
1479                 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{
1480                         ArvClient:     runner.DispatcherArvClient,
1481                         UUID:          runner.Container.UUID,
1482                         loggingStream: "crunch-run",
1483                         writeCloser:   nil,
1484                 })
1485                 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1486         }()
1487
1488         if runner.keepstoreLogger != nil {
1489                 // Flush any buffered logs from our local keepstore
1490                 // process.  Discard anything logged after this point
1491                 // -- it won't end up in the log collection, so
1492                 // there's no point writing it to the collectionfs.
1493                 runner.keepstoreLogbuf.SetWriter(io.Discard)
1494                 runner.keepstoreLogger.Close()
1495                 runner.keepstoreLogger = nil
1496         }
1497
1498         if runner.LogsPDH != nil {
1499                 // If we have already assigned something to LogsPDH,
1500                 // we must be closing the re-opened log, which won't
1501                 // end up getting attached to the container record and
1502                 // therefore doesn't need to be saved as a collection
1503                 // -- it exists only to send logs to other channels.
1504                 return nil
1505         }
1506
1507         saved, err := runner.saveLogCollection(true)
1508         if err != nil {
1509                 return fmt.Errorf("error saving log collection: %s", err)
1510         }
1511         runner.logMtx.Lock()
1512         defer runner.logMtx.Unlock()
1513         runner.LogsPDH = &saved.PortableDataHash
1514         return nil
1515 }
1516
1517 // Create/update the log collection. Return value has UUID and
1518 // PortableDataHash fields populated, but others may be blank.
1519 func (runner *ContainerRunner) saveLogCollection(final bool) (response arvados.Collection, err error) {
1520         runner.logMtx.Lock()
1521         defer runner.logMtx.Unlock()
1522         if runner.LogsPDH != nil {
1523                 // Already finalized.
1524                 return
1525         }
1526         updates := arvadosclient.Dict{
1527                 "name": "logs for " + runner.Container.UUID,
1528         }
1529         mt, err1 := runner.LogCollection.MarshalManifest(".")
1530         if err1 == nil {
1531                 // Only send updated manifest text if there was no
1532                 // error.
1533                 updates["manifest_text"] = mt
1534         }
1535
1536         // Even if flushing the manifest had an error, we still want
1537         // to update the log record, if possible, to push the trash_at
1538         // and delete_at times into the future.  Details on bug
1539         // #17293.
1540         if final {
1541                 updates["is_trashed"] = true
1542         } else {
1543                 // We set trash_at so this collection gets
1544                 // automatically cleaned up eventually.  It used to be
1545                 // 12 hours but we had a situation where the API
1546                 // server was down over a weekend but the containers
1547                 // kept running such that the log collection got
1548                 // trashed, so now we make it 2 weeks.  refs #20378
1549                 exp := time.Now().Add(time.Duration(24*14) * time.Hour)
1550                 updates["trash_at"] = exp
1551                 updates["delete_at"] = exp
1552         }
1553         reqBody := arvadosclient.Dict{
1554                 "select":     []string{"uuid", "portable_data_hash"},
1555                 "collection": updates,
1556         }
1557         var err2 error
1558         if runner.logUUID == "" {
1559                 reqBody["ensure_unique_name"] = true
1560                 err2 = runner.DispatcherArvClient.Create("collections", reqBody, &response)
1561         } else {
1562                 err2 = runner.DispatcherArvClient.Update("collections", runner.logUUID, reqBody, &response)
1563         }
1564         if err2 == nil {
1565                 runner.logUUID = response.UUID
1566         }
1567
1568         if err1 != nil || err2 != nil {
1569                 err = fmt.Errorf("error recording logs: %q, %q", err1, err2)
1570         }
1571         return
1572 }
1573
1574 // UpdateContainerRunning updates the container state to "Running"
1575 func (runner *ContainerRunner) UpdateContainerRunning(logId string) error {
1576         runner.cStateLock.Lock()
1577         defer runner.cStateLock.Unlock()
1578         if runner.cCancelled {
1579                 return ErrCancelled
1580         }
1581         updates := arvadosclient.Dict{
1582                 "gateway_address": runner.gateway.Address,
1583                 "state":           "Running",
1584         }
1585         if logId != "" {
1586                 updates["log"] = logId
1587         }
1588         return runner.DispatcherArvClient.Update(
1589                 "containers",
1590                 runner.Container.UUID,
1591                 arvadosclient.Dict{
1592                         "select":    []string{"uuid"},
1593                         "container": updates,
1594                 },
1595                 nil,
1596         )
1597 }
1598
1599 // ContainerToken returns the api_token the container (and any
1600 // arv-mount processes) are allowed to use.
1601 func (runner *ContainerRunner) ContainerToken() (string, error) {
1602         if runner.token != "" {
1603                 return runner.token, nil
1604         }
1605
1606         var auth arvados.APIClientAuthorization
1607         err := runner.DispatcherArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1608         if err != nil {
1609                 return "", err
1610         }
1611         runner.token = fmt.Sprintf("v2/%s/%s/%s", auth.UUID, auth.APIToken, runner.Container.UUID)
1612         return runner.token, nil
1613 }
1614
1615 // UpdateContainerFinal updates the container record state on API
1616 // server to "Complete" or "Cancelled"
1617 func (runner *ContainerRunner) UpdateContainerFinal() error {
1618         update := arvadosclient.Dict{}
1619         update["state"] = runner.finalState
1620         if runner.LogsPDH != nil {
1621                 update["log"] = *runner.LogsPDH
1622         }
1623         if runner.ExitCode != nil {
1624                 update["exit_code"] = *runner.ExitCode
1625         } else {
1626                 update["exit_code"] = nil
1627         }
1628         if runner.finalState == "Complete" && runner.OutputPDH != nil {
1629                 update["output"] = *runner.OutputPDH
1630         }
1631         update["cost"] = runner.calculateCost(time.Now())
1632         return runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1633                 "select":    []string{"uuid"},
1634                 "container": update,
1635         }, nil)
1636 }
1637
1638 // IsCancelled returns the value of Cancelled, with goroutine safety.
1639 func (runner *ContainerRunner) IsCancelled() bool {
1640         runner.cStateLock.Lock()
1641         defer runner.cStateLock.Unlock()
1642         return runner.cCancelled
1643 }
1644
1645 // NewArvLogWriter creates an ArvLogWriter
1646 func (runner *ContainerRunner) NewArvLogWriter(name string) (io.WriteCloser, error) {
1647         writer, err := runner.LogCollection.OpenFile(name+".txt", os.O_CREATE|os.O_WRONLY, 0666)
1648         if err != nil {
1649                 return nil, err
1650         }
1651         return &ArvLogWriter{
1652                 ArvClient:     runner.DispatcherArvClient,
1653                 UUID:          runner.Container.UUID,
1654                 loggingStream: name,
1655                 writeCloser:   writer,
1656         }, nil
1657 }
1658
1659 // Run the full container lifecycle.
1660 func (runner *ContainerRunner) Run() (err error) {
1661         runner.CrunchLog.Printf("crunch-run %s started", cmd.Version.String())
1662         runner.CrunchLog.Printf("%s", currentUserAndGroups())
1663         v, _ := exec.Command("arv-mount", "--version").CombinedOutput()
1664         runner.CrunchLog.Printf("Using FUSE mount: %s", v)
1665         runner.CrunchLog.Printf("Using container runtime: %s", runner.executor.Runtime())
1666         runner.CrunchLog.Printf("Executing container: %s", runner.Container.UUID)
1667         runner.costStartTime = time.Now()
1668
1669         hostname, hosterr := os.Hostname()
1670         if hosterr != nil {
1671                 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1672         } else {
1673                 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1674         }
1675
1676         sigusr2 := make(chan os.Signal, 1)
1677         signal.Notify(sigusr2, syscall.SIGUSR2)
1678         defer signal.Stop(sigusr2)
1679         runner.loadPrices()
1680         go runner.handleSIGUSR2(sigusr2)
1681
1682         runner.finalState = "Queued"
1683
1684         defer func() {
1685                 runner.CleanupDirs()
1686
1687                 runner.CrunchLog.Printf("crunch-run finished")
1688                 runner.CrunchLog.Close()
1689         }()
1690
1691         err = runner.fetchContainerRecord()
1692         if err != nil {
1693                 return
1694         }
1695         if runner.Container.State != "Locked" {
1696                 return fmt.Errorf("dispatch error detected: container %q has state %q", runner.Container.UUID, runner.Container.State)
1697         }
1698
1699         var bindmounts map[string]bindmount
1700         defer func() {
1701                 // checkErr prints e (unless it's nil) and sets err to
1702                 // e (unless err is already non-nil). Thus, if err
1703                 // hasn't already been assigned when Run() returns,
1704                 // this cleanup func will cause Run() to return the
1705                 // first non-nil error that is passed to checkErr().
1706                 checkErr := func(errorIn string, e error) {
1707                         if e == nil {
1708                                 return
1709                         }
1710                         runner.CrunchLog.Printf("error in %s: %v", errorIn, e)
1711                         if err == nil {
1712                                 err = e
1713                         }
1714                         if runner.finalState == "Complete" {
1715                                 // There was an error in the finalization.
1716                                 runner.finalState = "Cancelled"
1717                         }
1718                 }
1719
1720                 // Log the error encountered in Run(), if any
1721                 checkErr("Run", err)
1722
1723                 if runner.finalState == "Queued" {
1724                         runner.UpdateContainerFinal()
1725                         return
1726                 }
1727
1728                 if runner.IsCancelled() {
1729                         runner.finalState = "Cancelled"
1730                         // but don't return yet -- we still want to
1731                         // capture partial output and write logs
1732                 }
1733
1734                 if bindmounts != nil {
1735                         checkErr("CaptureOutput", runner.CaptureOutput(bindmounts))
1736                 }
1737                 checkErr("stopHoststat", runner.stopHoststat())
1738                 checkErr("CommitLogs", runner.CommitLogs())
1739                 runner.CleanupDirs()
1740                 checkErr("UpdateContainerFinal", runner.UpdateContainerFinal())
1741         }()
1742
1743         runner.setupSignals()
1744         err = runner.startHoststat()
1745         if err != nil {
1746                 return
1747         }
1748         if runner.keepstore != nil {
1749                 runner.hoststatReporter.ReportPID("keepstore", runner.keepstore.Process.Pid)
1750         }
1751
1752         // set up FUSE mount and binds
1753         bindmounts, err = runner.SetupMounts()
1754         if err != nil {
1755                 runner.finalState = "Cancelled"
1756                 err = fmt.Errorf("While setting up mounts: %v", err)
1757                 return
1758         }
1759
1760         // check for and/or load image
1761         imageID, err := runner.LoadImage()
1762         if err != nil {
1763                 if !runner.checkBrokenNode(err) {
1764                         // Failed to load image but not due to a "broken node"
1765                         // condition, probably user error.
1766                         runner.finalState = "Cancelled"
1767                 }
1768                 err = fmt.Errorf("While loading container image: %v", err)
1769                 return
1770         }
1771
1772         err = runner.CreateContainer(imageID, bindmounts)
1773         if err != nil {
1774                 return
1775         }
1776         err = runner.LogHostInfo()
1777         if err != nil {
1778                 return
1779         }
1780         err = runner.LogNodeRecord()
1781         if err != nil {
1782                 return
1783         }
1784         err = runner.LogContainerRecord()
1785         if err != nil {
1786                 return
1787         }
1788
1789         if runner.IsCancelled() {
1790                 return
1791         }
1792
1793         logCollection, err := runner.saveLogCollection(false)
1794         var logId string
1795         if err == nil {
1796                 logId = logCollection.PortableDataHash
1797         } else {
1798                 runner.CrunchLog.Printf("Error committing initial log collection: %v", err)
1799         }
1800         err = runner.UpdateContainerRunning(logId)
1801         if err != nil {
1802                 return
1803         }
1804         runner.finalState = "Cancelled"
1805
1806         err = runner.startCrunchstat()
1807         if err != nil {
1808                 return
1809         }
1810
1811         err = runner.StartContainer()
1812         if err != nil {
1813                 runner.checkBrokenNode(err)
1814                 return
1815         }
1816
1817         err = runner.WaitFinish()
1818         if err == nil && !runner.IsCancelled() {
1819                 runner.finalState = "Complete"
1820         }
1821         return
1822 }
1823
1824 // Fetch the current container record (uuid = runner.Container.UUID)
1825 // into runner.Container.
1826 func (runner *ContainerRunner) fetchContainerRecord() error {
1827         reader, err := runner.DispatcherArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1828         if err != nil {
1829                 return fmt.Errorf("error fetching container record: %v", err)
1830         }
1831         defer reader.Close()
1832
1833         dec := json.NewDecoder(reader)
1834         dec.UseNumber()
1835         err = dec.Decode(&runner.Container)
1836         if err != nil {
1837                 return fmt.Errorf("error decoding container record: %v", err)
1838         }
1839
1840         var sm struct {
1841                 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
1842         }
1843
1844         containerToken, err := runner.ContainerToken()
1845         if err != nil {
1846                 return fmt.Errorf("error getting container token: %v", err)
1847         }
1848
1849         runner.ContainerArvClient, runner.ContainerKeepClient,
1850                 runner.containerClient, err = runner.MkArvClient(containerToken)
1851         if err != nil {
1852                 return fmt.Errorf("error creating container API client: %v", err)
1853         }
1854
1855         runner.ContainerKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1856         runner.DispatcherKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1857
1858         err = runner.ContainerArvClient.Call("GET", "containers", runner.Container.UUID, "secret_mounts", nil, &sm)
1859         if err != nil {
1860                 if apierr, ok := err.(arvadosclient.APIServerError); !ok || apierr.HttpStatusCode != 404 {
1861                         return fmt.Errorf("error fetching secret_mounts: %v", err)
1862                 }
1863                 // ok && apierr.HttpStatusCode == 404, which means
1864                 // secret_mounts isn't supported by this API server.
1865         }
1866         runner.SecretMounts = sm.SecretMounts
1867
1868         return nil
1869 }
1870
1871 // NewContainerRunner creates a new container runner.
1872 func NewContainerRunner(dispatcherClient *arvados.Client,
1873         dispatcherArvClient IArvadosClient,
1874         dispatcherKeepClient IKeepClient,
1875         containerUUID string) (*ContainerRunner, error) {
1876
1877         cr := &ContainerRunner{
1878                 dispatcherClient:     dispatcherClient,
1879                 DispatcherArvClient:  dispatcherArvClient,
1880                 DispatcherKeepClient: dispatcherKeepClient,
1881         }
1882         cr.NewLogWriter = cr.NewArvLogWriter
1883         cr.RunArvMount = cr.ArvMountCmd
1884         cr.MkTempDir = ioutil.TempDir
1885         cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1886                 cl, err := arvadosclient.MakeArvadosClient()
1887                 if err != nil {
1888                         return nil, nil, nil, err
1889                 }
1890                 cl.ApiToken = token
1891                 kc, err := keepclient.MakeKeepClient(cl)
1892                 if err != nil {
1893                         return nil, nil, nil, err
1894                 }
1895                 c2 := arvados.NewClientFromEnv()
1896                 c2.AuthToken = token
1897                 return cl, kc, c2, nil
1898         }
1899         var err error
1900         cr.LogCollection, err = (&arvados.Collection{}).FileSystem(cr.dispatcherClient, cr.DispatcherKeepClient)
1901         if err != nil {
1902                 return nil, err
1903         }
1904         cr.Container.UUID = containerUUID
1905         w, err := cr.NewLogWriter("crunch-run")
1906         if err != nil {
1907                 return nil, err
1908         }
1909         cr.CrunchLog = NewThrottledLogger(w)
1910         cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1911
1912         loadLogThrottleParams(dispatcherArvClient)
1913         go cr.updateLogs()
1914
1915         return cr, nil
1916 }
1917
1918 func (command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
1919         log := log.New(stderr, "", 0)
1920         flags := flag.NewFlagSet(prog, flag.ContinueOnError)
1921         statInterval := flags.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1922         flags.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree (obsolete, ignored)")
1923         flags.String("cgroup-parent", "docker", "name of container's parent cgroup (obsolete, ignored)")
1924         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")
1925         caCertsPath := flags.String("ca-certs", "", "Path to TLS root certificates")
1926         detach := flags.Bool("detach", false, "Detach from parent process and run in the background")
1927         stdinConfig := flags.Bool("stdin-config", false, "Load config and environment variables from JSON message on stdin")
1928         configFile := flags.String("config", arvados.DefaultConfigFile, "filename of cluster config file to try loading if -stdin-config=false (default is $ARVADOS_CONFIG)")
1929         sleep := flags.Duration("sleep", 0, "Delay before starting (testing use only)")
1930         kill := flags.Int("kill", -1, "Send signal to an existing crunch-run process for given UUID")
1931         list := flags.Bool("list", false, "List UUIDs of existing crunch-run processes (and notify them to use price data passed on stdin)")
1932         enableMemoryLimit := flags.Bool("enable-memory-limit", true, "tell container runtime to limit container's memory usage")
1933         enableNetwork := flags.String("container-enable-networking", "default", "enable networking \"always\" (for all containers) or \"default\" (for containers that request it)")
1934         networkMode := flags.String("container-network-mode", "default", `Docker network mode for container (use any argument valid for docker --net)`)
1935         memprofile := flags.String("memprofile", "", "write memory profile to `file` after running container")
1936         runtimeEngine := flags.String("runtime-engine", "docker", "container runtime: docker or singularity")
1937         brokenNodeHook := flags.String("broken-node-hook", "", "script to run if node is detected to be broken (for example, Docker daemon is not running)")
1938         flags.Duration("check-containerd", 0, "Ignored. Exists for compatibility with older versions.")
1939         version := flags.Bool("version", false, "Write version information to stdout and exit 0.")
1940
1941         ignoreDetachFlag := false
1942         if len(args) > 0 && args[0] == "-no-detach" {
1943                 // This process was invoked by a parent process, which
1944                 // has passed along its own arguments, including
1945                 // -detach, after the leading -no-detach flag.  Strip
1946                 // the leading -no-detach flag (it's not recognized by
1947                 // flags.Parse()) and ignore the -detach flag that
1948                 // comes later.
1949                 args = args[1:]
1950                 ignoreDetachFlag = true
1951         }
1952
1953         if ok, code := cmd.ParseFlags(flags, prog, args, "container-uuid", stderr); !ok {
1954                 return code
1955         } else if *version {
1956                 fmt.Fprintln(stdout, prog, cmd.Version.String())
1957                 return 0
1958         } else if !*list && flags.NArg() != 1 {
1959                 fmt.Fprintf(stderr, "missing required argument: container-uuid (try -help)\n")
1960                 return 2
1961         }
1962
1963         containerUUID := flags.Arg(0)
1964
1965         switch {
1966         case *detach && !ignoreDetachFlag:
1967                 return Detach(containerUUID, prog, args, stdin, stdout, stderr)
1968         case *kill >= 0:
1969                 return KillProcess(containerUUID, syscall.Signal(*kill), stdout, stderr)
1970         case *list:
1971                 return ListProcesses(stdin, stdout, stderr)
1972         }
1973
1974         if len(containerUUID) != 27 {
1975                 log.Printf("usage: %s [options] UUID", prog)
1976                 return 1
1977         }
1978
1979         var keepstoreLogbuf bufThenWrite
1980         var conf ConfigData
1981         if *stdinConfig {
1982                 err := json.NewDecoder(stdin).Decode(&conf)
1983                 if err != nil {
1984                         log.Printf("decode stdin: %s", err)
1985                         return 1
1986                 }
1987                 for k, v := range conf.Env {
1988                         err = os.Setenv(k, v)
1989                         if err != nil {
1990                                 log.Printf("setenv(%q): %s", k, err)
1991                                 return 1
1992                         }
1993                 }
1994                 if conf.Cluster != nil {
1995                         // ClusterID is missing from the JSON
1996                         // representation, but we need it to generate
1997                         // a valid config file for keepstore, so we
1998                         // fill it using the container UUID prefix.
1999                         conf.Cluster.ClusterID = containerUUID[:5]
2000                 }
2001         } else {
2002                 conf = hpcConfData(containerUUID, *configFile, io.MultiWriter(&keepstoreLogbuf, stderr))
2003         }
2004
2005         log.Printf("crunch-run %s started", cmd.Version.String())
2006         time.Sleep(*sleep)
2007
2008         if *caCertsPath != "" {
2009                 os.Setenv("SSL_CERT_FILE", *caCertsPath)
2010         }
2011
2012         keepstore, err := startLocalKeepstore(conf, io.MultiWriter(&keepstoreLogbuf, stderr))
2013         if err != nil {
2014                 log.Print(err)
2015                 return 1
2016         }
2017         if keepstore != nil {
2018                 defer keepstore.Process.Kill()
2019         }
2020
2021         api, err := arvadosclient.MakeArvadosClient()
2022         if err != nil {
2023                 log.Printf("%s: %v", containerUUID, err)
2024                 return 1
2025         }
2026         // arvadosclient now interprets Retries=10 to mean
2027         // Timeout=10m, retrying with exponential backoff + jitter.
2028         api.Retries = 10
2029
2030         kc, err := keepclient.MakeKeepClient(api)
2031         if err != nil {
2032                 log.Printf("%s: %v", containerUUID, err)
2033                 return 1
2034         }
2035         kc.Retries = 4
2036
2037         cr, err := NewContainerRunner(arvados.NewClientFromEnv(), api, kc, containerUUID)
2038         if err != nil {
2039                 log.Print(err)
2040                 return 1
2041         }
2042
2043         cr.keepstore = keepstore
2044         if keepstore == nil {
2045                 // Log explanation (if any) for why we're not running
2046                 // a local keepstore.
2047                 var buf bytes.Buffer
2048                 keepstoreLogbuf.SetWriter(&buf)
2049                 if buf.Len() > 0 {
2050                         cr.CrunchLog.Printf("%s", strings.TrimSpace(buf.String()))
2051                 }
2052         } else if logWhat := conf.Cluster.Containers.LocalKeepLogsToContainerLog; logWhat == "none" {
2053                 cr.CrunchLog.Printf("using local keepstore process (pid %d) at %s", keepstore.Process.Pid, os.Getenv("ARVADOS_KEEP_SERVICES"))
2054                 keepstoreLogbuf.SetWriter(io.Discard)
2055         } else {
2056                 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"))
2057                 logwriter, err := cr.NewLogWriter("keepstore")
2058                 if err != nil {
2059                         log.Print(err)
2060                         return 1
2061                 }
2062                 cr.keepstoreLogger = NewThrottledLogger(logwriter)
2063
2064                 var writer io.WriteCloser = cr.keepstoreLogger
2065                 if logWhat == "errors" {
2066                         writer = &filterKeepstoreErrorsOnly{WriteCloser: writer}
2067                 } else if logWhat != "all" {
2068                         // should have been caught earlier by
2069                         // dispatcher's config loader
2070                         log.Printf("invalid value for Containers.LocalKeepLogsToContainerLog: %q", logWhat)
2071                         return 1
2072                 }
2073                 err = keepstoreLogbuf.SetWriter(writer)
2074                 if err != nil {
2075                         log.Print(err)
2076                         return 1
2077                 }
2078                 cr.keepstoreLogbuf = &keepstoreLogbuf
2079         }
2080
2081         switch *runtimeEngine {
2082         case "docker":
2083                 cr.executor, err = newDockerExecutor(containerUUID, cr.CrunchLog.Printf, cr.containerWatchdogInterval)
2084         case "singularity":
2085                 cr.executor, err = newSingularityExecutor(cr.CrunchLog.Printf)
2086         default:
2087                 cr.CrunchLog.Printf("%s: unsupported RuntimeEngine %q", containerUUID, *runtimeEngine)
2088                 cr.CrunchLog.Close()
2089                 return 1
2090         }
2091         if err != nil {
2092                 cr.CrunchLog.Printf("%s: %v", containerUUID, err)
2093                 cr.checkBrokenNode(err)
2094                 cr.CrunchLog.Close()
2095                 return 1
2096         }
2097         defer cr.executor.Close()
2098
2099         cr.brokenNodeHook = *brokenNodeHook
2100
2101         gwAuthSecret := os.Getenv("GatewayAuthSecret")
2102         os.Unsetenv("GatewayAuthSecret")
2103         if gwAuthSecret == "" {
2104                 // not safe to run a gateway service without an auth
2105                 // secret
2106                 cr.CrunchLog.Printf("Not starting a gateway server (GatewayAuthSecret was not provided by dispatcher)")
2107         } else {
2108                 gwListen := os.Getenv("GatewayAddress")
2109                 cr.gateway = Gateway{
2110                         Address:       gwListen,
2111                         AuthSecret:    gwAuthSecret,
2112                         ContainerUUID: containerUUID,
2113                         Target:        cr.executor,
2114                         Log:           cr.CrunchLog,
2115                         LogCollection: cr.LogCollection,
2116                 }
2117                 if gwListen == "" {
2118                         // Direct connection won't work, so we use the
2119                         // gateway_address field to indicate the
2120                         // internalURL of the controller process that
2121                         // has the current tunnel connection.
2122                         cr.gateway.ArvadosClient = cr.dispatcherClient
2123                         cr.gateway.UpdateTunnelURL = func(url string) {
2124                                 cr.gateway.Address = "tunnel " + url
2125                                 cr.DispatcherArvClient.Update("containers", containerUUID,
2126                                         arvadosclient.Dict{
2127                                                 "select":    []string{"uuid"},
2128                                                 "container": arvadosclient.Dict{"gateway_address": cr.gateway.Address},
2129                                         }, nil)
2130                         }
2131                 }
2132                 err = cr.gateway.Start()
2133                 if err != nil {
2134                         log.Printf("error starting gateway server: %s", err)
2135                         return 1
2136                 }
2137         }
2138
2139         parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerUUID+".")
2140         if tmperr != nil {
2141                 log.Printf("%s: %v", containerUUID, tmperr)
2142                 return 1
2143         }
2144
2145         cr.parentTemp = parentTemp
2146         cr.statInterval = *statInterval
2147         cr.enableMemoryLimit = *enableMemoryLimit
2148         cr.enableNetwork = *enableNetwork
2149         cr.networkMode = *networkMode
2150         if *cgroupParentSubsystem != "" {
2151                 p, err := findCgroup(os.DirFS("/"), *cgroupParentSubsystem)
2152                 if err != nil {
2153                         log.Printf("fatal: cgroup parent subsystem: %s", err)
2154                         return 1
2155                 }
2156                 cr.setCgroupParent = p
2157         }
2158
2159         if conf.EC2SpotCheck {
2160                 go cr.checkSpotInterruptionNotices()
2161         }
2162
2163         runerr := cr.Run()
2164
2165         if *memprofile != "" {
2166                 f, err := os.Create(*memprofile)
2167                 if err != nil {
2168                         log.Printf("could not create memory profile: %s", err)
2169                 }
2170                 runtime.GC() // get up-to-date statistics
2171                 if err := pprof.WriteHeapProfile(f); err != nil {
2172                         log.Printf("could not write memory profile: %s", err)
2173                 }
2174                 closeerr := f.Close()
2175                 if closeerr != nil {
2176                         log.Printf("closing memprofile file: %s", err)
2177                 }
2178         }
2179
2180         if runerr != nil {
2181                 log.Printf("%s: %v", containerUUID, runerr)
2182                 return 1
2183         }
2184         return 0
2185 }
2186
2187 // Try to load ConfigData in hpc (slurm/lsf) environment. This means
2188 // loading the cluster config from the specified file and (if that
2189 // works) getting the runtime_constraints container field from
2190 // controller to determine # VCPUs so we can calculate KeepBuffers.
2191 func hpcConfData(uuid string, configFile string, stderr io.Writer) ConfigData {
2192         var conf ConfigData
2193         conf.Cluster = loadClusterConfigFile(configFile, stderr)
2194         if conf.Cluster == nil {
2195                 // skip loading the container record -- we won't be
2196                 // able to start local keepstore anyway.
2197                 return conf
2198         }
2199         arv, err := arvadosclient.MakeArvadosClient()
2200         if err != nil {
2201                 fmt.Fprintf(stderr, "error setting up arvadosclient: %s\n", err)
2202                 return conf
2203         }
2204         // arvadosclient now interprets Retries=10 to mean
2205         // Timeout=10m, retrying with exponential backoff + jitter.
2206         arv.Retries = 10
2207         var ctr arvados.Container
2208         err = arv.Call("GET", "containers", uuid, "", arvadosclient.Dict{"select": []string{"runtime_constraints"}}, &ctr)
2209         if err != nil {
2210                 fmt.Fprintf(stderr, "error getting container record: %s\n", err)
2211                 return conf
2212         }
2213         if ctr.RuntimeConstraints.VCPUs > 0 {
2214                 conf.KeepBuffers = ctr.RuntimeConstraints.VCPUs * conf.Cluster.Containers.LocalKeepBlobBuffersPerVCPU
2215         }
2216         return conf
2217 }
2218
2219 // Load cluster config file from given path. If an error occurs, log
2220 // the error to stderr and return nil.
2221 func loadClusterConfigFile(path string, stderr io.Writer) *arvados.Cluster {
2222         ldr := config.NewLoader(&bytes.Buffer{}, ctxlog.New(stderr, "plain", "info"))
2223         ldr.Path = path
2224         cfg, err := ldr.Load()
2225         if err != nil {
2226                 fmt.Fprintf(stderr, "could not load config file %s: %s\n", path, err)
2227                 return nil
2228         }
2229         cluster, err := cfg.GetCluster("")
2230         if err != nil {
2231                 fmt.Fprintf(stderr, "could not use config file %s: %s\n", path, err)
2232                 return nil
2233         }
2234         fmt.Fprintf(stderr, "loaded config file %s\n", path)
2235         return cluster
2236 }
2237
2238 func startLocalKeepstore(configData ConfigData, logbuf io.Writer) (*exec.Cmd, error) {
2239         if configData.KeepBuffers < 1 {
2240                 fmt.Fprintf(logbuf, "not starting a local keepstore process because KeepBuffers=%v in config\n", configData.KeepBuffers)
2241                 return nil, nil
2242         }
2243         if configData.Cluster == nil {
2244                 fmt.Fprint(logbuf, "not starting a local keepstore process because cluster config file was not loaded\n")
2245                 return nil, nil
2246         }
2247         for uuid, vol := range configData.Cluster.Volumes {
2248                 if len(vol.AccessViaHosts) > 0 {
2249                         fmt.Fprintf(logbuf, "not starting a local keepstore process because a volume (%s) uses AccessViaHosts\n", uuid)
2250                         return nil, nil
2251                 }
2252                 if !vol.ReadOnly && vol.Replication < configData.Cluster.Collections.DefaultReplication {
2253                         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)
2254                         return nil, nil
2255                 }
2256         }
2257
2258         // Rather than have an alternate way to tell keepstore how
2259         // many buffers to use, etc., when starting it this way, we
2260         // just modify the cluster configuration that we feed it on
2261         // stdin.
2262         ccfg := *configData.Cluster
2263         ccfg.API.MaxKeepBlobBuffers = configData.KeepBuffers
2264         ccfg.Collections.BlobTrash = false
2265         ccfg.Collections.BlobTrashConcurrency = 0
2266         ccfg.Collections.BlobDeleteConcurrency = 0
2267
2268         localaddr := localKeepstoreAddr()
2269         ln, err := net.Listen("tcp", net.JoinHostPort(localaddr, "0"))
2270         if err != nil {
2271                 return nil, err
2272         }
2273         _, port, err := net.SplitHostPort(ln.Addr().String())
2274         if err != nil {
2275                 ln.Close()
2276                 return nil, err
2277         }
2278         ln.Close()
2279         url := "http://" + net.JoinHostPort(localaddr, port)
2280
2281         fmt.Fprintf(logbuf, "starting keepstore on %s\n", url)
2282
2283         var confJSON bytes.Buffer
2284         err = json.NewEncoder(&confJSON).Encode(arvados.Config{
2285                 Clusters: map[string]arvados.Cluster{
2286                         ccfg.ClusterID: ccfg,
2287                 },
2288         })
2289         if err != nil {
2290                 return nil, err
2291         }
2292         cmd := exec.Command("/proc/self/exe", "keepstore", "-config=-")
2293         if target, err := os.Readlink(cmd.Path); err == nil && strings.HasSuffix(target, ".test") {
2294                 // If we're a 'go test' process, running
2295                 // /proc/self/exe would start the test suite in a
2296                 // child process, which is not what we want.
2297                 cmd.Path, _ = exec.LookPath("go")
2298                 cmd.Args = append([]string{"go", "run", "../../cmd/arvados-server"}, cmd.Args[1:]...)
2299                 cmd.Env = os.Environ()
2300         }
2301         cmd.Stdin = &confJSON
2302         cmd.Stdout = logbuf
2303         cmd.Stderr = logbuf
2304         cmd.Env = append(cmd.Env,
2305                 "GOGC=10",
2306                 "ARVADOS_SERVICE_INTERNAL_URL="+url)
2307         err = cmd.Start()
2308         if err != nil {
2309                 return nil, fmt.Errorf("error starting keepstore process: %w", err)
2310         }
2311         cmdExited := false
2312         go func() {
2313                 cmd.Wait()
2314                 cmdExited = true
2315         }()
2316         ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*10))
2317         defer cancel()
2318         poll := time.NewTicker(time.Second / 10)
2319         defer poll.Stop()
2320         client := http.Client{}
2321         for range poll.C {
2322                 testReq, err := http.NewRequestWithContext(ctx, "GET", url+"/_health/ping", nil)
2323                 testReq.Header.Set("Authorization", "Bearer "+configData.Cluster.ManagementToken)
2324                 if err != nil {
2325                         return nil, err
2326                 }
2327                 resp, err := client.Do(testReq)
2328                 if err == nil {
2329                         resp.Body.Close()
2330                         if resp.StatusCode == http.StatusOK {
2331                                 break
2332                         }
2333                 }
2334                 if cmdExited {
2335                         return nil, fmt.Errorf("keepstore child process exited")
2336                 }
2337                 if ctx.Err() != nil {
2338                         return nil, fmt.Errorf("timed out waiting for new keepstore process to report healthy")
2339                 }
2340         }
2341         os.Setenv("ARVADOS_KEEP_SERVICES", url)
2342         return cmd, nil
2343 }
2344
2345 // return current uid, gid, groups in a format suitable for logging:
2346 // "crunch-run process has uid=1234(arvados) gid=1234(arvados)
2347 // groups=1234(arvados),114(fuse)"
2348 func currentUserAndGroups() string {
2349         u, err := user.Current()
2350         if err != nil {
2351                 return fmt.Sprintf("error getting current user ID: %s", err)
2352         }
2353         s := fmt.Sprintf("crunch-run process has uid=%s(%s) gid=%s", u.Uid, u.Username, u.Gid)
2354         if g, err := user.LookupGroupId(u.Gid); err == nil {
2355                 s += fmt.Sprintf("(%s)", g.Name)
2356         }
2357         s += " groups="
2358         if gids, err := u.GroupIds(); err == nil {
2359                 for i, gid := range gids {
2360                         if i > 0 {
2361                                 s += ","
2362                         }
2363                         s += gid
2364                         if g, err := user.LookupGroupId(gid); err == nil {
2365                                 s += fmt.Sprintf("(%s)", g.Name)
2366                         }
2367                 }
2368         }
2369         return s
2370 }
2371
2372 // Return a suitable local interface address for a local keepstore
2373 // service. Currently this is the numerically lowest non-loopback ipv4
2374 // address assigned to a local interface that is not in any of the
2375 // link-local/vpn/loopback ranges 169.254/16, 100.64/10, or 127/8.
2376 func localKeepstoreAddr() string {
2377         var ips []net.IP
2378         // Ignore error (proceed with zero IPs)
2379         addrs, _ := processIPs(os.Getpid())
2380         for addr := range addrs {
2381                 ip := net.ParseIP(addr)
2382                 if ip == nil {
2383                         // invalid
2384                         continue
2385                 }
2386                 if ip.Mask(net.CIDRMask(8, 32)).Equal(net.IPv4(127, 0, 0, 0)) ||
2387                         ip.Mask(net.CIDRMask(10, 32)).Equal(net.IPv4(100, 64, 0, 0)) ||
2388                         ip.Mask(net.CIDRMask(16, 32)).Equal(net.IPv4(169, 254, 0, 0)) {
2389                         // unsuitable
2390                         continue
2391                 }
2392                 ips = append(ips, ip)
2393         }
2394         if len(ips) == 0 {
2395                 return "0.0.0.0"
2396         }
2397         sort.Slice(ips, func(ii, jj int) bool {
2398                 i, j := ips[ii], ips[jj]
2399                 if len(i) != len(j) {
2400                         return len(i) < len(j)
2401                 }
2402                 for x := range i {
2403                         if i[x] != j[x] {
2404                                 return i[x] < j[x]
2405                         }
2406                 }
2407                 return false
2408         })
2409         return ips[0].String()
2410 }
2411
2412 func (cr *ContainerRunner) loadPrices() {
2413         buf, err := os.ReadFile(filepath.Join(lockdir, pricesfile))
2414         if err != nil {
2415                 if !os.IsNotExist(err) {
2416                         cr.CrunchLog.Printf("loadPrices: read: %s", err)
2417                 }
2418                 return
2419         }
2420         var prices []cloud.InstancePrice
2421         err = json.Unmarshal(buf, &prices)
2422         if err != nil {
2423                 cr.CrunchLog.Printf("loadPrices: decode: %s", err)
2424                 return
2425         }
2426         cr.pricesLock.Lock()
2427         defer cr.pricesLock.Unlock()
2428         var lastKnown time.Time
2429         if len(cr.prices) > 0 {
2430                 lastKnown = cr.prices[0].StartTime
2431         }
2432         cr.prices = cloud.NormalizePriceHistory(append(prices, cr.prices...))
2433         for i := len(cr.prices) - 1; i >= 0; i-- {
2434                 price := cr.prices[i]
2435                 if price.StartTime.After(lastKnown) {
2436                         cr.CrunchLog.Printf("Instance price changed to %#.3g at %s", price.Price, price.StartTime.UTC())
2437                 }
2438         }
2439 }
2440
2441 func (cr *ContainerRunner) calculateCost(now time.Time) float64 {
2442         cr.pricesLock.Lock()
2443         defer cr.pricesLock.Unlock()
2444
2445         // First, make a "prices" slice with the real data as far back
2446         // as it goes, and (if needed) a "since the beginning of time"
2447         // placeholder containing a reasonable guess about what the
2448         // price was between cr.costStartTime and the earliest real
2449         // data point.
2450         prices := cr.prices
2451         if len(prices) == 0 {
2452                 // use price info in InstanceType record initially
2453                 // provided by cloud dispatcher
2454                 var p float64
2455                 var it arvados.InstanceType
2456                 if j := os.Getenv("InstanceType"); j != "" && json.Unmarshal([]byte(j), &it) == nil && it.Price > 0 {
2457                         p = it.Price
2458                 }
2459                 prices = []cloud.InstancePrice{{Price: p}}
2460         } else if prices[len(prices)-1].StartTime.After(cr.costStartTime) {
2461                 // guess earlier pricing was the same as the earliest
2462                 // price we know about
2463                 filler := prices[len(prices)-1]
2464                 filler.StartTime = time.Time{}
2465                 prices = append(prices, filler)
2466         }
2467
2468         // Now that our history of price changes goes back at least as
2469         // far as cr.costStartTime, add up the costs for each
2470         // interval.
2471         cost := 0.0
2472         spanEnd := now
2473         for _, ip := range prices {
2474                 spanStart := ip.StartTime
2475                 if spanStart.After(now) {
2476                         // pricing information from the future -- not
2477                         // expected from AWS, but possible in
2478                         // principle, and exercised by tests.
2479                         continue
2480                 }
2481                 last := false
2482                 if spanStart.Before(cr.costStartTime) {
2483                         spanStart = cr.costStartTime
2484                         last = true
2485                 }
2486                 cost += ip.Price * spanEnd.Sub(spanStart).Seconds() / 3600
2487                 if last {
2488                         break
2489                 }
2490                 spanEnd = spanStart
2491         }
2492
2493         return cost
2494 }
2495
2496 func (runner *ContainerRunner) handleSIGUSR2(sigchan chan os.Signal) {
2497         for range sigchan {
2498                 runner.loadPrices()
2499                 update := arvadosclient.Dict{
2500                         "select": []string{"uuid"},
2501                         "container": arvadosclient.Dict{
2502                                 "cost": runner.calculateCost(time.Now()),
2503                         },
2504                 }
2505                 runner.DispatcherArvClient.Update("containers", runner.Container.UUID, update, nil)
2506         }
2507 }