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