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