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