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