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