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