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