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