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