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