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