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