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