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