f8941162ec089515fd8ad2708f32e72162bc771e
[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         }
631
632         if runner.HostOutputDir == "" {
633                 return nil, fmt.Errorf("output path does not correspond to a writable mount point")
634         }
635
636         if needCertMount && runner.Container.RuntimeConstraints.API {
637                 for _, certfile := range []string{
638                         // Populated by caller, or sdk/go/arvados init(), or test suite:
639                         os.Getenv("SSL_CERT_FILE"),
640                         // Copied from Go 1.21 stdlib (src/crypto/x509/root_linux.go):
641                         "/etc/ssl/certs/ca-certificates.crt",                // Debian/Ubuntu/Gentoo etc.
642                         "/etc/pki/tls/certs/ca-bundle.crt",                  // Fedora/RHEL 6
643                         "/etc/ssl/ca-bundle.pem",                            // OpenSUSE
644                         "/etc/pki/tls/cacert.pem",                           // OpenELEC
645                         "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", // CentOS/RHEL 7
646                         "/etc/ssl/cert.pem",                                 // Alpine Linux
647                 } {
648                         if _, err := os.Stat(certfile); err == nil {
649                                 bindmounts[arvadosCertPath] = bindmount{HostPath: certfile, ReadOnly: true}
650                                 break
651                         }
652                 }
653         }
654
655         if pdhOnly {
656                 // If we are only mounting collections by pdh, make
657                 // sure we don't subscribe to websocket events to
658                 // avoid putting undesired load on the API server
659                 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id", "--disable-event-listening")
660         } else {
661                 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
662         }
663         // the by_uuid mount point is used by singularity when writing
664         // out docker images converted to SIF
665         arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_uuid")
666         arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
667
668         runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
669         if err != nil {
670                 return nil, fmt.Errorf("while trying to start arv-mount: %v", err)
671         }
672         if runner.hoststatReporter != nil && runner.ArvMount != nil {
673                 runner.hoststatReporter.ReportPID("arv-mount", runner.ArvMount.Process.Pid)
674         }
675
676         for _, p := range collectionPaths {
677                 _, err = os.Stat(p)
678                 if err != nil {
679                         return nil, fmt.Errorf("while checking that input files exist: %v", err)
680                 }
681         }
682
683         for _, cp := range copyFiles {
684                 st, err := os.Stat(cp.src)
685                 if err != nil {
686                         return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
687                 }
688                 if st.IsDir() {
689                         err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
690                                 if walkerr != nil {
691                                         return walkerr
692                                 }
693                                 target := path.Join(cp.bind, walkpath[len(cp.src):])
694                                 if walkinfo.Mode().IsRegular() {
695                                         copyerr := copyfile(walkpath, target)
696                                         if copyerr != nil {
697                                                 return copyerr
698                                         }
699                                         return os.Chmod(target, walkinfo.Mode()|0777)
700                                 } else if walkinfo.Mode().IsDir() {
701                                         mkerr := os.MkdirAll(target, 0777)
702                                         if mkerr != nil {
703                                                 return mkerr
704                                         }
705                                         return os.Chmod(target, walkinfo.Mode()|os.ModeSetgid|0777)
706                                 } else {
707                                         return fmt.Errorf("source %q is not a regular file or directory", cp.src)
708                                 }
709                         })
710                 } else if st.Mode().IsRegular() {
711                         err = copyfile(cp.src, cp.bind)
712                         if err == nil {
713                                 err = os.Chmod(cp.bind, st.Mode()|0777)
714                         }
715                 }
716                 if err != nil {
717                         return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
718                 }
719         }
720
721         return bindmounts, nil
722 }
723
724 func (runner *ContainerRunner) stopHoststat() error {
725         if runner.hoststatReporter == nil {
726                 return nil
727         }
728         runner.hoststatReporter.Stop()
729         runner.hoststatReporter.LogProcessMemMax(runner.CrunchLog)
730         err := runner.hoststatLogger.Close()
731         if err != nil {
732                 return fmt.Errorf("error closing hoststat logs: %v", err)
733         }
734         return nil
735 }
736
737 func (runner *ContainerRunner) startHoststat() error {
738         w, err := runner.NewLogWriter("hoststat")
739         if err != nil {
740                 return err
741         }
742         runner.hoststatLogger = NewThrottledLogger(w)
743         runner.hoststatReporter = &crunchstat.Reporter{
744                 Logger: log.New(runner.hoststatLogger, "", 0),
745                 // Our own cgroup is the "host" cgroup, in the sense
746                 // that it accounts for resource usage outside the
747                 // container. It doesn't count _all_ resource usage on
748                 // the system.
749                 //
750                 // TODO?: Use the furthest ancestor of our own cgroup
751                 // that has stats available. (Currently crunchstat
752                 // does not have that capability.)
753                 Pid:        os.Getpid,
754                 PollPeriod: runner.statInterval,
755         }
756         runner.hoststatReporter.Start()
757         runner.hoststatReporter.ReportPID("crunch-run", os.Getpid())
758         return nil
759 }
760
761 func (runner *ContainerRunner) startCrunchstat() error {
762         w, err := runner.NewLogWriter("crunchstat")
763         if err != nil {
764                 return err
765         }
766         runner.statLogger = NewThrottledLogger(w)
767         runner.statReporter = &crunchstat.Reporter{
768                 Pid:    runner.executor.Pid,
769                 FS:     runner.crunchstatFakeFS,
770                 Logger: log.New(runner.statLogger, "", 0),
771                 MemThresholds: map[string][]crunchstat.Threshold{
772                         "rss": crunchstat.NewThresholdsFromPercentages(runner.Container.RuntimeConstraints.RAM, []int64{90, 95, 99}),
773                 },
774                 PollPeriod:      runner.statInterval,
775                 TempDir:         runner.parentTemp,
776                 ThresholdLogger: runner.CrunchLog,
777         }
778         runner.statReporter.Start()
779         return nil
780 }
781
782 type infoCommand struct {
783         label string
784         cmd   []string
785 }
786
787 // LogHostInfo logs info about the current host, for debugging and
788 // accounting purposes. Although it's logged as "node-info", this is
789 // about the environment where crunch-run is actually running, which
790 // might differ from what's described in the node record (see
791 // LogNodeRecord).
792 func (runner *ContainerRunner) LogHostInfo() (err error) {
793         w, err := runner.NewLogWriter("node-info")
794         if err != nil {
795                 return
796         }
797
798         commands := []infoCommand{
799                 {
800                         label: "Host Information",
801                         cmd:   []string{"uname", "-a"},
802                 },
803                 {
804                         label: "CPU Information",
805                         cmd:   []string{"cat", "/proc/cpuinfo"},
806                 },
807                 {
808                         label: "Memory Information",
809                         cmd:   []string{"cat", "/proc/meminfo"},
810                 },
811                 {
812                         label: "Disk Space",
813                         cmd:   []string{"df", "-m", "/", os.TempDir()},
814                 },
815                 {
816                         label: "Disk INodes",
817                         cmd:   []string{"df", "-i", "/", os.TempDir()},
818                 },
819         }
820
821         // Run commands with informational output to be logged.
822         for _, command := range commands {
823                 fmt.Fprintln(w, command.label)
824                 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
825                 cmd.Stdout = w
826                 cmd.Stderr = w
827                 if err := cmd.Run(); err != nil {
828                         err = fmt.Errorf("While running command %q: %v", command.cmd, err)
829                         fmt.Fprintln(w, err)
830                         return err
831                 }
832                 fmt.Fprintln(w, "")
833         }
834
835         err = w.Close()
836         if err != nil {
837                 return fmt.Errorf("While closing node-info logs: %v", err)
838         }
839         return nil
840 }
841
842 // LogContainerRecord gets and saves the raw JSON container record from the API server
843 func (runner *ContainerRunner) LogContainerRecord() error {
844         logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}})
845         if !logged && err == nil {
846                 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
847         }
848         return err
849 }
850
851 // LogNodeRecord logs the current host's InstanceType config entry, if
852 // running via arvados-dispatch-cloud.
853 func (runner *ContainerRunner) LogNodeRecord() error {
854         it := os.Getenv("InstanceType")
855         if it == "" {
856                 // Not dispatched by arvados-dispatch-cloud.
857                 return nil
858         }
859         // Save InstanceType config fragment received from dispatcher
860         // on stdin.
861         w, err := runner.LogCollection.OpenFile("node.json", os.O_CREATE|os.O_WRONLY, 0666)
862         if err != nil {
863                 return err
864         }
865         defer w.Close()
866         _, err = io.WriteString(w, it)
867         if err != nil {
868                 return err
869         }
870         return w.Close()
871 }
872
873 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}) (logged bool, err error) {
874         writer, err := runner.LogCollection.OpenFile(label+".json", os.O_CREATE|os.O_WRONLY, 0666)
875         if err != nil {
876                 return false, err
877         }
878         w := &ArvLogWriter{
879                 ArvClient:     runner.DispatcherArvClient,
880                 UUID:          runner.Container.UUID,
881                 loggingStream: label,
882                 writeCloser:   writer,
883         }
884
885         reader, err := runner.DispatcherArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
886         if err != nil {
887                 return false, fmt.Errorf("error getting %s record: %v", label, err)
888         }
889         defer reader.Close()
890
891         dec := json.NewDecoder(reader)
892         dec.UseNumber()
893         var resp map[string]interface{}
894         if err = dec.Decode(&resp); err != nil {
895                 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
896         }
897         items, ok := resp["items"].([]interface{})
898         if !ok {
899                 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
900         } else if len(items) < 1 {
901                 return false, nil
902         }
903         // Re-encode it using indentation to improve readability
904         enc := json.NewEncoder(w)
905         enc.SetIndent("", "    ")
906         if err = enc.Encode(items[0]); err != nil {
907                 return false, fmt.Errorf("error logging %s record: %v", label, err)
908         }
909         err = w.Close()
910         if err != nil {
911                 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
912         }
913         return true, nil
914 }
915
916 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
917         stdoutPath := mntPath[len(runner.Container.OutputPath):]
918         index := strings.LastIndex(stdoutPath, "/")
919         if index > 0 {
920                 subdirs := stdoutPath[:index]
921                 if subdirs != "" {
922                         st, err := os.Stat(runner.HostOutputDir)
923                         if err != nil {
924                                 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
925                         }
926                         stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
927                         err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
928                         if err != nil {
929                                 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
930                         }
931                 }
932         }
933         stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
934         if err != nil {
935                 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
936         }
937
938         return stdoutFile, nil
939 }
940
941 // CreateContainer creates the docker container.
942 func (runner *ContainerRunner) CreateContainer(imageID string, bindmounts map[string]bindmount) error {
943         var stdin io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
944         if mnt, ok := runner.Container.Mounts["stdin"]; ok {
945                 switch mnt.Kind {
946                 case "collection":
947                         var collID string
948                         if mnt.UUID != "" {
949                                 collID = mnt.UUID
950                         } else {
951                                 collID = mnt.PortableDataHash
952                         }
953                         path := runner.ArvMountPoint + "/by_id/" + collID + "/" + mnt.Path
954                         f, err := os.Open(path)
955                         if err != nil {
956                                 return err
957                         }
958                         stdin = f
959                 case "json":
960                         j, err := json.Marshal(mnt.Content)
961                         if err != nil {
962                                 return fmt.Errorf("error encoding stdin json data: %v", err)
963                         }
964                         stdin = ioutil.NopCloser(bytes.NewReader(j))
965                 default:
966                         return fmt.Errorf("stdin mount has unsupported kind %q", mnt.Kind)
967                 }
968         }
969
970         var stdout, stderr io.WriteCloser
971         if mnt, ok := runner.Container.Mounts["stdout"]; ok {
972                 f, err := runner.getStdoutFile(mnt.Path)
973                 if err != nil {
974                         return err
975                 }
976                 stdout = f
977         } else if w, err := runner.NewLogWriter("stdout"); err != nil {
978                 return err
979         } else {
980                 stdout = NewThrottledLogger(w)
981         }
982
983         if mnt, ok := runner.Container.Mounts["stderr"]; ok {
984                 f, err := runner.getStdoutFile(mnt.Path)
985                 if err != nil {
986                         return err
987                 }
988                 stderr = f
989         } else if w, err := runner.NewLogWriter("stderr"); err != nil {
990                 return err
991         } else {
992                 stderr = NewThrottledLogger(w)
993         }
994
995         env := runner.Container.Environment
996         enableNetwork := runner.enableNetwork == "always"
997         if runner.Container.RuntimeConstraints.API {
998                 enableNetwork = true
999                 tok, err := runner.ContainerToken()
1000                 if err != nil {
1001                         return err
1002                 }
1003                 env = map[string]string{}
1004                 for k, v := range runner.Container.Environment {
1005                         env[k] = v
1006                 }
1007                 env["ARVADOS_API_TOKEN"] = tok
1008                 env["ARVADOS_API_HOST"] = os.Getenv("ARVADOS_API_HOST")
1009                 env["ARVADOS_API_HOST_INSECURE"] = os.Getenv("ARVADOS_API_HOST_INSECURE")
1010                 env["ARVADOS_KEEP_SERVICES"] = os.Getenv("ARVADOS_KEEP_SERVICES")
1011         }
1012         workdir := runner.Container.Cwd
1013         if workdir == "." {
1014                 // both "" and "." mean default
1015                 workdir = ""
1016         }
1017         ram := runner.Container.RuntimeConstraints.RAM
1018         if !runner.enableMemoryLimit {
1019                 ram = 0
1020         }
1021         runner.executorStdin = stdin
1022         runner.executorStdout = stdout
1023         runner.executorStderr = stderr
1024
1025         if runner.Container.RuntimeConstraints.CUDA.DeviceCount > 0 {
1026                 nvidiaModprobe(runner.CrunchLog)
1027         }
1028
1029         return runner.executor.Create(containerSpec{
1030                 Image:           imageID,
1031                 VCPUs:           runner.Container.RuntimeConstraints.VCPUs,
1032                 RAM:             ram,
1033                 WorkingDir:      workdir,
1034                 Env:             env,
1035                 BindMounts:      bindmounts,
1036                 Command:         runner.Container.Command,
1037                 EnableNetwork:   enableNetwork,
1038                 CUDADeviceCount: runner.Container.RuntimeConstraints.CUDA.DeviceCount,
1039                 NetworkMode:     runner.networkMode,
1040                 CgroupParent:    runner.setCgroupParent,
1041                 Stdin:           stdin,
1042                 Stdout:          stdout,
1043                 Stderr:          stderr,
1044         })
1045 }
1046
1047 // StartContainer starts the docker container created by CreateContainer.
1048 func (runner *ContainerRunner) StartContainer() error {
1049         runner.CrunchLog.Printf("Starting container")
1050         runner.cStateLock.Lock()
1051         defer runner.cStateLock.Unlock()
1052         if runner.cCancelled {
1053                 return ErrCancelled
1054         }
1055         err := runner.executor.Start()
1056         if err != nil {
1057                 var advice string
1058                 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
1059                         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])
1060                 }
1061                 return fmt.Errorf("could not start container: %v%s", err, advice)
1062         }
1063         return nil
1064 }
1065
1066 // WaitFinish waits for the container to terminate, capture the exit code, and
1067 // close the stdout/stderr logging.
1068 func (runner *ContainerRunner) WaitFinish() error {
1069         runner.CrunchLog.Print("Waiting for container to finish")
1070         var timeout <-chan time.Time
1071         if s := runner.Container.SchedulingParameters.MaxRunTime; s > 0 {
1072                 timeout = time.After(time.Duration(s) * time.Second)
1073         }
1074         ctx, cancel := context.WithCancel(context.Background())
1075         defer cancel()
1076         go func() {
1077                 select {
1078                 case <-timeout:
1079                         runner.CrunchLog.Printf("maximum run time exceeded. Stopping container.")
1080                         runner.stop(nil)
1081                 case <-runner.ArvMountExit:
1082                         runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
1083                         runner.stop(nil)
1084                 case <-ctx.Done():
1085                 }
1086         }()
1087         exitcode, err := runner.executor.Wait(ctx)
1088         if err != nil {
1089                 runner.checkBrokenNode(err)
1090                 return err
1091         }
1092         runner.ExitCode = &exitcode
1093
1094         extra := ""
1095         if exitcode&0x80 != 0 {
1096                 // Convert raw exit status (0x80 + signal number) to a
1097                 // string to log after the code, like " (signal 101)"
1098                 // or " (signal 9, killed)"
1099                 sig := syscall.WaitStatus(exitcode).Signal()
1100                 if name := unix.SignalName(sig); name != "" {
1101                         extra = fmt.Sprintf(" (signal %d, %s)", sig, name)
1102                 } else {
1103                         extra = fmt.Sprintf(" (signal %d)", sig)
1104                 }
1105         }
1106         runner.CrunchLog.Printf("Container exited with status code %d%s", exitcode, extra)
1107         err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1108                 "select":    []string{"uuid"},
1109                 "container": arvadosclient.Dict{"exit_code": exitcode},
1110         }, nil)
1111         if err != nil {
1112                 runner.CrunchLog.Printf("ignoring error updating exit_code: %s", err)
1113         }
1114
1115         var returnErr error
1116         if err = runner.executorStdin.Close(); err != nil {
1117                 err = fmt.Errorf("error closing container stdin: %s", err)
1118                 runner.CrunchLog.Printf("%s", err)
1119                 returnErr = err
1120         }
1121         if err = runner.executorStdout.Close(); err != nil {
1122                 err = fmt.Errorf("error closing container stdout: %s", err)
1123                 runner.CrunchLog.Printf("%s", err)
1124                 if returnErr == nil {
1125                         returnErr = err
1126                 }
1127         }
1128         if err = runner.executorStderr.Close(); err != nil {
1129                 err = fmt.Errorf("error closing container stderr: %s", err)
1130                 runner.CrunchLog.Printf("%s", err)
1131                 if returnErr == nil {
1132                         returnErr = err
1133                 }
1134         }
1135
1136         if runner.statReporter != nil {
1137                 runner.statReporter.Stop()
1138                 runner.statReporter.LogMaxima(runner.CrunchLog, map[string]int64{
1139                         "rss": runner.Container.RuntimeConstraints.RAM,
1140                 })
1141                 err = runner.statLogger.Close()
1142                 if err != nil {
1143                         runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
1144                 }
1145         }
1146         return returnErr
1147 }
1148
1149 func (runner *ContainerRunner) updateLogs() {
1150         ticker := time.NewTicker(crunchLogUpdatePeriod / 360)
1151         defer ticker.Stop()
1152
1153         sigusr1 := make(chan os.Signal, 1)
1154         signal.Notify(sigusr1, syscall.SIGUSR1)
1155         defer signal.Stop(sigusr1)
1156
1157         saveAtTime := time.Now().Add(crunchLogUpdatePeriod)
1158         saveAtSize := crunchLogUpdateSize
1159         var savedSize int64
1160         for {
1161                 select {
1162                 case <-ticker.C:
1163                 case <-sigusr1:
1164                         saveAtTime = time.Now()
1165                 }
1166                 runner.logMtx.Lock()
1167                 done := runner.LogsPDH != nil
1168                 runner.logMtx.Unlock()
1169                 if done {
1170                         return
1171                 }
1172                 size := runner.LogCollection.Size()
1173                 if size == savedSize || (time.Now().Before(saveAtTime) && size < saveAtSize) {
1174                         continue
1175                 }
1176                 saveAtTime = time.Now().Add(crunchLogUpdatePeriod)
1177                 saveAtSize = runner.LogCollection.Size() + crunchLogUpdateSize
1178                 saved, err := runner.saveLogCollection(false)
1179                 if err != nil {
1180                         runner.CrunchLog.Printf("error updating log collection: %s", err)
1181                         continue
1182                 }
1183
1184                 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1185                         "select": []string{"uuid"},
1186                         "container": arvadosclient.Dict{
1187                                 "log": saved.PortableDataHash,
1188                         },
1189                 }, nil)
1190                 if err != nil {
1191                         runner.CrunchLog.Printf("error updating container log to %s: %s", saved.PortableDataHash, err)
1192                         continue
1193                 }
1194
1195                 savedSize = size
1196         }
1197 }
1198
1199 var spotInterruptionCheckInterval = 5 * time.Second
1200 var ec2MetadataBaseURL = "http://169.254.169.254"
1201
1202 const ec2TokenTTL = time.Second * 21600
1203
1204 func (runner *ContainerRunner) checkSpotInterruptionNotices() {
1205         type ec2metadata struct {
1206                 Action string    `json:"action"`
1207                 Time   time.Time `json:"time"`
1208         }
1209         runner.CrunchLog.Printf("Checking for spot interruptions every %v using instance metadata at %s", spotInterruptionCheckInterval, ec2MetadataBaseURL)
1210         var metadata ec2metadata
1211         var token string
1212         var tokenExp time.Time
1213         check := func() error {
1214                 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute))
1215                 defer cancel()
1216                 if token == "" || tokenExp.Sub(time.Now()) < time.Minute {
1217                         req, err := http.NewRequestWithContext(ctx, http.MethodPut, ec2MetadataBaseURL+"/latest/api/token", nil)
1218                         if err != nil {
1219                                 return err
1220                         }
1221                         req.Header.Set("X-aws-ec2-metadata-token-ttl-seconds", fmt.Sprintf("%d", int(ec2TokenTTL/time.Second)))
1222                         resp, err := http.DefaultClient.Do(req)
1223                         if err != nil {
1224                                 return err
1225                         }
1226                         defer resp.Body.Close()
1227                         if resp.StatusCode != http.StatusOK {
1228                                 return fmt.Errorf("%s", resp.Status)
1229                         }
1230                         newtoken, err := ioutil.ReadAll(resp.Body)
1231                         if err != nil {
1232                                 return err
1233                         }
1234                         token = strings.TrimSpace(string(newtoken))
1235                         tokenExp = time.Now().Add(ec2TokenTTL)
1236                 }
1237                 req, err := http.NewRequestWithContext(ctx, http.MethodGet, ec2MetadataBaseURL+"/latest/meta-data/spot/instance-action", nil)
1238                 if err != nil {
1239                         return err
1240                 }
1241                 req.Header.Set("X-aws-ec2-metadata-token", token)
1242                 resp, err := http.DefaultClient.Do(req)
1243                 if err != nil {
1244                         return err
1245                 }
1246                 defer resp.Body.Close()
1247                 metadata = ec2metadata{}
1248                 switch resp.StatusCode {
1249                 case http.StatusOK:
1250                         break
1251                 case http.StatusNotFound:
1252                         // "If Amazon EC2 is not preparing to stop or
1253                         // terminate the instance, or if you
1254                         // terminated the instance yourself,
1255                         // instance-action is not present in the
1256                         // instance metadata and you receive an HTTP
1257                         // 404 error when you try to retrieve it."
1258                         return nil
1259                 case http.StatusUnauthorized:
1260                         token = ""
1261                         return fmt.Errorf("%s", resp.Status)
1262                 default:
1263                         return fmt.Errorf("%s", resp.Status)
1264                 }
1265                 err = json.NewDecoder(resp.Body).Decode(&metadata)
1266                 if err != nil {
1267                         return err
1268                 }
1269                 return nil
1270         }
1271         failures := 0
1272         var lastmetadata ec2metadata
1273         for range time.NewTicker(spotInterruptionCheckInterval).C {
1274                 err := check()
1275                 if err != nil {
1276                         runner.CrunchLog.Printf("Error checking spot interruptions: %s", err)
1277                         failures++
1278                         if failures > 5 {
1279                                 runner.CrunchLog.Printf("Giving up on checking spot interruptions after too many consecutive failures")
1280                                 return
1281                         }
1282                         continue
1283                 }
1284                 failures = 0
1285                 if metadata != lastmetadata {
1286                         lastmetadata = metadata
1287                         text := fmt.Sprintf("Cloud provider scheduled instance %s at %s", metadata.Action, metadata.Time.UTC().Format(time.RFC3339))
1288                         runner.CrunchLog.Printf("%s", text)
1289                         runner.updateRuntimeStatus(arvadosclient.Dict{
1290                                 "warning":          "preemption notice",
1291                                 "warningDetail":    text,
1292                                 "preemptionNotice": text,
1293                         })
1294                         if proc, err := os.FindProcess(os.Getpid()); err == nil {
1295                                 // trigger updateLogs
1296                                 proc.Signal(syscall.SIGUSR1)
1297                         }
1298                 }
1299         }
1300 }
1301
1302 func (runner *ContainerRunner) updateRuntimeStatus(status arvadosclient.Dict) {
1303         err := runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1304                 "select": []string{"uuid"},
1305                 "container": arvadosclient.Dict{
1306                         "runtime_status": status,
1307                 },
1308         }, nil)
1309         if err != nil {
1310                 runner.CrunchLog.Printf("error updating container runtime_status: %s", err)
1311         }
1312 }
1313
1314 // CaptureOutput saves data from the container's output directory if
1315 // needed, and updates the container output accordingly.
1316 func (runner *ContainerRunner) CaptureOutput(bindmounts map[string]bindmount) error {
1317         if runner.Container.RuntimeConstraints.API {
1318                 // Output may have been set directly by the container, so
1319                 // refresh the container record to check.
1320                 err := runner.DispatcherArvClient.Get("containers", runner.Container.UUID,
1321                         arvadosclient.Dict{
1322                                 "select": []string{"output"},
1323                         }, &runner.Container)
1324                 if err != nil {
1325                         return err
1326                 }
1327                 if runner.Container.Output != "" {
1328                         // Container output is already set.
1329                         runner.OutputPDH = &runner.Container.Output
1330                         return nil
1331                 }
1332         }
1333
1334         txt, err := (&copier{
1335                 client:        runner.containerClient,
1336                 keepClient:    runner.ContainerKeepClient,
1337                 hostOutputDir: runner.HostOutputDir,
1338                 ctrOutputDir:  runner.Container.OutputPath,
1339                 globs:         runner.Container.OutputGlob,
1340                 bindmounts:    bindmounts,
1341                 mounts:        runner.Container.Mounts,
1342                 secretMounts:  runner.SecretMounts,
1343                 logger:        runner.CrunchLog,
1344         }).Copy()
1345         if err != nil {
1346                 return err
1347         }
1348         if n := len(regexp.MustCompile(` [0-9a-f]+\+\S*\+R`).FindAllStringIndex(txt, -1)); n > 0 {
1349                 runner.CrunchLog.Printf("Copying %d data blocks from remote input collections...", n)
1350                 fs, err := (&arvados.Collection{ManifestText: txt}).FileSystem(runner.containerClient, runner.ContainerKeepClient)
1351                 if err != nil {
1352                         return err
1353                 }
1354                 txt, err = fs.MarshalManifest(".")
1355                 if err != nil {
1356                         return err
1357                 }
1358         }
1359         var resp arvados.Collection
1360         err = runner.ContainerArvClient.Create("collections", arvadosclient.Dict{
1361                 "ensure_unique_name": true,
1362                 "select":             []string{"portable_data_hash"},
1363                 "collection": arvadosclient.Dict{
1364                         "is_trashed":    true,
1365                         "name":          "output for " + runner.Container.UUID,
1366                         "manifest_text": txt,
1367                 },
1368         }, &resp)
1369         if err != nil {
1370                 return fmt.Errorf("error creating output collection: %v", err)
1371         }
1372         runner.OutputPDH = &resp.PortableDataHash
1373         return nil
1374 }
1375
1376 func (runner *ContainerRunner) CleanupDirs() {
1377         if runner.ArvMount != nil {
1378                 var delay int64 = 8
1379                 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1380                 umount.Stdout = runner.CrunchLog
1381                 umount.Stderr = runner.CrunchLog
1382                 runner.CrunchLog.Printf("Running %v", umount.Args)
1383                 umnterr := umount.Start()
1384
1385                 if umnterr != nil {
1386                         runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1387                         runner.ArvMount.Process.Kill()
1388                 } else {
1389                         // If arv-mount --unmount gets stuck for any reason, we
1390                         // don't want to wait for it forever.  Do Wait() in a goroutine
1391                         // so it doesn't block crunch-run.
1392                         umountExit := make(chan error)
1393                         go func() {
1394                                 mnterr := umount.Wait()
1395                                 if mnterr != nil {
1396                                         runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1397                                 }
1398                                 umountExit <- mnterr
1399                         }()
1400
1401                         for again := true; again; {
1402                                 again = false
1403                                 select {
1404                                 case <-umountExit:
1405                                         umount = nil
1406                                         again = true
1407                                 case <-runner.ArvMountExit:
1408                                         break
1409                                 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1410                                         runner.CrunchLog.Printf("Timed out waiting for unmount")
1411                                         if umount != nil {
1412                                                 umount.Process.Kill()
1413                                         }
1414                                         runner.ArvMount.Process.Kill()
1415                                 }
1416                         }
1417                 }
1418                 runner.ArvMount = nil
1419         }
1420
1421         if runner.ArvMountPoint != "" {
1422                 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1423                         runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1424                 }
1425                 runner.ArvMountPoint = ""
1426         }
1427
1428         if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1429                 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1430         }
1431 }
1432
1433 // CommitLogs posts the collection containing the final container logs.
1434 func (runner *ContainerRunner) CommitLogs() error {
1435         func() {
1436                 // Hold cStateLock to prevent races on CrunchLog (e.g., stop()).
1437                 runner.cStateLock.Lock()
1438                 defer runner.cStateLock.Unlock()
1439
1440                 runner.CrunchLog.Print(runner.finalState)
1441
1442                 if runner.arvMountLog != nil {
1443                         runner.arvMountLog.Close()
1444                 }
1445                 runner.CrunchLog.Close()
1446
1447                 // Closing CrunchLog above allows them to be committed to Keep at this
1448                 // point, but re-open crunch log with ArvClient in case there are any
1449                 // other further errors (such as failing to write the log to Keep!)
1450                 // while shutting down
1451                 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{
1452                         ArvClient:     runner.DispatcherArvClient,
1453                         UUID:          runner.Container.UUID,
1454                         loggingStream: "crunch-run",
1455                         writeCloser:   nil,
1456                 })
1457                 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1458         }()
1459
1460         if runner.keepstoreLogger != nil {
1461                 // Flush any buffered logs from our local keepstore
1462                 // process.  Discard anything logged after this point
1463                 // -- it won't end up in the log collection, so
1464                 // there's no point writing it to the collectionfs.
1465                 runner.keepstoreLogbuf.SetWriter(io.Discard)
1466                 runner.keepstoreLogger.Close()
1467                 runner.keepstoreLogger = nil
1468         }
1469
1470         if runner.LogsPDH != nil {
1471                 // If we have already assigned something to LogsPDH,
1472                 // we must be closing the re-opened log, which won't
1473                 // end up getting attached to the container record and
1474                 // therefore doesn't need to be saved as a collection
1475                 // -- it exists only to send logs to other channels.
1476                 return nil
1477         }
1478
1479         saved, err := runner.saveLogCollection(true)
1480         if err != nil {
1481                 return fmt.Errorf("error saving log collection: %s", err)
1482         }
1483         runner.logMtx.Lock()
1484         defer runner.logMtx.Unlock()
1485         runner.LogsPDH = &saved.PortableDataHash
1486         return nil
1487 }
1488
1489 // Create/update the log collection. Return value has UUID and
1490 // PortableDataHash fields populated, but others may be blank.
1491 func (runner *ContainerRunner) saveLogCollection(final bool) (response arvados.Collection, err error) {
1492         runner.logMtx.Lock()
1493         defer runner.logMtx.Unlock()
1494         if runner.LogsPDH != nil {
1495                 // Already finalized.
1496                 return
1497         }
1498         updates := arvadosclient.Dict{
1499                 "name": "logs for " + runner.Container.UUID,
1500         }
1501         mt, err1 := runner.LogCollection.MarshalManifest(".")
1502         if err1 == nil {
1503                 // Only send updated manifest text if there was no
1504                 // error.
1505                 updates["manifest_text"] = mt
1506         }
1507
1508         // Even if flushing the manifest had an error, we still want
1509         // to update the log record, if possible, to push the trash_at
1510         // and delete_at times into the future.  Details on bug
1511         // #17293.
1512         if final {
1513                 updates["is_trashed"] = true
1514         } else {
1515                 // We set trash_at so this collection gets
1516                 // automatically cleaned up eventually.  It used to be
1517                 // 12 hours but we had a situation where the API
1518                 // server was down over a weekend but the containers
1519                 // kept running such that the log collection got
1520                 // trashed, so now we make it 2 weeks.  refs #20378
1521                 exp := time.Now().Add(time.Duration(24*14) * time.Hour)
1522                 updates["trash_at"] = exp
1523                 updates["delete_at"] = exp
1524         }
1525         reqBody := arvadosclient.Dict{
1526                 "select":     []string{"uuid", "portable_data_hash"},
1527                 "collection": updates,
1528         }
1529         var err2 error
1530         if runner.logUUID == "" {
1531                 reqBody["ensure_unique_name"] = true
1532                 err2 = runner.DispatcherArvClient.Create("collections", reqBody, &response)
1533         } else {
1534                 err2 = runner.DispatcherArvClient.Update("collections", runner.logUUID, reqBody, &response)
1535         }
1536         if err2 == nil {
1537                 runner.logUUID = response.UUID
1538         }
1539
1540         if err1 != nil || err2 != nil {
1541                 err = fmt.Errorf("error recording logs: %q, %q", err1, err2)
1542         }
1543         return
1544 }
1545
1546 // UpdateContainerRunning updates the container state to "Running"
1547 func (runner *ContainerRunner) UpdateContainerRunning(logId string) error {
1548         runner.cStateLock.Lock()
1549         defer runner.cStateLock.Unlock()
1550         if runner.cCancelled {
1551                 return ErrCancelled
1552         }
1553         updates := arvadosclient.Dict{
1554                 "gateway_address": runner.gateway.Address,
1555                 "state":           "Running",
1556         }
1557         if logId != "" {
1558                 updates["log"] = logId
1559         }
1560         return runner.DispatcherArvClient.Update(
1561                 "containers",
1562                 runner.Container.UUID,
1563                 arvadosclient.Dict{
1564                         "select":    []string{"uuid"},
1565                         "container": updates,
1566                 },
1567                 nil,
1568         )
1569 }
1570
1571 // ContainerToken returns the api_token the container (and any
1572 // arv-mount processes) are allowed to use.
1573 func (runner *ContainerRunner) ContainerToken() (string, error) {
1574         if runner.token != "" {
1575                 return runner.token, nil
1576         }
1577
1578         var auth arvados.APIClientAuthorization
1579         err := runner.DispatcherArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1580         if err != nil {
1581                 return "", err
1582         }
1583         runner.token = fmt.Sprintf("v2/%s/%s/%s", auth.UUID, auth.APIToken, runner.Container.UUID)
1584         return runner.token, nil
1585 }
1586
1587 // UpdateContainerFinal updates the container record state on API
1588 // server to "Complete" or "Cancelled"
1589 func (runner *ContainerRunner) UpdateContainerFinal() error {
1590         update := arvadosclient.Dict{}
1591         update["state"] = runner.finalState
1592         if runner.LogsPDH != nil {
1593                 update["log"] = *runner.LogsPDH
1594         }
1595         if runner.ExitCode != nil {
1596                 update["exit_code"] = *runner.ExitCode
1597         } else {
1598                 update["exit_code"] = nil
1599         }
1600         if runner.finalState == "Complete" && runner.OutputPDH != nil {
1601                 update["output"] = *runner.OutputPDH
1602         }
1603         update["cost"] = runner.calculateCost(time.Now())
1604         return runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1605                 "select":    []string{"uuid"},
1606                 "container": update,
1607         }, nil)
1608 }
1609
1610 // IsCancelled returns the value of Cancelled, with goroutine safety.
1611 func (runner *ContainerRunner) IsCancelled() bool {
1612         runner.cStateLock.Lock()
1613         defer runner.cStateLock.Unlock()
1614         return runner.cCancelled
1615 }
1616
1617 // NewArvLogWriter creates an ArvLogWriter
1618 func (runner *ContainerRunner) NewArvLogWriter(name string) (io.WriteCloser, error) {
1619         writer, err := runner.LogCollection.OpenFile(name+".txt", os.O_CREATE|os.O_WRONLY, 0666)
1620         if err != nil {
1621                 return nil, err
1622         }
1623         return &ArvLogWriter{
1624                 ArvClient:     runner.DispatcherArvClient,
1625                 UUID:          runner.Container.UUID,
1626                 loggingStream: name,
1627                 writeCloser:   writer,
1628         }, nil
1629 }
1630
1631 // Run the full container lifecycle.
1632 func (runner *ContainerRunner) Run() (err error) {
1633         runner.CrunchLog.Printf("crunch-run %s started", cmd.Version.String())
1634         runner.CrunchLog.Printf("%s", currentUserAndGroups())
1635         v, _ := exec.Command("arv-mount", "--version").CombinedOutput()
1636         runner.CrunchLog.Printf("Using FUSE mount: %s", v)
1637         runner.CrunchLog.Printf("Using container runtime: %s", runner.executor.Runtime())
1638         runner.CrunchLog.Printf("Executing container: %s", runner.Container.UUID)
1639         runner.costStartTime = time.Now()
1640
1641         hostname, hosterr := os.Hostname()
1642         if hosterr != nil {
1643                 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1644         } else {
1645                 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1646         }
1647
1648         sigusr2 := make(chan os.Signal, 1)
1649         signal.Notify(sigusr2, syscall.SIGUSR2)
1650         defer signal.Stop(sigusr2)
1651         runner.loadPrices()
1652         go runner.handleSIGUSR2(sigusr2)
1653
1654         runner.finalState = "Queued"
1655
1656         defer func() {
1657                 runner.CleanupDirs()
1658
1659                 runner.CrunchLog.Printf("crunch-run finished")
1660                 runner.CrunchLog.Close()
1661         }()
1662
1663         err = runner.fetchContainerRecord()
1664         if err != nil {
1665                 return
1666         }
1667         if runner.Container.State != "Locked" {
1668                 return fmt.Errorf("dispatch error detected: container %q has state %q", runner.Container.UUID, runner.Container.State)
1669         }
1670
1671         var bindmounts map[string]bindmount
1672         defer func() {
1673                 // checkErr prints e (unless it's nil) and sets err to
1674                 // e (unless err is already non-nil). Thus, if err
1675                 // hasn't already been assigned when Run() returns,
1676                 // this cleanup func will cause Run() to return the
1677                 // first non-nil error that is passed to checkErr().
1678                 checkErr := func(errorIn string, e error) {
1679                         if e == nil {
1680                                 return
1681                         }
1682                         runner.CrunchLog.Printf("error in %s: %v", errorIn, e)
1683                         if err == nil {
1684                                 err = e
1685                         }
1686                         if runner.finalState == "Complete" {
1687                                 // There was an error in the finalization.
1688                                 runner.finalState = "Cancelled"
1689                         }
1690                 }
1691
1692                 // Log the error encountered in Run(), if any
1693                 checkErr("Run", err)
1694
1695                 if runner.finalState == "Queued" {
1696                         runner.UpdateContainerFinal()
1697                         return
1698                 }
1699
1700                 if runner.IsCancelled() {
1701                         runner.finalState = "Cancelled"
1702                         // but don't return yet -- we still want to
1703                         // capture partial output and write logs
1704                 }
1705
1706                 if bindmounts != nil {
1707                         checkErr("CaptureOutput", runner.CaptureOutput(bindmounts))
1708                 }
1709                 checkErr("stopHoststat", runner.stopHoststat())
1710                 checkErr("CommitLogs", runner.CommitLogs())
1711                 runner.CleanupDirs()
1712                 checkErr("UpdateContainerFinal", runner.UpdateContainerFinal())
1713         }()
1714
1715         runner.setupSignals()
1716         err = runner.startHoststat()
1717         if err != nil {
1718                 return
1719         }
1720         if runner.keepstore != nil {
1721                 runner.hoststatReporter.ReportPID("keepstore", runner.keepstore.Process.Pid)
1722         }
1723
1724         // set up FUSE mount and binds
1725         bindmounts, err = runner.SetupMounts()
1726         if err != nil {
1727                 runner.finalState = "Cancelled"
1728                 err = fmt.Errorf("While setting up mounts: %v", err)
1729                 return
1730         }
1731
1732         // check for and/or load image
1733         imageID, err := runner.LoadImage()
1734         if err != nil {
1735                 if !runner.checkBrokenNode(err) {
1736                         // Failed to load image but not due to a "broken node"
1737                         // condition, probably user error.
1738                         runner.finalState = "Cancelled"
1739                 }
1740                 err = fmt.Errorf("While loading container image: %v", err)
1741                 return
1742         }
1743
1744         err = runner.CreateContainer(imageID, bindmounts)
1745         if err != nil {
1746                 return
1747         }
1748         err = runner.LogHostInfo()
1749         if err != nil {
1750                 return
1751         }
1752         err = runner.LogNodeRecord()
1753         if err != nil {
1754                 return
1755         }
1756         err = runner.LogContainerRecord()
1757         if err != nil {
1758                 return
1759         }
1760
1761         if runner.IsCancelled() {
1762                 return
1763         }
1764
1765         logCollection, err := runner.saveLogCollection(false)
1766         var logId string
1767         if err == nil {
1768                 logId = logCollection.PortableDataHash
1769         } else {
1770                 runner.CrunchLog.Printf("Error committing initial log collection: %v", err)
1771         }
1772         err = runner.UpdateContainerRunning(logId)
1773         if err != nil {
1774                 return
1775         }
1776         runner.finalState = "Cancelled"
1777
1778         err = runner.startCrunchstat()
1779         if err != nil {
1780                 return
1781         }
1782
1783         err = runner.StartContainer()
1784         if err != nil {
1785                 runner.checkBrokenNode(err)
1786                 return
1787         }
1788
1789         err = runner.WaitFinish()
1790         if err == nil && !runner.IsCancelled() {
1791                 runner.finalState = "Complete"
1792         }
1793         return
1794 }
1795
1796 // Fetch the current container record (uuid = runner.Container.UUID)
1797 // into runner.Container.
1798 func (runner *ContainerRunner) fetchContainerRecord() error {
1799         reader, err := runner.DispatcherArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1800         if err != nil {
1801                 return fmt.Errorf("error fetching container record: %v", err)
1802         }
1803         defer reader.Close()
1804
1805         dec := json.NewDecoder(reader)
1806         dec.UseNumber()
1807         err = dec.Decode(&runner.Container)
1808         if err != nil {
1809                 return fmt.Errorf("error decoding container record: %v", err)
1810         }
1811
1812         var sm struct {
1813                 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
1814         }
1815
1816         containerToken, err := runner.ContainerToken()
1817         if err != nil {
1818                 return fmt.Errorf("error getting container token: %v", err)
1819         }
1820
1821         runner.ContainerArvClient, runner.ContainerKeepClient,
1822                 runner.containerClient, err = runner.MkArvClient(containerToken)
1823         if err != nil {
1824                 return fmt.Errorf("error creating container API client: %v", err)
1825         }
1826
1827         runner.ContainerKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1828         runner.DispatcherKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1829
1830         err = runner.ContainerArvClient.Call("GET", "containers", runner.Container.UUID, "secret_mounts", nil, &sm)
1831         if err != nil {
1832                 if apierr, ok := err.(arvadosclient.APIServerError); !ok || apierr.HttpStatusCode != 404 {
1833                         return fmt.Errorf("error fetching secret_mounts: %v", err)
1834                 }
1835                 // ok && apierr.HttpStatusCode == 404, which means
1836                 // secret_mounts isn't supported by this API server.
1837         }
1838         runner.SecretMounts = sm.SecretMounts
1839
1840         return nil
1841 }
1842
1843 // NewContainerRunner creates a new container runner.
1844 func NewContainerRunner(dispatcherClient *arvados.Client,
1845         dispatcherArvClient IArvadosClient,
1846         dispatcherKeepClient IKeepClient,
1847         containerUUID string) (*ContainerRunner, error) {
1848
1849         cr := &ContainerRunner{
1850                 dispatcherClient:     dispatcherClient,
1851                 DispatcherArvClient:  dispatcherArvClient,
1852                 DispatcherKeepClient: dispatcherKeepClient,
1853         }
1854         cr.NewLogWriter = cr.NewArvLogWriter
1855         cr.RunArvMount = cr.ArvMountCmd
1856         cr.MkTempDir = ioutil.TempDir
1857         cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1858                 cl, err := arvadosclient.MakeArvadosClient()
1859                 if err != nil {
1860                         return nil, nil, nil, err
1861                 }
1862                 cl.ApiToken = token
1863                 kc, err := keepclient.MakeKeepClient(cl)
1864                 if err != nil {
1865                         return nil, nil, nil, err
1866                 }
1867                 c2 := arvados.NewClientFromEnv()
1868                 c2.AuthToken = token
1869                 return cl, kc, c2, nil
1870         }
1871         var err error
1872         cr.LogCollection, err = (&arvados.Collection{}).FileSystem(cr.dispatcherClient, cr.DispatcherKeepClient)
1873         if err != nil {
1874                 return nil, err
1875         }
1876         cr.Container.UUID = containerUUID
1877         w, err := cr.NewLogWriter("crunch-run")
1878         if err != nil {
1879                 return nil, err
1880         }
1881         cr.CrunchLog = NewThrottledLogger(w)
1882         cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1883
1884         loadLogThrottleParams(dispatcherArvClient)
1885         go cr.updateLogs()
1886
1887         return cr, nil
1888 }
1889
1890 func (command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
1891         log := log.New(stderr, "", 0)
1892         flags := flag.NewFlagSet(prog, flag.ContinueOnError)
1893         statInterval := flags.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1894         flags.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree (obsolete, ignored)")
1895         flags.String("cgroup-parent", "docker", "name of container's parent cgroup (obsolete, ignored)")
1896         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")
1897         caCertsPath := flags.String("ca-certs", "", "Path to TLS root certificates")
1898         detach := flags.Bool("detach", false, "Detach from parent process and run in the background")
1899         stdinConfig := flags.Bool("stdin-config", false, "Load config and environment variables from JSON message on stdin")
1900         configFile := flags.String("config", arvados.DefaultConfigFile, "filename of cluster config file to try loading if -stdin-config=false (default is $ARVADOS_CONFIG)")
1901         sleep := flags.Duration("sleep", 0, "Delay before starting (testing use only)")
1902         kill := flags.Int("kill", -1, "Send signal to an existing crunch-run process for given UUID")
1903         list := flags.Bool("list", false, "List UUIDs of existing crunch-run processes (and notify them to use price data passed on stdin)")
1904         enableMemoryLimit := flags.Bool("enable-memory-limit", true, "tell container runtime to limit container's memory usage")
1905         enableNetwork := flags.String("container-enable-networking", "default", "enable networking \"always\" (for all containers) or \"default\" (for containers that request it)")
1906         networkMode := flags.String("container-network-mode", "default", `Docker network mode for container (use any argument valid for docker --net)`)
1907         memprofile := flags.String("memprofile", "", "write memory profile to `file` after running container")
1908         runtimeEngine := flags.String("runtime-engine", "docker", "container runtime: docker or singularity")
1909         brokenNodeHook := flags.String("broken-node-hook", "", "script to run if node is detected to be broken (for example, Docker daemon is not running)")
1910         flags.Duration("check-containerd", 0, "Ignored. Exists for compatibility with older versions.")
1911         version := flags.Bool("version", false, "Write version information to stdout and exit 0.")
1912
1913         ignoreDetachFlag := false
1914         if len(args) > 0 && args[0] == "-no-detach" {
1915                 // This process was invoked by a parent process, which
1916                 // has passed along its own arguments, including
1917                 // -detach, after the leading -no-detach flag.  Strip
1918                 // the leading -no-detach flag (it's not recognized by
1919                 // flags.Parse()) and ignore the -detach flag that
1920                 // comes later.
1921                 args = args[1:]
1922                 ignoreDetachFlag = true
1923         }
1924
1925         if ok, code := cmd.ParseFlags(flags, prog, args, "container-uuid", stderr); !ok {
1926                 return code
1927         } else if *version {
1928                 fmt.Fprintln(stdout, prog, cmd.Version.String())
1929                 return 0
1930         } else if !*list && flags.NArg() != 1 {
1931                 fmt.Fprintf(stderr, "missing required argument: container-uuid (try -help)\n")
1932                 return 2
1933         }
1934
1935         containerUUID := flags.Arg(0)
1936
1937         switch {
1938         case *detach && !ignoreDetachFlag:
1939                 return Detach(containerUUID, prog, args, stdin, stdout, stderr)
1940         case *kill >= 0:
1941                 return KillProcess(containerUUID, syscall.Signal(*kill), stdout, stderr)
1942         case *list:
1943                 return ListProcesses(stdin, stdout, stderr)
1944         }
1945
1946         if len(containerUUID) != 27 {
1947                 log.Printf("usage: %s [options] UUID", prog)
1948                 return 1
1949         }
1950
1951         var keepstoreLogbuf bufThenWrite
1952         var conf ConfigData
1953         if *stdinConfig {
1954                 err := json.NewDecoder(stdin).Decode(&conf)
1955                 if err != nil {
1956                         log.Printf("decode stdin: %s", err)
1957                         return 1
1958                 }
1959                 for k, v := range conf.Env {
1960                         err = os.Setenv(k, v)
1961                         if err != nil {
1962                                 log.Printf("setenv(%q): %s", k, err)
1963                                 return 1
1964                         }
1965                 }
1966                 if conf.Cluster != nil {
1967                         // ClusterID is missing from the JSON
1968                         // representation, but we need it to generate
1969                         // a valid config file for keepstore, so we
1970                         // fill it using the container UUID prefix.
1971                         conf.Cluster.ClusterID = containerUUID[:5]
1972                 }
1973         } else {
1974                 conf = hpcConfData(containerUUID, *configFile, io.MultiWriter(&keepstoreLogbuf, stderr))
1975         }
1976
1977         log.Printf("crunch-run %s started", cmd.Version.String())
1978         time.Sleep(*sleep)
1979
1980         if *caCertsPath != "" {
1981                 os.Setenv("SSL_CERT_FILE", *caCertsPath)
1982         }
1983
1984         keepstore, err := startLocalKeepstore(conf, io.MultiWriter(&keepstoreLogbuf, stderr))
1985         if err != nil {
1986                 log.Print(err)
1987                 return 1
1988         }
1989         if keepstore != nil {
1990                 defer keepstore.Process.Kill()
1991         }
1992
1993         api, err := arvadosclient.MakeArvadosClient()
1994         if err != nil {
1995                 log.Printf("%s: %v", containerUUID, err)
1996                 return 1
1997         }
1998         // arvadosclient now interprets Retries=10 to mean
1999         // Timeout=10m, retrying with exponential backoff + jitter.
2000         api.Retries = 10
2001
2002         kc, err := keepclient.MakeKeepClient(api)
2003         if err != nil {
2004                 log.Printf("%s: %v", containerUUID, err)
2005                 return 1
2006         }
2007         kc.Retries = 4
2008
2009         cr, err := NewContainerRunner(arvados.NewClientFromEnv(), api, kc, containerUUID)
2010         if err != nil {
2011                 log.Print(err)
2012                 return 1
2013         }
2014
2015         cr.keepstore = keepstore
2016         if keepstore == nil {
2017                 // Log explanation (if any) for why we're not running
2018                 // a local keepstore.
2019                 var buf bytes.Buffer
2020                 keepstoreLogbuf.SetWriter(&buf)
2021                 if buf.Len() > 0 {
2022                         cr.CrunchLog.Printf("%s", strings.TrimSpace(buf.String()))
2023                 }
2024         } else if logWhat := conf.Cluster.Containers.LocalKeepLogsToContainerLog; logWhat == "none" {
2025                 cr.CrunchLog.Printf("using local keepstore process (pid %d) at %s", keepstore.Process.Pid, os.Getenv("ARVADOS_KEEP_SERVICES"))
2026                 keepstoreLogbuf.SetWriter(io.Discard)
2027         } else {
2028                 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"))
2029                 logwriter, err := cr.NewLogWriter("keepstore")
2030                 if err != nil {
2031                         log.Print(err)
2032                         return 1
2033                 }
2034                 cr.keepstoreLogger = NewThrottledLogger(logwriter)
2035
2036                 var writer io.WriteCloser = cr.keepstoreLogger
2037                 if logWhat == "errors" {
2038                         writer = &filterKeepstoreErrorsOnly{WriteCloser: writer}
2039                 } else if logWhat != "all" {
2040                         // should have been caught earlier by
2041                         // dispatcher's config loader
2042                         log.Printf("invalid value for Containers.LocalKeepLogsToContainerLog: %q", logWhat)
2043                         return 1
2044                 }
2045                 err = keepstoreLogbuf.SetWriter(writer)
2046                 if err != nil {
2047                         log.Print(err)
2048                         return 1
2049                 }
2050                 cr.keepstoreLogbuf = &keepstoreLogbuf
2051         }
2052
2053         switch *runtimeEngine {
2054         case "docker":
2055                 cr.executor, err = newDockerExecutor(containerUUID, cr.CrunchLog.Printf, cr.containerWatchdogInterval)
2056         case "singularity":
2057                 cr.executor, err = newSingularityExecutor(cr.CrunchLog.Printf)
2058         default:
2059                 cr.CrunchLog.Printf("%s: unsupported RuntimeEngine %q", containerUUID, *runtimeEngine)
2060                 cr.CrunchLog.Close()
2061                 return 1
2062         }
2063         if err != nil {
2064                 cr.CrunchLog.Printf("%s: %v", containerUUID, err)
2065                 cr.checkBrokenNode(err)
2066                 cr.CrunchLog.Close()
2067                 return 1
2068         }
2069         defer cr.executor.Close()
2070
2071         cr.brokenNodeHook = *brokenNodeHook
2072
2073         gwAuthSecret := os.Getenv("GatewayAuthSecret")
2074         os.Unsetenv("GatewayAuthSecret")
2075         if gwAuthSecret == "" {
2076                 // not safe to run a gateway service without an auth
2077                 // secret
2078                 cr.CrunchLog.Printf("Not starting a gateway server (GatewayAuthSecret was not provided by dispatcher)")
2079         } else {
2080                 gwListen := os.Getenv("GatewayAddress")
2081                 cr.gateway = Gateway{
2082                         Address:       gwListen,
2083                         AuthSecret:    gwAuthSecret,
2084                         ContainerUUID: containerUUID,
2085                         Target:        cr.executor,
2086                         Log:           cr.CrunchLog,
2087                         LogCollection: cr.LogCollection,
2088                 }
2089                 if gwListen == "" {
2090                         // Direct connection won't work, so we use the
2091                         // gateway_address field to indicate the
2092                         // internalURL of the controller process that
2093                         // has the current tunnel connection.
2094                         cr.gateway.ArvadosClient = cr.dispatcherClient
2095                         cr.gateway.UpdateTunnelURL = func(url string) {
2096                                 cr.gateway.Address = "tunnel " + url
2097                                 cr.DispatcherArvClient.Update("containers", containerUUID,
2098                                         arvadosclient.Dict{
2099                                                 "select":    []string{"uuid"},
2100                                                 "container": arvadosclient.Dict{"gateway_address": cr.gateway.Address},
2101                                         }, nil)
2102                         }
2103                 }
2104                 err = cr.gateway.Start()
2105                 if err != nil {
2106                         log.Printf("error starting gateway server: %s", err)
2107                         return 1
2108                 }
2109         }
2110
2111         parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerUUID+".")
2112         if tmperr != nil {
2113                 log.Printf("%s: %v", containerUUID, tmperr)
2114                 return 1
2115         }
2116
2117         cr.parentTemp = parentTemp
2118         cr.statInterval = *statInterval
2119         cr.enableMemoryLimit = *enableMemoryLimit
2120         cr.enableNetwork = *enableNetwork
2121         cr.networkMode = *networkMode
2122         if *cgroupParentSubsystem != "" {
2123                 p, err := findCgroup(os.DirFS("/"), *cgroupParentSubsystem)
2124                 if err != nil {
2125                         log.Printf("fatal: cgroup parent subsystem: %s", err)
2126                         return 1
2127                 }
2128                 cr.setCgroupParent = p
2129         }
2130
2131         if conf.EC2SpotCheck {
2132                 go cr.checkSpotInterruptionNotices()
2133         }
2134
2135         runerr := cr.Run()
2136
2137         if *memprofile != "" {
2138                 f, err := os.Create(*memprofile)
2139                 if err != nil {
2140                         log.Printf("could not create memory profile: %s", err)
2141                 }
2142                 runtime.GC() // get up-to-date statistics
2143                 if err := pprof.WriteHeapProfile(f); err != nil {
2144                         log.Printf("could not write memory profile: %s", err)
2145                 }
2146                 closeerr := f.Close()
2147                 if closeerr != nil {
2148                         log.Printf("closing memprofile file: %s", err)
2149                 }
2150         }
2151
2152         if runerr != nil {
2153                 log.Printf("%s: %v", containerUUID, runerr)
2154                 return 1
2155         }
2156         return 0
2157 }
2158
2159 // Try to load ConfigData in hpc (slurm/lsf) environment. This means
2160 // loading the cluster config from the specified file and (if that
2161 // works) getting the runtime_constraints container field from
2162 // controller to determine # VCPUs so we can calculate KeepBuffers.
2163 func hpcConfData(uuid string, configFile string, stderr io.Writer) ConfigData {
2164         var conf ConfigData
2165         conf.Cluster = loadClusterConfigFile(configFile, stderr)
2166         if conf.Cluster == nil {
2167                 // skip loading the container record -- we won't be
2168                 // able to start local keepstore anyway.
2169                 return conf
2170         }
2171         arv, err := arvadosclient.MakeArvadosClient()
2172         if err != nil {
2173                 fmt.Fprintf(stderr, "error setting up arvadosclient: %s\n", err)
2174                 return conf
2175         }
2176         // arvadosclient now interprets Retries=10 to mean
2177         // Timeout=10m, retrying with exponential backoff + jitter.
2178         arv.Retries = 10
2179         var ctr arvados.Container
2180         err = arv.Call("GET", "containers", uuid, "", arvadosclient.Dict{"select": []string{"runtime_constraints"}}, &ctr)
2181         if err != nil {
2182                 fmt.Fprintf(stderr, "error getting container record: %s\n", err)
2183                 return conf
2184         }
2185         if ctr.RuntimeConstraints.VCPUs > 0 {
2186                 conf.KeepBuffers = ctr.RuntimeConstraints.VCPUs * conf.Cluster.Containers.LocalKeepBlobBuffersPerVCPU
2187         }
2188         return conf
2189 }
2190
2191 // Load cluster config file from given path. If an error occurs, log
2192 // the error to stderr and return nil.
2193 func loadClusterConfigFile(path string, stderr io.Writer) *arvados.Cluster {
2194         ldr := config.NewLoader(&bytes.Buffer{}, ctxlog.New(stderr, "plain", "info"))
2195         ldr.Path = path
2196         cfg, err := ldr.Load()
2197         if err != nil {
2198                 fmt.Fprintf(stderr, "could not load config file %s: %s\n", path, err)
2199                 return nil
2200         }
2201         cluster, err := cfg.GetCluster("")
2202         if err != nil {
2203                 fmt.Fprintf(stderr, "could not use config file %s: %s\n", path, err)
2204                 return nil
2205         }
2206         fmt.Fprintf(stderr, "loaded config file %s\n", path)
2207         return cluster
2208 }
2209
2210 func startLocalKeepstore(configData ConfigData, logbuf io.Writer) (*exec.Cmd, error) {
2211         if configData.KeepBuffers < 1 {
2212                 fmt.Fprintf(logbuf, "not starting a local keepstore process because KeepBuffers=%v in config\n", configData.KeepBuffers)
2213                 return nil, nil
2214         }
2215         if configData.Cluster == nil {
2216                 fmt.Fprint(logbuf, "not starting a local keepstore process because cluster config file was not loaded\n")
2217                 return nil, nil
2218         }
2219         for uuid, vol := range configData.Cluster.Volumes {
2220                 if len(vol.AccessViaHosts) > 0 {
2221                         fmt.Fprintf(logbuf, "not starting a local keepstore process because a volume (%s) uses AccessViaHosts\n", uuid)
2222                         return nil, nil
2223                 }
2224                 if !vol.ReadOnly && vol.Replication < configData.Cluster.Collections.DefaultReplication {
2225                         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)
2226                         return nil, nil
2227                 }
2228         }
2229
2230         // Rather than have an alternate way to tell keepstore how
2231         // many buffers to use, etc., when starting it this way, we
2232         // just modify the cluster configuration that we feed it on
2233         // stdin.
2234         ccfg := *configData.Cluster
2235         ccfg.API.MaxKeepBlobBuffers = configData.KeepBuffers
2236         ccfg.Collections.BlobTrash = false
2237         ccfg.Collections.BlobTrashConcurrency = 0
2238         ccfg.Collections.BlobDeleteConcurrency = 0
2239
2240         localaddr := localKeepstoreAddr()
2241         ln, err := net.Listen("tcp", net.JoinHostPort(localaddr, "0"))
2242         if err != nil {
2243                 return nil, err
2244         }
2245         _, port, err := net.SplitHostPort(ln.Addr().String())
2246         if err != nil {
2247                 ln.Close()
2248                 return nil, err
2249         }
2250         ln.Close()
2251         url := "http://" + net.JoinHostPort(localaddr, port)
2252
2253         fmt.Fprintf(logbuf, "starting keepstore on %s\n", url)
2254
2255         var confJSON bytes.Buffer
2256         err = json.NewEncoder(&confJSON).Encode(arvados.Config{
2257                 Clusters: map[string]arvados.Cluster{
2258                         ccfg.ClusterID: ccfg,
2259                 },
2260         })
2261         if err != nil {
2262                 return nil, err
2263         }
2264         cmd := exec.Command("/proc/self/exe", "keepstore", "-config=-")
2265         if target, err := os.Readlink(cmd.Path); err == nil && strings.HasSuffix(target, ".test") {
2266                 // If we're a 'go test' process, running
2267                 // /proc/self/exe would start the test suite in a
2268                 // child process, which is not what we want.
2269                 cmd.Path, _ = exec.LookPath("go")
2270                 cmd.Args = append([]string{"go", "run", "../../cmd/arvados-server"}, cmd.Args[1:]...)
2271                 cmd.Env = os.Environ()
2272         }
2273         cmd.Stdin = &confJSON
2274         cmd.Stdout = logbuf
2275         cmd.Stderr = logbuf
2276         cmd.Env = append(cmd.Env,
2277                 "GOGC=10",
2278                 "ARVADOS_SERVICE_INTERNAL_URL="+url)
2279         err = cmd.Start()
2280         if err != nil {
2281                 return nil, fmt.Errorf("error starting keepstore process: %w", err)
2282         }
2283         cmdExited := false
2284         go func() {
2285                 cmd.Wait()
2286                 cmdExited = true
2287         }()
2288         ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*10))
2289         defer cancel()
2290         poll := time.NewTicker(time.Second / 10)
2291         defer poll.Stop()
2292         client := http.Client{}
2293         for range poll.C {
2294                 testReq, err := http.NewRequestWithContext(ctx, "GET", url+"/_health/ping", nil)
2295                 testReq.Header.Set("Authorization", "Bearer "+configData.Cluster.ManagementToken)
2296                 if err != nil {
2297                         return nil, err
2298                 }
2299                 resp, err := client.Do(testReq)
2300                 if err == nil {
2301                         resp.Body.Close()
2302                         if resp.StatusCode == http.StatusOK {
2303                                 break
2304                         }
2305                 }
2306                 if cmdExited {
2307                         return nil, fmt.Errorf("keepstore child process exited")
2308                 }
2309                 if ctx.Err() != nil {
2310                         return nil, fmt.Errorf("timed out waiting for new keepstore process to report healthy")
2311                 }
2312         }
2313         os.Setenv("ARVADOS_KEEP_SERVICES", url)
2314         return cmd, nil
2315 }
2316
2317 // return current uid, gid, groups in a format suitable for logging:
2318 // "crunch-run process has uid=1234(arvados) gid=1234(arvados)
2319 // groups=1234(arvados),114(fuse)"
2320 func currentUserAndGroups() string {
2321         u, err := user.Current()
2322         if err != nil {
2323                 return fmt.Sprintf("error getting current user ID: %s", err)
2324         }
2325         s := fmt.Sprintf("crunch-run process has uid=%s(%s) gid=%s", u.Uid, u.Username, u.Gid)
2326         if g, err := user.LookupGroupId(u.Gid); err == nil {
2327                 s += fmt.Sprintf("(%s)", g.Name)
2328         }
2329         s += " groups="
2330         if gids, err := u.GroupIds(); err == nil {
2331                 for i, gid := range gids {
2332                         if i > 0 {
2333                                 s += ","
2334                         }
2335                         s += gid
2336                         if g, err := user.LookupGroupId(gid); err == nil {
2337                                 s += fmt.Sprintf("(%s)", g.Name)
2338                         }
2339                 }
2340         }
2341         return s
2342 }
2343
2344 // Return a suitable local interface address for a local keepstore
2345 // service. Currently this is the numerically lowest non-loopback ipv4
2346 // address assigned to a local interface that is not in any of the
2347 // link-local/vpn/loopback ranges 169.254/16, 100.64/10, or 127/8.
2348 func localKeepstoreAddr() string {
2349         var ips []net.IP
2350         // Ignore error (proceed with zero IPs)
2351         addrs, _ := processIPs(os.Getpid())
2352         for addr := range addrs {
2353                 ip := net.ParseIP(addr)
2354                 if ip == nil {
2355                         // invalid
2356                         continue
2357                 }
2358                 if ip.Mask(net.CIDRMask(8, 32)).Equal(net.IPv4(127, 0, 0, 0)) ||
2359                         ip.Mask(net.CIDRMask(10, 32)).Equal(net.IPv4(100, 64, 0, 0)) ||
2360                         ip.Mask(net.CIDRMask(16, 32)).Equal(net.IPv4(169, 254, 0, 0)) {
2361                         // unsuitable
2362                         continue
2363                 }
2364                 ips = append(ips, ip)
2365         }
2366         if len(ips) == 0 {
2367                 return "0.0.0.0"
2368         }
2369         sort.Slice(ips, func(ii, jj int) bool {
2370                 i, j := ips[ii], ips[jj]
2371                 if len(i) != len(j) {
2372                         return len(i) < len(j)
2373                 }
2374                 for x := range i {
2375                         if i[x] != j[x] {
2376                                 return i[x] < j[x]
2377                         }
2378                 }
2379                 return false
2380         })
2381         return ips[0].String()
2382 }
2383
2384 func (cr *ContainerRunner) loadPrices() {
2385         buf, err := os.ReadFile(filepath.Join(lockdir, pricesfile))
2386         if err != nil {
2387                 if !os.IsNotExist(err) {
2388                         cr.CrunchLog.Printf("loadPrices: read: %s", err)
2389                 }
2390                 return
2391         }
2392         var prices []cloud.InstancePrice
2393         err = json.Unmarshal(buf, &prices)
2394         if err != nil {
2395                 cr.CrunchLog.Printf("loadPrices: decode: %s", err)
2396                 return
2397         }
2398         cr.pricesLock.Lock()
2399         defer cr.pricesLock.Unlock()
2400         var lastKnown time.Time
2401         if len(cr.prices) > 0 {
2402                 lastKnown = cr.prices[0].StartTime
2403         }
2404         cr.prices = cloud.NormalizePriceHistory(append(prices, cr.prices...))
2405         for i := len(cr.prices) - 1; i >= 0; i-- {
2406                 price := cr.prices[i]
2407                 if price.StartTime.After(lastKnown) {
2408                         cr.CrunchLog.Printf("Instance price changed to %#.3g at %s", price.Price, price.StartTime.UTC())
2409                 }
2410         }
2411 }
2412
2413 func (cr *ContainerRunner) calculateCost(now time.Time) float64 {
2414         cr.pricesLock.Lock()
2415         defer cr.pricesLock.Unlock()
2416
2417         // First, make a "prices" slice with the real data as far back
2418         // as it goes, and (if needed) a "since the beginning of time"
2419         // placeholder containing a reasonable guess about what the
2420         // price was between cr.costStartTime and the earliest real
2421         // data point.
2422         prices := cr.prices
2423         if len(prices) == 0 {
2424                 // use price info in InstanceType record initially
2425                 // provided by cloud dispatcher
2426                 var p float64
2427                 var it arvados.InstanceType
2428                 if j := os.Getenv("InstanceType"); j != "" && json.Unmarshal([]byte(j), &it) == nil && it.Price > 0 {
2429                         p = it.Price
2430                 }
2431                 prices = []cloud.InstancePrice{{Price: p}}
2432         } else if prices[len(prices)-1].StartTime.After(cr.costStartTime) {
2433                 // guess earlier pricing was the same as the earliest
2434                 // price we know about
2435                 filler := prices[len(prices)-1]
2436                 filler.StartTime = time.Time{}
2437                 prices = append(prices, filler)
2438         }
2439
2440         // Now that our history of price changes goes back at least as
2441         // far as cr.costStartTime, add up the costs for each
2442         // interval.
2443         cost := 0.0
2444         spanEnd := now
2445         for _, ip := range prices {
2446                 spanStart := ip.StartTime
2447                 if spanStart.After(now) {
2448                         // pricing information from the future -- not
2449                         // expected from AWS, but possible in
2450                         // principle, and exercised by tests.
2451                         continue
2452                 }
2453                 last := false
2454                 if spanStart.Before(cr.costStartTime) {
2455                         spanStart = cr.costStartTime
2456                         last = true
2457                 }
2458                 cost += ip.Price * spanEnd.Sub(spanStart).Seconds() / 3600
2459                 if last {
2460                         break
2461                 }
2462                 spanEnd = spanStart
2463         }
2464
2465         return cost
2466 }
2467
2468 func (runner *ContainerRunner) handleSIGUSR2(sigchan chan os.Signal) {
2469         for range sigchan {
2470                 runner.loadPrices()
2471                 update := arvadosclient.Dict{
2472                         "select": []string{"uuid"},
2473                         "container": arvadosclient.Dict{
2474                                 "cost": runner.calculateCost(time.Now()),
2475                         },
2476                 }
2477                 runner.DispatcherArvClient.Update("containers", runner.Container.UUID, update, nil)
2478         }
2479 }