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