8363: Report arv-mount error messages as runtime_status warnings.
[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(message 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: " + message,
1118                         },
1119                 },
1120         }, &updated)
1121         if err != nil {
1122                 runner.CrunchLog.Printf("error updating container runtime_status: %s", err)
1123         }
1124 }
1125
1126 // CaptureOutput saves data from the container's output directory if
1127 // needed, and updates the container output accordingly.
1128 func (runner *ContainerRunner) CaptureOutput(bindmounts map[string]bindmount) error {
1129         if runner.Container.RuntimeConstraints.API {
1130                 // Output may have been set directly by the container, so
1131                 // refresh the container record to check.
1132                 err := runner.DispatcherArvClient.Get("containers", runner.Container.UUID,
1133                         nil, &runner.Container)
1134                 if err != nil {
1135                         return err
1136                 }
1137                 if runner.Container.Output != "" {
1138                         // Container output is already set.
1139                         runner.OutputPDH = &runner.Container.Output
1140                         return nil
1141                 }
1142         }
1143
1144         txt, err := (&copier{
1145                 client:        runner.containerClient,
1146                 arvClient:     runner.ContainerArvClient,
1147                 keepClient:    runner.ContainerKeepClient,
1148                 hostOutputDir: runner.HostOutputDir,
1149                 ctrOutputDir:  runner.Container.OutputPath,
1150                 bindmounts:    bindmounts,
1151                 mounts:        runner.Container.Mounts,
1152                 secretMounts:  runner.SecretMounts,
1153                 logger:        runner.CrunchLog,
1154         }).Copy()
1155         if err != nil {
1156                 return err
1157         }
1158         if n := len(regexp.MustCompile(` [0-9a-f]+\+\S*\+R`).FindAllStringIndex(txt, -1)); n > 0 {
1159                 runner.CrunchLog.Printf("Copying %d data blocks from remote input collections...", n)
1160                 fs, err := (&arvados.Collection{ManifestText: txt}).FileSystem(runner.containerClient, runner.ContainerKeepClient)
1161                 if err != nil {
1162                         return err
1163                 }
1164                 txt, err = fs.MarshalManifest(".")
1165                 if err != nil {
1166                         return err
1167                 }
1168         }
1169         var resp arvados.Collection
1170         err = runner.ContainerArvClient.Create("collections", arvadosclient.Dict{
1171                 "ensure_unique_name": true,
1172                 "collection": arvadosclient.Dict{
1173                         "is_trashed":    true,
1174                         "name":          "output for " + runner.Container.UUID,
1175                         "manifest_text": txt,
1176                 },
1177         }, &resp)
1178         if err != nil {
1179                 return fmt.Errorf("error creating output collection: %v", err)
1180         }
1181         runner.OutputPDH = &resp.PortableDataHash
1182         return nil
1183 }
1184
1185 func (runner *ContainerRunner) CleanupDirs() {
1186         if runner.ArvMount != nil {
1187                 var delay int64 = 8
1188                 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1189                 umount.Stdout = runner.CrunchLog
1190                 umount.Stderr = runner.CrunchLog
1191                 runner.CrunchLog.Printf("Running %v", umount.Args)
1192                 umnterr := umount.Start()
1193
1194                 if umnterr != nil {
1195                         runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1196                         runner.ArvMount.Process.Kill()
1197                 } else {
1198                         // If arv-mount --unmount gets stuck for any reason, we
1199                         // don't want to wait for it forever.  Do Wait() in a goroutine
1200                         // so it doesn't block crunch-run.
1201                         umountExit := make(chan error)
1202                         go func() {
1203                                 mnterr := umount.Wait()
1204                                 if mnterr != nil {
1205                                         runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1206                                 }
1207                                 umountExit <- mnterr
1208                         }()
1209
1210                         for again := true; again; {
1211                                 again = false
1212                                 select {
1213                                 case <-umountExit:
1214                                         umount = nil
1215                                         again = true
1216                                 case <-runner.ArvMountExit:
1217                                         break
1218                                 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1219                                         runner.CrunchLog.Printf("Timed out waiting for unmount")
1220                                         if umount != nil {
1221                                                 umount.Process.Kill()
1222                                         }
1223                                         runner.ArvMount.Process.Kill()
1224                                 }
1225                         }
1226                 }
1227                 runner.ArvMount = nil
1228         }
1229
1230         if runner.ArvMountPoint != "" {
1231                 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1232                         runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1233                 }
1234                 runner.ArvMountPoint = ""
1235         }
1236
1237         if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1238                 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1239         }
1240 }
1241
1242 // CommitLogs posts the collection containing the final container logs.
1243 func (runner *ContainerRunner) CommitLogs() error {
1244         func() {
1245                 // Hold cStateLock to prevent races on CrunchLog (e.g., stop()).
1246                 runner.cStateLock.Lock()
1247                 defer runner.cStateLock.Unlock()
1248
1249                 runner.CrunchLog.Print(runner.finalState)
1250
1251                 if runner.arvMountLog != nil {
1252                         runner.arvMountLog.Close()
1253                 }
1254                 runner.CrunchLog.Close()
1255
1256                 // Closing CrunchLog above allows them to be committed to Keep at this
1257                 // point, but re-open crunch log with ArvClient in case there are any
1258                 // other further errors (such as failing to write the log to Keep!)
1259                 // while shutting down
1260                 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{
1261                         ArvClient:     runner.DispatcherArvClient,
1262                         UUID:          runner.Container.UUID,
1263                         loggingStream: "crunch-run",
1264                         writeCloser:   nil,
1265                 })
1266                 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1267         }()
1268
1269         if runner.LogsPDH != nil {
1270                 // If we have already assigned something to LogsPDH,
1271                 // we must be closing the re-opened log, which won't
1272                 // end up getting attached to the container record and
1273                 // therefore doesn't need to be saved as a collection
1274                 // -- it exists only to send logs to other channels.
1275                 return nil
1276         }
1277         saved, err := runner.saveLogCollection(true)
1278         if err != nil {
1279                 return fmt.Errorf("error saving log collection: %s", err)
1280         }
1281         runner.logMtx.Lock()
1282         defer runner.logMtx.Unlock()
1283         runner.LogsPDH = &saved.PortableDataHash
1284         return nil
1285 }
1286
1287 func (runner *ContainerRunner) saveLogCollection(final bool) (response arvados.Collection, err error) {
1288         runner.logMtx.Lock()
1289         defer runner.logMtx.Unlock()
1290         if runner.LogsPDH != nil {
1291                 // Already finalized.
1292                 return
1293         }
1294         updates := arvadosclient.Dict{
1295                 "name": "logs for " + runner.Container.UUID,
1296         }
1297         mt, err1 := runner.LogCollection.MarshalManifest(".")
1298         if err1 == nil {
1299                 // Only send updated manifest text if there was no
1300                 // error.
1301                 updates["manifest_text"] = mt
1302         }
1303
1304         // Even if flushing the manifest had an error, we still want
1305         // to update the log record, if possible, to push the trash_at
1306         // and delete_at times into the future.  Details on bug
1307         // #17293.
1308         if final {
1309                 updates["is_trashed"] = true
1310         } else {
1311                 exp := time.Now().Add(crunchLogUpdatePeriod * 24)
1312                 updates["trash_at"] = exp
1313                 updates["delete_at"] = exp
1314         }
1315         reqBody := arvadosclient.Dict{"collection": updates}
1316         var err2 error
1317         if runner.logUUID == "" {
1318                 reqBody["ensure_unique_name"] = true
1319                 err2 = runner.DispatcherArvClient.Create("collections", reqBody, &response)
1320         } else {
1321                 err2 = runner.DispatcherArvClient.Update("collections", runner.logUUID, reqBody, &response)
1322         }
1323         if err2 == nil {
1324                 runner.logUUID = response.UUID
1325         }
1326
1327         if err1 != nil || err2 != nil {
1328                 err = fmt.Errorf("error recording logs: %q, %q", err1, err2)
1329         }
1330         return
1331 }
1332
1333 // UpdateContainerRunning updates the container state to "Running"
1334 func (runner *ContainerRunner) UpdateContainerRunning() error {
1335         runner.cStateLock.Lock()
1336         defer runner.cStateLock.Unlock()
1337         if runner.cCancelled {
1338                 return ErrCancelled
1339         }
1340         return runner.DispatcherArvClient.Update("containers", runner.Container.UUID,
1341                 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running", "gateway_address": runner.gateway.Address}}, nil)
1342 }
1343
1344 // ContainerToken returns the api_token the container (and any
1345 // arv-mount processes) are allowed to use.
1346 func (runner *ContainerRunner) ContainerToken() (string, error) {
1347         if runner.token != "" {
1348                 return runner.token, nil
1349         }
1350
1351         var auth arvados.APIClientAuthorization
1352         err := runner.DispatcherArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1353         if err != nil {
1354                 return "", err
1355         }
1356         runner.token = fmt.Sprintf("v2/%s/%s/%s", auth.UUID, auth.APIToken, runner.Container.UUID)
1357         return runner.token, nil
1358 }
1359
1360 // UpdateContainerFinal updates the container record state on API
1361 // server to "Complete" or "Cancelled"
1362 func (runner *ContainerRunner) UpdateContainerFinal() error {
1363         update := arvadosclient.Dict{}
1364         update["state"] = runner.finalState
1365         if runner.LogsPDH != nil {
1366                 update["log"] = *runner.LogsPDH
1367         }
1368         if runner.finalState == "Complete" {
1369                 if runner.ExitCode != nil {
1370                         update["exit_code"] = *runner.ExitCode
1371                 }
1372                 if runner.OutputPDH != nil {
1373                         update["output"] = *runner.OutputPDH
1374                 }
1375         }
1376         return runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1377 }
1378
1379 // IsCancelled returns the value of Cancelled, with goroutine safety.
1380 func (runner *ContainerRunner) IsCancelled() bool {
1381         runner.cStateLock.Lock()
1382         defer runner.cStateLock.Unlock()
1383         return runner.cCancelled
1384 }
1385
1386 // NewArvLogWriter creates an ArvLogWriter
1387 func (runner *ContainerRunner) NewArvLogWriter(name string) (io.WriteCloser, error) {
1388         writer, err := runner.LogCollection.OpenFile(name+".txt", os.O_CREATE|os.O_WRONLY, 0666)
1389         if err != nil {
1390                 return nil, err
1391         }
1392         return &ArvLogWriter{
1393                 ArvClient:     runner.DispatcherArvClient,
1394                 UUID:          runner.Container.UUID,
1395                 loggingStream: name,
1396                 writeCloser:   writer,
1397         }, nil
1398 }
1399
1400 // Run the full container lifecycle.
1401 func (runner *ContainerRunner) Run() (err error) {
1402         runner.CrunchLog.Printf("crunch-run %s started", cmd.Version.String())
1403         runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1404
1405         hostname, hosterr := os.Hostname()
1406         if hosterr != nil {
1407                 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1408         } else {
1409                 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1410         }
1411
1412         runner.finalState = "Queued"
1413
1414         defer func() {
1415                 runner.CleanupDirs()
1416
1417                 runner.CrunchLog.Printf("crunch-run finished")
1418                 runner.CrunchLog.Close()
1419         }()
1420
1421         err = runner.fetchContainerRecord()
1422         if err != nil {
1423                 return
1424         }
1425         if runner.Container.State != "Locked" {
1426                 return fmt.Errorf("dispatch error detected: container %q has state %q", runner.Container.UUID, runner.Container.State)
1427         }
1428
1429         var bindmounts map[string]bindmount
1430         defer func() {
1431                 // checkErr prints e (unless it's nil) and sets err to
1432                 // e (unless err is already non-nil). Thus, if err
1433                 // hasn't already been assigned when Run() returns,
1434                 // this cleanup func will cause Run() to return the
1435                 // first non-nil error that is passed to checkErr().
1436                 checkErr := func(errorIn string, e error) {
1437                         if e == nil {
1438                                 return
1439                         }
1440                         runner.CrunchLog.Printf("error in %s: %v", errorIn, e)
1441                         if err == nil {
1442                                 err = e
1443                         }
1444                         if runner.finalState == "Complete" {
1445                                 // There was an error in the finalization.
1446                                 runner.finalState = "Cancelled"
1447                         }
1448                 }
1449
1450                 // Log the error encountered in Run(), if any
1451                 checkErr("Run", err)
1452
1453                 if runner.finalState == "Queued" {
1454                         runner.UpdateContainerFinal()
1455                         return
1456                 }
1457
1458                 if runner.IsCancelled() {
1459                         runner.finalState = "Cancelled"
1460                         // but don't return yet -- we still want to
1461                         // capture partial output and write logs
1462                 }
1463
1464                 if bindmounts != nil {
1465                         checkErr("CaptureOutput", runner.CaptureOutput(bindmounts))
1466                 }
1467                 checkErr("stopHoststat", runner.stopHoststat())
1468                 checkErr("CommitLogs", runner.CommitLogs())
1469                 runner.CleanupDirs()
1470                 checkErr("UpdateContainerFinal", runner.UpdateContainerFinal())
1471         }()
1472
1473         runner.setupSignals()
1474         err = runner.startHoststat()
1475         if err != nil {
1476                 return
1477         }
1478
1479         // set up FUSE mount and binds
1480         bindmounts, err = runner.SetupMounts()
1481         if err != nil {
1482                 runner.finalState = "Cancelled"
1483                 err = fmt.Errorf("While setting up mounts: %v", err)
1484                 return
1485         }
1486
1487         // check for and/or load image
1488         imageID, err := runner.LoadImage()
1489         if err != nil {
1490                 if !runner.checkBrokenNode(err) {
1491                         // Failed to load image but not due to a "broken node"
1492                         // condition, probably user error.
1493                         runner.finalState = "Cancelled"
1494                 }
1495                 err = fmt.Errorf("While loading container image: %v", err)
1496                 return
1497         }
1498
1499         err = runner.CreateContainer(imageID, bindmounts)
1500         if err != nil {
1501                 return
1502         }
1503         err = runner.LogHostInfo()
1504         if err != nil {
1505                 return
1506         }
1507         err = runner.LogNodeRecord()
1508         if err != nil {
1509                 return
1510         }
1511         err = runner.LogContainerRecord()
1512         if err != nil {
1513                 return
1514         }
1515
1516         if runner.IsCancelled() {
1517                 return
1518         }
1519
1520         err = runner.UpdateContainerRunning()
1521         if err != nil {
1522                 return
1523         }
1524         runner.finalState = "Cancelled"
1525
1526         err = runner.startCrunchstat()
1527         if err != nil {
1528                 return
1529         }
1530
1531         err = runner.StartContainer()
1532         if err != nil {
1533                 runner.checkBrokenNode(err)
1534                 return
1535         }
1536
1537         err = runner.WaitFinish()
1538         if err == nil && !runner.IsCancelled() {
1539                 runner.finalState = "Complete"
1540         }
1541         return
1542 }
1543
1544 // Fetch the current container record (uuid = runner.Container.UUID)
1545 // into runner.Container.
1546 func (runner *ContainerRunner) fetchContainerRecord() error {
1547         reader, err := runner.DispatcherArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1548         if err != nil {
1549                 return fmt.Errorf("error fetching container record: %v", err)
1550         }
1551         defer reader.Close()
1552
1553         dec := json.NewDecoder(reader)
1554         dec.UseNumber()
1555         err = dec.Decode(&runner.Container)
1556         if err != nil {
1557                 return fmt.Errorf("error decoding container record: %v", err)
1558         }
1559
1560         var sm struct {
1561                 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
1562         }
1563
1564         containerToken, err := runner.ContainerToken()
1565         if err != nil {
1566                 return fmt.Errorf("error getting container token: %v", err)
1567         }
1568
1569         runner.ContainerArvClient, runner.ContainerKeepClient,
1570                 runner.containerClient, err = runner.MkArvClient(containerToken)
1571         if err != nil {
1572                 return fmt.Errorf("error creating container API client: %v", err)
1573         }
1574
1575         runner.ContainerKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1576         runner.DispatcherKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1577
1578         err = runner.ContainerArvClient.Call("GET", "containers", runner.Container.UUID, "secret_mounts", nil, &sm)
1579         if err != nil {
1580                 if apierr, ok := err.(arvadosclient.APIServerError); !ok || apierr.HttpStatusCode != 404 {
1581                         return fmt.Errorf("error fetching secret_mounts: %v", err)
1582                 }
1583                 // ok && apierr.HttpStatusCode == 404, which means
1584                 // secret_mounts isn't supported by this API server.
1585         }
1586         runner.SecretMounts = sm.SecretMounts
1587
1588         return nil
1589 }
1590
1591 // NewContainerRunner creates a new container runner.
1592 func NewContainerRunner(dispatcherClient *arvados.Client,
1593         dispatcherArvClient IArvadosClient,
1594         dispatcherKeepClient IKeepClient,
1595         containerUUID string) (*ContainerRunner, error) {
1596
1597         cr := &ContainerRunner{
1598                 dispatcherClient:     dispatcherClient,
1599                 DispatcherArvClient:  dispatcherArvClient,
1600                 DispatcherKeepClient: dispatcherKeepClient,
1601         }
1602         cr.NewLogWriter = cr.NewArvLogWriter
1603         cr.RunArvMount = cr.ArvMountCmd
1604         cr.MkTempDir = ioutil.TempDir
1605         cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1606                 cl, err := arvadosclient.MakeArvadosClient()
1607                 if err != nil {
1608                         return nil, nil, nil, err
1609                 }
1610                 cl.ApiToken = token
1611                 kc, err := keepclient.MakeKeepClient(cl)
1612                 if err != nil {
1613                         return nil, nil, nil, err
1614                 }
1615                 c2 := arvados.NewClientFromEnv()
1616                 c2.AuthToken = token
1617                 return cl, kc, c2, nil
1618         }
1619         var err error
1620         cr.LogCollection, err = (&arvados.Collection{}).FileSystem(cr.dispatcherClient, cr.DispatcherKeepClient)
1621         if err != nil {
1622                 return nil, err
1623         }
1624         cr.Container.UUID = containerUUID
1625         w, err := cr.NewLogWriter("crunch-run")
1626         if err != nil {
1627                 return nil, err
1628         }
1629         cr.CrunchLog = NewThrottledLogger(w)
1630         cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1631
1632         loadLogThrottleParams(dispatcherArvClient)
1633         go cr.updateLogs()
1634
1635         return cr, nil
1636 }
1637
1638 func (command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
1639         flags := flag.NewFlagSet(prog, flag.ContinueOnError)
1640         statInterval := flags.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1641         cgroupRoot := flags.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1642         cgroupParent := flags.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1643         cgroupParentSubsystem := flags.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1644         caCertsPath := flags.String("ca-certs", "", "Path to TLS root certificates")
1645         detach := flags.Bool("detach", false, "Detach from parent process and run in the background")
1646         stdinEnv := flags.Bool("stdin-env", false, "Load environment variables from JSON message on stdin")
1647         sleep := flags.Duration("sleep", 0, "Delay before starting (testing use only)")
1648         kill := flags.Int("kill", -1, "Send signal to an existing crunch-run process for given UUID")
1649         list := flags.Bool("list", false, "List UUIDs of existing crunch-run processes")
1650         enableMemoryLimit := flags.Bool("enable-memory-limit", true, "tell container runtime to limit container's memory usage")
1651         enableNetwork := flags.String("container-enable-networking", "default", "enable networking \"always\" (for all containers) or \"default\" (for containers that request it)")
1652         networkMode := flags.String("container-network-mode", "default", `Docker network mode for container (use any argument valid for docker --net)`)
1653         memprofile := flags.String("memprofile", "", "write memory profile to `file` after running container")
1654         runtimeEngine := flags.String("runtime-engine", "docker", "container runtime: docker or singularity")
1655         flags.Duration("check-containerd", 0, "Ignored. Exists for compatibility with older versions.")
1656
1657         ignoreDetachFlag := false
1658         if len(args) > 0 && args[0] == "-no-detach" {
1659                 // This process was invoked by a parent process, which
1660                 // has passed along its own arguments, including
1661                 // -detach, after the leading -no-detach flag.  Strip
1662                 // the leading -no-detach flag (it's not recognized by
1663                 // flags.Parse()) and ignore the -detach flag that
1664                 // comes later.
1665                 args = args[1:]
1666                 ignoreDetachFlag = true
1667         }
1668
1669         if err := flags.Parse(args); err == flag.ErrHelp {
1670                 return 0
1671         } else if err != nil {
1672                 log.Print(err)
1673                 return 1
1674         }
1675
1676         if *stdinEnv && !ignoreDetachFlag {
1677                 // Load env vars on stdin if asked (but not in a
1678                 // detached child process, in which case stdin is
1679                 // /dev/null).
1680                 err := loadEnv(os.Stdin)
1681                 if err != nil {
1682                         log.Print(err)
1683                         return 1
1684                 }
1685         }
1686
1687         containerUUID := flags.Arg(0)
1688
1689         switch {
1690         case *detach && !ignoreDetachFlag:
1691                 return Detach(containerUUID, prog, args, os.Stdout, os.Stderr)
1692         case *kill >= 0:
1693                 return KillProcess(containerUUID, syscall.Signal(*kill), os.Stdout, os.Stderr)
1694         case *list:
1695                 return ListProcesses(os.Stdout, os.Stderr)
1696         }
1697
1698         if containerUUID == "" {
1699                 log.Printf("usage: %s [options] UUID", prog)
1700                 return 1
1701         }
1702
1703         log.Printf("crunch-run %s started", cmd.Version.String())
1704         time.Sleep(*sleep)
1705
1706         if *caCertsPath != "" {
1707                 arvadosclient.CertFiles = []string{*caCertsPath}
1708         }
1709
1710         api, err := arvadosclient.MakeArvadosClient()
1711         if err != nil {
1712                 log.Printf("%s: %v", containerUUID, err)
1713                 return 1
1714         }
1715         api.Retries = 8
1716
1717         kc, kcerr := keepclient.MakeKeepClient(api)
1718         if kcerr != nil {
1719                 log.Printf("%s: %v", containerUUID, kcerr)
1720                 return 1
1721         }
1722         kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1723         kc.Retries = 4
1724
1725         cr, err := NewContainerRunner(arvados.NewClientFromEnv(), api, kc, containerUUID)
1726         if err != nil {
1727                 log.Print(err)
1728                 return 1
1729         }
1730
1731         switch *runtimeEngine {
1732         case "docker":
1733                 cr.executor, err = newDockerExecutor(containerUUID, cr.CrunchLog.Printf, cr.containerWatchdogInterval)
1734         case "singularity":
1735                 cr.executor, err = newSingularityExecutor(cr.CrunchLog.Printf)
1736         default:
1737                 cr.CrunchLog.Printf("%s: unsupported RuntimeEngine %q", containerUUID, *runtimeEngine)
1738                 cr.CrunchLog.Close()
1739                 return 1
1740         }
1741         if err != nil {
1742                 cr.CrunchLog.Printf("%s: %v", containerUUID, err)
1743                 cr.checkBrokenNode(err)
1744                 cr.CrunchLog.Close()
1745                 return 1
1746         }
1747         defer cr.executor.Close()
1748
1749         gwAuthSecret := os.Getenv("GatewayAuthSecret")
1750         os.Unsetenv("GatewayAuthSecret")
1751         if gwAuthSecret == "" {
1752                 // not safe to run a gateway service without an auth
1753                 // secret
1754                 cr.CrunchLog.Printf("Not starting a gateway server (GatewayAuthSecret was not provided by dispatcher)")
1755         } else if gwListen := os.Getenv("GatewayAddress"); gwListen == "" {
1756                 // dispatcher did not tell us which external IP
1757                 // address to advertise --> no gateway service
1758                 cr.CrunchLog.Printf("Not starting a gateway server (GatewayAddress was not provided by dispatcher)")
1759         } else if de, ok := cr.executor.(*dockerExecutor); ok {
1760                 cr.gateway = Gateway{
1761                         Address:            gwListen,
1762                         AuthSecret:         gwAuthSecret,
1763                         ContainerUUID:      containerUUID,
1764                         DockerContainerID:  &de.containerID,
1765                         Log:                cr.CrunchLog,
1766                         ContainerIPAddress: dockerContainerIPAddress(&de.containerID),
1767                 }
1768                 err = cr.gateway.Start()
1769                 if err != nil {
1770                         log.Printf("error starting gateway server: %s", err)
1771                         return 1
1772                 }
1773         }
1774
1775         parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerUUID+".")
1776         if tmperr != nil {
1777                 log.Printf("%s: %v", containerUUID, tmperr)
1778                 return 1
1779         }
1780
1781         cr.parentTemp = parentTemp
1782         cr.statInterval = *statInterval
1783         cr.cgroupRoot = *cgroupRoot
1784         cr.expectCgroupParent = *cgroupParent
1785         cr.enableMemoryLimit = *enableMemoryLimit
1786         cr.enableNetwork = *enableNetwork
1787         cr.networkMode = *networkMode
1788         if *cgroupParentSubsystem != "" {
1789                 p := findCgroup(*cgroupParentSubsystem)
1790                 cr.setCgroupParent = p
1791                 cr.expectCgroupParent = p
1792         }
1793
1794         runerr := cr.Run()
1795
1796         if *memprofile != "" {
1797                 f, err := os.Create(*memprofile)
1798                 if err != nil {
1799                         log.Printf("could not create memory profile: %s", err)
1800                 }
1801                 runtime.GC() // get up-to-date statistics
1802                 if err := pprof.WriteHeapProfile(f); err != nil {
1803                         log.Printf("could not write memory profile: %s", err)
1804                 }
1805                 closeerr := f.Close()
1806                 if closeerr != nil {
1807                         log.Printf("closing memprofile file: %s", err)
1808                 }
1809         }
1810
1811         if runerr != nil {
1812                 log.Printf("%s: %v", containerUUID, runerr)
1813                 return 1
1814         }
1815         return 0
1816 }
1817
1818 func loadEnv(rdr io.Reader) error {
1819         buf, err := ioutil.ReadAll(rdr)
1820         if err != nil {
1821                 return fmt.Errorf("read stdin: %s", err)
1822         }
1823         var env map[string]string
1824         err = json.Unmarshal(buf, &env)
1825         if err != nil {
1826                 return fmt.Errorf("decode stdin: %s", err)
1827         }
1828         for k, v := range env {
1829                 err = os.Setenv(k, v)
1830                 if err != nil {
1831                         return fmt.Errorf("setenv(%q): %s", k, err)
1832                 }
1833         }
1834         return nil
1835 }