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