Merge branch '18102-max-dispatch-attempts'
[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         executorStdin  io.Closer
82         executorStdout io.Closer
83         executorStderr io.Closer
84
85         // Dispatcher client is initialized with the Dispatcher token.
86         // This is a privileged token used to manage container status
87         // and logs.
88         //
89         // We have both dispatcherClient and DispatcherArvClient
90         // because there are two different incompatible Arvados Go
91         // SDKs and we have to use both (hopefully this gets fixed in
92         // #14467)
93         dispatcherClient     *arvados.Client
94         DispatcherArvClient  IArvadosClient
95         DispatcherKeepClient IKeepClient
96
97         // Container client is initialized with the Container token
98         // This token controls the permissions of the container, and
99         // must be used for operations such as reading collections.
100         //
101         // Same comment as above applies to
102         // containerClient/ContainerArvClient.
103         containerClient     *arvados.Client
104         ContainerArvClient  IArvadosClient
105         ContainerKeepClient IKeepClient
106
107         Container     arvados.Container
108         token         string
109         ExitCode      *int
110         NewLogWriter  NewLogWriter
111         CrunchLog     *ThrottledLogger
112         logUUID       string
113         logMtx        sync.Mutex
114         LogCollection arvados.CollectionFileSystem
115         LogsPDH       *string
116         RunArvMount   RunArvMount
117         MkTempDir     MkTempDir
118         ArvMount      *exec.Cmd
119         ArvMountPoint string
120         HostOutputDir string
121         Volumes       map[string]struct{}
122         OutputPDH     *string
123         SigChan       chan os.Signal
124         ArvMountExit  chan error
125         SecretMounts  map[string]arvados.Mount
126         MkArvClient   func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error)
127         finalState    string
128         parentTemp    string
129
130         statLogger       io.WriteCloser
131         statReporter     *crunchstat.Reporter
132         hoststatLogger   io.WriteCloser
133         hoststatReporter *crunchstat.Reporter
134         statInterval     time.Duration
135         cgroupRoot       string
136         // What we expect the container's cgroup parent to be.
137         expectCgroupParent string
138         // What we tell docker to use as the container's cgroup
139         // parent. Note: Ideally we would use the same field for both
140         // expectCgroupParent and setCgroupParent, and just make it
141         // default to "docker". However, when using docker < 1.10 with
142         // systemd, specifying a non-empty cgroup parent (even the
143         // default value "docker") hits a docker bug
144         // (https://github.com/docker/docker/issues/17126). Using two
145         // separate fields makes it possible to use the "expect cgroup
146         // parent to be X" feature even on sites where the "specify
147         // cgroup parent" feature breaks.
148         setCgroupParent string
149
150         cStateLock sync.Mutex
151         cCancelled bool // StopContainer() invoked
152
153         enableMemoryLimit bool
154         enableNetwork     string // one of "default" or "always"
155         networkMode       string // "none", "host", or "" -- passed through to executor
156         arvMountLog       *ThrottledLogger
157
158         containerWatchdogInterval time.Duration
159
160         gateway Gateway
161 }
162
163 // setupSignals sets up signal handling to gracefully terminate the
164 // underlying container and update state when receiving a TERM, INT or
165 // QUIT signal.
166 func (runner *ContainerRunner) setupSignals() {
167         runner.SigChan = make(chan os.Signal, 1)
168         signal.Notify(runner.SigChan, syscall.SIGTERM)
169         signal.Notify(runner.SigChan, syscall.SIGINT)
170         signal.Notify(runner.SigChan, syscall.SIGQUIT)
171
172         go func(sig chan os.Signal) {
173                 for s := range sig {
174                         runner.stop(s)
175                 }
176         }(runner.SigChan)
177 }
178
179 // stop the underlying container.
180 func (runner *ContainerRunner) stop(sig os.Signal) {
181         runner.cStateLock.Lock()
182         defer runner.cStateLock.Unlock()
183         if sig != nil {
184                 runner.CrunchLog.Printf("caught signal: %v", sig)
185         }
186         runner.cCancelled = true
187         runner.CrunchLog.Printf("stopping container")
188         err := runner.executor.Stop()
189         if err != nil {
190                 runner.CrunchLog.Printf("error stopping container: %s", err)
191         }
192 }
193
194 var errorBlacklist = []string{
195         "(?ms).*[Cc]annot connect to the Docker daemon.*",
196         "(?ms).*oci runtime error.*starting container process.*container init.*mounting.*to rootfs.*no such file or directory.*",
197         "(?ms).*grpc: the connection is unavailable.*",
198 }
199 var brokenNodeHook *string = flag.String("broken-node-hook", "", "Script to run if node is detected to be broken (for example, Docker daemon is not running)")
200
201 func (runner *ContainerRunner) runBrokenNodeHook() {
202         if *brokenNodeHook == "" {
203                 path := filepath.Join(lockdir, brokenfile)
204                 runner.CrunchLog.Printf("Writing %s to mark node as broken", path)
205                 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0700)
206                 if err != nil {
207                         runner.CrunchLog.Printf("Error writing %s: %s", path, err)
208                         return
209                 }
210                 f.Close()
211         } else {
212                 runner.CrunchLog.Printf("Running broken node hook %q", *brokenNodeHook)
213                 // run killme script
214                 c := exec.Command(*brokenNodeHook)
215                 c.Stdout = runner.CrunchLog
216                 c.Stderr = runner.CrunchLog
217                 err := c.Run()
218                 if err != nil {
219                         runner.CrunchLog.Printf("Error running broken node hook: %v", err)
220                 }
221         }
222 }
223
224 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
225         for _, d := range errorBlacklist {
226                 if m, e := regexp.MatchString(d, goterr.Error()); m && e == nil {
227                         runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
228                         runner.runBrokenNodeHook()
229                         return true
230                 }
231         }
232         return false
233 }
234
235 // LoadImage determines the docker image id from the container record and
236 // checks if it is available in the local Docker image store.  If not, it loads
237 // the image from Keep.
238 func (runner *ContainerRunner) LoadImage() (string, error) {
239         runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
240
241         d, err := os.Open(runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage)
242         if err != nil {
243                 return "", err
244         }
245         defer d.Close()
246         allfiles, err := d.Readdirnames(-1)
247         if err != nil {
248                 return "", err
249         }
250         var tarfiles []string
251         for _, fnm := range allfiles {
252                 if strings.HasSuffix(fnm, ".tar") {
253                         tarfiles = append(tarfiles, fnm)
254                 }
255         }
256         if len(tarfiles) == 0 {
257                 return "", fmt.Errorf("image collection does not include a .tar image file")
258         }
259         if len(tarfiles) > 1 {
260                 return "", fmt.Errorf("cannot choose from multiple tar files in image collection: %v", tarfiles)
261         }
262         imageID := tarfiles[0][:len(tarfiles[0])-4]
263         imageTarballPath := runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage + "/" + imageID + ".tar"
264         runner.CrunchLog.Printf("Using Docker image id %q", imageID)
265
266         runner.CrunchLog.Print("Loading Docker image from keep")
267         err = runner.executor.LoadImage(imageID, imageTarballPath, runner.Container, runner.ArvMountPoint,
268                 runner.containerClient)
269         if err != nil {
270                 return "", err
271         }
272
273         return imageID, nil
274 }
275
276 func (runner *ContainerRunner) ArvMountCmd(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                 "--storage-classes", strings.Join(runner.Container.OutputStorageClasses, ","),
399                 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
400
401         if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
402                 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
403         }
404
405         collectionPaths := []string{}
406         needCertMount := true
407         type copyFile struct {
408                 src  string
409                 bind string
410         }
411         var copyFiles []copyFile
412
413         var binds []string
414         for bind := range runner.Container.Mounts {
415                 binds = append(binds, bind)
416         }
417         for bind := range runner.SecretMounts {
418                 if _, ok := runner.Container.Mounts[bind]; ok {
419                         return nil, fmt.Errorf("secret mount %q conflicts with regular mount", bind)
420                 }
421                 if runner.SecretMounts[bind].Kind != "json" &&
422                         runner.SecretMounts[bind].Kind != "text" {
423                         return nil, fmt.Errorf("secret mount %q type is %q but only 'json' and 'text' are permitted",
424                                 bind, runner.SecretMounts[bind].Kind)
425                 }
426                 binds = append(binds, bind)
427         }
428         sort.Strings(binds)
429
430         for _, bind := range binds {
431                 mnt, ok := runner.Container.Mounts[bind]
432                 if !ok {
433                         mnt = runner.SecretMounts[bind]
434                 }
435                 if bind == "stdout" || bind == "stderr" {
436                         // Is it a "file" mount kind?
437                         if mnt.Kind != "file" {
438                                 return nil, fmt.Errorf("unsupported mount kind '%s' for %s: only 'file' is supported", mnt.Kind, bind)
439                         }
440
441                         // Does path start with OutputPath?
442                         prefix := runner.Container.OutputPath
443                         if !strings.HasSuffix(prefix, "/") {
444                                 prefix += "/"
445                         }
446                         if !strings.HasPrefix(mnt.Path, prefix) {
447                                 return nil, fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
448                         }
449                 }
450
451                 if bind == "stdin" {
452                         // Is it a "collection" mount kind?
453                         if mnt.Kind != "collection" && mnt.Kind != "json" {
454                                 return nil, fmt.Errorf("unsupported mount kind '%s' for stdin: only 'collection' and 'json' are supported", mnt.Kind)
455                         }
456                 }
457
458                 if bind == "/etc/arvados/ca-certificates.crt" {
459                         needCertMount = false
460                 }
461
462                 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
463                         if mnt.Kind != "collection" && mnt.Kind != "text" && mnt.Kind != "json" {
464                                 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)
465                         }
466                 }
467
468                 switch {
469                 case mnt.Kind == "collection" && bind != "stdin":
470                         var src string
471                         if mnt.UUID != "" && mnt.PortableDataHash != "" {
472                                 return nil, fmt.Errorf("cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
473                         }
474                         if mnt.UUID != "" {
475                                 if mnt.Writable {
476                                         return nil, fmt.Errorf("writing to existing collections currently not permitted")
477                                 }
478                                 pdhOnly = false
479                                 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
480                         } else if mnt.PortableDataHash != "" {
481                                 if mnt.Writable && !strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
482                                         return nil, fmt.Errorf("can never write to a collection specified by portable data hash")
483                                 }
484                                 idx := strings.Index(mnt.PortableDataHash, "/")
485                                 if idx > 0 {
486                                         mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
487                                         mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
488                                         runner.Container.Mounts[bind] = mnt
489                                 }
490                                 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
491                                 if mnt.Path != "" && mnt.Path != "." {
492                                         if strings.HasPrefix(mnt.Path, "./") {
493                                                 mnt.Path = mnt.Path[2:]
494                                         } else if strings.HasPrefix(mnt.Path, "/") {
495                                                 mnt.Path = mnt.Path[1:]
496                                         }
497                                         src += "/" + mnt.Path
498                                 }
499                         } else {
500                                 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
501                                 arvMountCmd = append(arvMountCmd, "--mount-tmp")
502                                 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
503                                 tmpcount++
504                         }
505                         if mnt.Writable {
506                                 if bind == runner.Container.OutputPath {
507                                         runner.HostOutputDir = src
508                                         bindmounts[bind] = bindmount{HostPath: src}
509                                 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
510                                         copyFiles = append(copyFiles, copyFile{src, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
511                                 } else {
512                                         bindmounts[bind] = bindmount{HostPath: src}
513                                 }
514                         } else {
515                                 bindmounts[bind] = bindmount{HostPath: src, ReadOnly: true}
516                         }
517                         collectionPaths = append(collectionPaths, src)
518
519                 case mnt.Kind == "tmp":
520                         var tmpdir string
521                         tmpdir, err = runner.MkTempDir(runner.parentTemp, "tmp")
522                         if err != nil {
523                                 return nil, fmt.Errorf("while creating mount temp dir: %v", err)
524                         }
525                         st, staterr := os.Stat(tmpdir)
526                         if staterr != nil {
527                                 return nil, fmt.Errorf("while Stat on temp dir: %v", staterr)
528                         }
529                         err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
530                         if staterr != nil {
531                                 return nil, fmt.Errorf("while Chmod temp dir: %v", err)
532                         }
533                         bindmounts[bind] = bindmount{HostPath: tmpdir}
534                         if bind == runner.Container.OutputPath {
535                                 runner.HostOutputDir = tmpdir
536                         }
537
538                 case mnt.Kind == "json" || mnt.Kind == "text":
539                         var filedata []byte
540                         if mnt.Kind == "json" {
541                                 filedata, err = json.Marshal(mnt.Content)
542                                 if err != nil {
543                                         return nil, fmt.Errorf("encoding json data: %v", err)
544                                 }
545                         } else {
546                                 text, ok := mnt.Content.(string)
547                                 if !ok {
548                                         return nil, fmt.Errorf("content for mount %q must be a string", bind)
549                                 }
550                                 filedata = []byte(text)
551                         }
552
553                         tmpdir, err := runner.MkTempDir(runner.parentTemp, mnt.Kind)
554                         if err != nil {
555                                 return nil, fmt.Errorf("creating temp dir: %v", err)
556                         }
557                         tmpfn := filepath.Join(tmpdir, "mountdata."+mnt.Kind)
558                         err = ioutil.WriteFile(tmpfn, filedata, 0444)
559                         if err != nil {
560                                 return nil, fmt.Errorf("writing temp file: %v", err)
561                         }
562                         if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
563                                 copyFiles = append(copyFiles, copyFile{tmpfn, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
564                         } else {
565                                 bindmounts[bind] = bindmount{HostPath: tmpfn, ReadOnly: true}
566                         }
567
568                 case mnt.Kind == "git_tree":
569                         tmpdir, err := runner.MkTempDir(runner.parentTemp, "git_tree")
570                         if err != nil {
571                                 return nil, fmt.Errorf("creating temp dir: %v", err)
572                         }
573                         err = gitMount(mnt).extractTree(runner.ContainerArvClient, tmpdir, token)
574                         if err != nil {
575                                 return nil, err
576                         }
577                         bindmounts[bind] = bindmount{HostPath: tmpdir, ReadOnly: true}
578                 }
579         }
580
581         if runner.HostOutputDir == "" {
582                 return nil, fmt.Errorf("output path does not correspond to a writable mount point")
583         }
584
585         if needCertMount && runner.Container.RuntimeConstraints.API {
586                 for _, certfile := range arvadosclient.CertFiles {
587                         _, err := os.Stat(certfile)
588                         if err == nil {
589                                 bindmounts["/etc/arvados/ca-certificates.crt"] = bindmount{HostPath: certfile, ReadOnly: true}
590                                 break
591                         }
592                 }
593         }
594
595         if pdhOnly {
596                 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
597         } else {
598                 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
599         }
600         arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_uuid")
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 = ioutil.NopCloser(bytes.NewReader(nil))
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         runner.executorStdin = stdin
958         runner.executorStdout = stdout
959         runner.executorStderr = stderr
960         return runner.executor.Create(containerSpec{
961                 Image:         imageID,
962                 VCPUs:         runner.Container.RuntimeConstraints.VCPUs,
963                 RAM:           ram,
964                 WorkingDir:    workdir,
965                 Env:           env,
966                 BindMounts:    bindmounts,
967                 Command:       runner.Container.Command,
968                 EnableNetwork: enableNetwork,
969                 NetworkMode:   runner.networkMode,
970                 CgroupParent:  runner.setCgroupParent,
971                 Stdin:         stdin,
972                 Stdout:        stdout,
973                 Stderr:        stderr,
974         })
975 }
976
977 // StartContainer starts the docker container created by CreateContainer.
978 func (runner *ContainerRunner) StartContainer() error {
979         runner.CrunchLog.Printf("Starting container")
980         runner.cStateLock.Lock()
981         defer runner.cStateLock.Unlock()
982         if runner.cCancelled {
983                 return ErrCancelled
984         }
985         err := runner.executor.Start()
986         if err != nil {
987                 var advice string
988                 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
989                         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])
990                 }
991                 return fmt.Errorf("could not start container: %v%s", err, advice)
992         }
993         return nil
994 }
995
996 // WaitFinish waits for the container to terminate, capture the exit code, and
997 // close the stdout/stderr logging.
998 func (runner *ContainerRunner) WaitFinish() error {
999         runner.CrunchLog.Print("Waiting for container to finish")
1000         var timeout <-chan time.Time
1001         if s := runner.Container.SchedulingParameters.MaxRunTime; s > 0 {
1002                 timeout = time.After(time.Duration(s) * time.Second)
1003         }
1004         ctx, cancel := context.WithCancel(context.Background())
1005         defer cancel()
1006         go func() {
1007                 select {
1008                 case <-timeout:
1009                         runner.CrunchLog.Printf("maximum run time exceeded. Stopping container.")
1010                         runner.stop(nil)
1011                 case <-runner.ArvMountExit:
1012                         runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
1013                         runner.stop(nil)
1014                 case <-ctx.Done():
1015                 }
1016         }()
1017         exitcode, err := runner.executor.Wait(ctx)
1018         if err != nil {
1019                 runner.checkBrokenNode(err)
1020                 return err
1021         }
1022         runner.ExitCode = &exitcode
1023
1024         var returnErr error
1025         if err = runner.executorStdin.Close(); err != nil {
1026                 err = fmt.Errorf("error closing container stdin: %s", err)
1027                 runner.CrunchLog.Printf("%s", err)
1028                 returnErr = err
1029         }
1030         if err = runner.executorStdout.Close(); err != nil {
1031                 err = fmt.Errorf("error closing container stdout: %s", err)
1032                 runner.CrunchLog.Printf("%s", err)
1033                 if returnErr == nil {
1034                         returnErr = err
1035                 }
1036         }
1037         if err = runner.executorStderr.Close(); err != nil {
1038                 err = fmt.Errorf("error closing container stderr: %s", err)
1039                 runner.CrunchLog.Printf("%s", err)
1040                 if returnErr == nil {
1041                         returnErr = err
1042                 }
1043         }
1044
1045         if runner.statReporter != nil {
1046                 runner.statReporter.Stop()
1047                 err = runner.statLogger.Close()
1048                 if err != nil {
1049                         runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
1050                 }
1051         }
1052         return returnErr
1053 }
1054
1055 func (runner *ContainerRunner) updateLogs() {
1056         ticker := time.NewTicker(crunchLogUpdatePeriod / 360)
1057         defer ticker.Stop()
1058
1059         sigusr1 := make(chan os.Signal, 1)
1060         signal.Notify(sigusr1, syscall.SIGUSR1)
1061         defer signal.Stop(sigusr1)
1062
1063         saveAtTime := time.Now().Add(crunchLogUpdatePeriod)
1064         saveAtSize := crunchLogUpdateSize
1065         var savedSize int64
1066         for {
1067                 select {
1068                 case <-ticker.C:
1069                 case <-sigusr1:
1070                         saveAtTime = time.Now()
1071                 }
1072                 runner.logMtx.Lock()
1073                 done := runner.LogsPDH != nil
1074                 runner.logMtx.Unlock()
1075                 if done {
1076                         return
1077                 }
1078                 size := runner.LogCollection.Size()
1079                 if size == savedSize || (time.Now().Before(saveAtTime) && size < saveAtSize) {
1080                         continue
1081                 }
1082                 saveAtTime = time.Now().Add(crunchLogUpdatePeriod)
1083                 saveAtSize = runner.LogCollection.Size() + crunchLogUpdateSize
1084                 saved, err := runner.saveLogCollection(false)
1085                 if err != nil {
1086                         runner.CrunchLog.Printf("error updating log collection: %s", err)
1087                         continue
1088                 }
1089
1090                 var updated arvados.Container
1091                 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1092                         "container": arvadosclient.Dict{"log": saved.PortableDataHash},
1093                 }, &updated)
1094                 if err != nil {
1095                         runner.CrunchLog.Printf("error updating container log to %s: %s", saved.PortableDataHash, err)
1096                         continue
1097                 }
1098
1099                 savedSize = size
1100         }
1101 }
1102
1103 // CaptureOutput saves data from the container's output directory if
1104 // needed, and updates the container output accordingly.
1105 func (runner *ContainerRunner) CaptureOutput(bindmounts map[string]bindmount) error {
1106         if runner.Container.RuntimeConstraints.API {
1107                 // Output may have been set directly by the container, so
1108                 // refresh the container record to check.
1109                 err := runner.DispatcherArvClient.Get("containers", runner.Container.UUID,
1110                         nil, &runner.Container)
1111                 if err != nil {
1112                         return err
1113                 }
1114                 if runner.Container.Output != "" {
1115                         // Container output is already set.
1116                         runner.OutputPDH = &runner.Container.Output
1117                         return nil
1118                 }
1119         }
1120
1121         txt, err := (&copier{
1122                 client:        runner.containerClient,
1123                 arvClient:     runner.ContainerArvClient,
1124                 keepClient:    runner.ContainerKeepClient,
1125                 hostOutputDir: runner.HostOutputDir,
1126                 ctrOutputDir:  runner.Container.OutputPath,
1127                 bindmounts:    bindmounts,
1128                 mounts:        runner.Container.Mounts,
1129                 secretMounts:  runner.SecretMounts,
1130                 logger:        runner.CrunchLog,
1131         }).Copy()
1132         if err != nil {
1133                 return err
1134         }
1135         if n := len(regexp.MustCompile(` [0-9a-f]+\+\S*\+R`).FindAllStringIndex(txt, -1)); n > 0 {
1136                 runner.CrunchLog.Printf("Copying %d data blocks from remote input collections...", n)
1137                 fs, err := (&arvados.Collection{ManifestText: txt}).FileSystem(runner.containerClient, runner.ContainerKeepClient)
1138                 if err != nil {
1139                         return err
1140                 }
1141                 txt, err = fs.MarshalManifest(".")
1142                 if err != nil {
1143                         return err
1144                 }
1145         }
1146         var resp arvados.Collection
1147         err = runner.ContainerArvClient.Create("collections", arvadosclient.Dict{
1148                 "ensure_unique_name": true,
1149                 "collection": arvadosclient.Dict{
1150                         "is_trashed":    true,
1151                         "name":          "output for " + runner.Container.UUID,
1152                         "manifest_text": txt,
1153                 },
1154         }, &resp)
1155         if err != nil {
1156                 return fmt.Errorf("error creating output collection: %v", err)
1157         }
1158         runner.OutputPDH = &resp.PortableDataHash
1159         return nil
1160 }
1161
1162 func (runner *ContainerRunner) CleanupDirs() {
1163         if runner.ArvMount != nil {
1164                 var delay int64 = 8
1165                 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1166                 umount.Stdout = runner.CrunchLog
1167                 umount.Stderr = runner.CrunchLog
1168                 runner.CrunchLog.Printf("Running %v", umount.Args)
1169                 umnterr := umount.Start()
1170
1171                 if umnterr != nil {
1172                         runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1173                         runner.ArvMount.Process.Kill()
1174                 } else {
1175                         // If arv-mount --unmount gets stuck for any reason, we
1176                         // don't want to wait for it forever.  Do Wait() in a goroutine
1177                         // so it doesn't block crunch-run.
1178                         umountExit := make(chan error)
1179                         go func() {
1180                                 mnterr := umount.Wait()
1181                                 if mnterr != nil {
1182                                         runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1183                                 }
1184                                 umountExit <- mnterr
1185                         }()
1186
1187                         for again := true; again; {
1188                                 again = false
1189                                 select {
1190                                 case <-umountExit:
1191                                         umount = nil
1192                                         again = true
1193                                 case <-runner.ArvMountExit:
1194                                         break
1195                                 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1196                                         runner.CrunchLog.Printf("Timed out waiting for unmount")
1197                                         if umount != nil {
1198                                                 umount.Process.Kill()
1199                                         }
1200                                         runner.ArvMount.Process.Kill()
1201                                 }
1202                         }
1203                 }
1204                 runner.ArvMount = nil
1205         }
1206
1207         if runner.ArvMountPoint != "" {
1208                 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1209                         runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1210                 }
1211                 runner.ArvMountPoint = ""
1212         }
1213
1214         if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1215                 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1216         }
1217 }
1218
1219 // CommitLogs posts the collection containing the final container logs.
1220 func (runner *ContainerRunner) CommitLogs() error {
1221         func() {
1222                 // Hold cStateLock to prevent races on CrunchLog (e.g., stop()).
1223                 runner.cStateLock.Lock()
1224                 defer runner.cStateLock.Unlock()
1225
1226                 runner.CrunchLog.Print(runner.finalState)
1227
1228                 if runner.arvMountLog != nil {
1229                         runner.arvMountLog.Close()
1230                 }
1231                 runner.CrunchLog.Close()
1232
1233                 // Closing CrunchLog above allows them to be committed to Keep at this
1234                 // point, but re-open crunch log with ArvClient in case there are any
1235                 // other further errors (such as failing to write the log to Keep!)
1236                 // while shutting down
1237                 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{
1238                         ArvClient:     runner.DispatcherArvClient,
1239                         UUID:          runner.Container.UUID,
1240                         loggingStream: "crunch-run",
1241                         writeCloser:   nil,
1242                 })
1243                 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1244         }()
1245
1246         if runner.LogsPDH != nil {
1247                 // If we have already assigned something to LogsPDH,
1248                 // we must be closing the re-opened log, which won't
1249                 // end up getting attached to the container record and
1250                 // therefore doesn't need to be saved as a collection
1251                 // -- it exists only to send logs to other channels.
1252                 return nil
1253         }
1254         saved, err := runner.saveLogCollection(true)
1255         if err != nil {
1256                 return fmt.Errorf("error saving log collection: %s", err)
1257         }
1258         runner.logMtx.Lock()
1259         defer runner.logMtx.Unlock()
1260         runner.LogsPDH = &saved.PortableDataHash
1261         return nil
1262 }
1263
1264 func (runner *ContainerRunner) saveLogCollection(final bool) (response arvados.Collection, err error) {
1265         runner.logMtx.Lock()
1266         defer runner.logMtx.Unlock()
1267         if runner.LogsPDH != nil {
1268                 // Already finalized.
1269                 return
1270         }
1271         updates := arvadosclient.Dict{
1272                 "name": "logs for " + runner.Container.UUID,
1273         }
1274         mt, err1 := runner.LogCollection.MarshalManifest(".")
1275         if err1 == nil {
1276                 // Only send updated manifest text if there was no
1277                 // error.
1278                 updates["manifest_text"] = mt
1279         }
1280
1281         // Even if flushing the manifest had an error, we still want
1282         // to update the log record, if possible, to push the trash_at
1283         // and delete_at times into the future.  Details on bug
1284         // #17293.
1285         if final {
1286                 updates["is_trashed"] = true
1287         } else {
1288                 exp := time.Now().Add(crunchLogUpdatePeriod * 24)
1289                 updates["trash_at"] = exp
1290                 updates["delete_at"] = exp
1291         }
1292         reqBody := arvadosclient.Dict{"collection": updates}
1293         var err2 error
1294         if runner.logUUID == "" {
1295                 reqBody["ensure_unique_name"] = true
1296                 err2 = runner.DispatcherArvClient.Create("collections", reqBody, &response)
1297         } else {
1298                 err2 = runner.DispatcherArvClient.Update("collections", runner.logUUID, reqBody, &response)
1299         }
1300         if err2 == nil {
1301                 runner.logUUID = response.UUID
1302         }
1303
1304         if err1 != nil || err2 != nil {
1305                 err = fmt.Errorf("error recording logs: %q, %q", err1, err2)
1306         }
1307         return
1308 }
1309
1310 // UpdateContainerRunning updates the container state to "Running"
1311 func (runner *ContainerRunner) UpdateContainerRunning() error {
1312         runner.cStateLock.Lock()
1313         defer runner.cStateLock.Unlock()
1314         if runner.cCancelled {
1315                 return ErrCancelled
1316         }
1317         return runner.DispatcherArvClient.Update("containers", runner.Container.UUID,
1318                 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running", "gateway_address": runner.gateway.Address}}, nil)
1319 }
1320
1321 // ContainerToken returns the api_token the container (and any
1322 // arv-mount processes) are allowed to use.
1323 func (runner *ContainerRunner) ContainerToken() (string, error) {
1324         if runner.token != "" {
1325                 return runner.token, nil
1326         }
1327
1328         var auth arvados.APIClientAuthorization
1329         err := runner.DispatcherArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1330         if err != nil {
1331                 return "", err
1332         }
1333         runner.token = fmt.Sprintf("v2/%s/%s/%s", auth.UUID, auth.APIToken, runner.Container.UUID)
1334         return runner.token, nil
1335 }
1336
1337 // UpdateContainerFinal updates the container record state on API
1338 // server to "Complete" or "Cancelled"
1339 func (runner *ContainerRunner) UpdateContainerFinal() error {
1340         update := arvadosclient.Dict{}
1341         update["state"] = runner.finalState
1342         if runner.LogsPDH != nil {
1343                 update["log"] = *runner.LogsPDH
1344         }
1345         if runner.finalState == "Complete" {
1346                 if runner.ExitCode != nil {
1347                         update["exit_code"] = *runner.ExitCode
1348                 }
1349                 if runner.OutputPDH != nil {
1350                         update["output"] = *runner.OutputPDH
1351                 }
1352         }
1353         return runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1354 }
1355
1356 // IsCancelled returns the value of Cancelled, with goroutine safety.
1357 func (runner *ContainerRunner) IsCancelled() bool {
1358         runner.cStateLock.Lock()
1359         defer runner.cStateLock.Unlock()
1360         return runner.cCancelled
1361 }
1362
1363 // NewArvLogWriter creates an ArvLogWriter
1364 func (runner *ContainerRunner) NewArvLogWriter(name string) (io.WriteCloser, error) {
1365         writer, err := runner.LogCollection.OpenFile(name+".txt", os.O_CREATE|os.O_WRONLY, 0666)
1366         if err != nil {
1367                 return nil, err
1368         }
1369         return &ArvLogWriter{
1370                 ArvClient:     runner.DispatcherArvClient,
1371                 UUID:          runner.Container.UUID,
1372                 loggingStream: name,
1373                 writeCloser:   writer,
1374         }, nil
1375 }
1376
1377 // Run the full container lifecycle.
1378 func (runner *ContainerRunner) Run() (err error) {
1379         runner.CrunchLog.Printf("crunch-run %s started", cmd.Version.String())
1380         runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1381
1382         hostname, hosterr := os.Hostname()
1383         if hosterr != nil {
1384                 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1385         } else {
1386                 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1387         }
1388
1389         runner.finalState = "Queued"
1390
1391         defer func() {
1392                 runner.CleanupDirs()
1393
1394                 runner.CrunchLog.Printf("crunch-run finished")
1395                 runner.CrunchLog.Close()
1396         }()
1397
1398         err = runner.fetchContainerRecord()
1399         if err != nil {
1400                 return
1401         }
1402         if runner.Container.State != "Locked" {
1403                 return fmt.Errorf("dispatch error detected: container %q has state %q", runner.Container.UUID, runner.Container.State)
1404         }
1405
1406         var bindmounts map[string]bindmount
1407         defer func() {
1408                 // checkErr prints e (unless it's nil) and sets err to
1409                 // e (unless err is already non-nil). Thus, if err
1410                 // hasn't already been assigned when Run() returns,
1411                 // this cleanup func will cause Run() to return the
1412                 // first non-nil error that is passed to checkErr().
1413                 checkErr := func(errorIn string, e error) {
1414                         if e == nil {
1415                                 return
1416                         }
1417                         runner.CrunchLog.Printf("error in %s: %v", errorIn, e)
1418                         if err == nil {
1419                                 err = e
1420                         }
1421                         if runner.finalState == "Complete" {
1422                                 // There was an error in the finalization.
1423                                 runner.finalState = "Cancelled"
1424                         }
1425                 }
1426
1427                 // Log the error encountered in Run(), if any
1428                 checkErr("Run", err)
1429
1430                 if runner.finalState == "Queued" {
1431                         runner.UpdateContainerFinal()
1432                         return
1433                 }
1434
1435                 if runner.IsCancelled() {
1436                         runner.finalState = "Cancelled"
1437                         // but don't return yet -- we still want to
1438                         // capture partial output and write logs
1439                 }
1440
1441                 if bindmounts != nil {
1442                         checkErr("CaptureOutput", runner.CaptureOutput(bindmounts))
1443                 }
1444                 checkErr("stopHoststat", runner.stopHoststat())
1445                 checkErr("CommitLogs", runner.CommitLogs())
1446                 runner.CleanupDirs()
1447                 checkErr("UpdateContainerFinal", runner.UpdateContainerFinal())
1448         }()
1449
1450         runner.setupSignals()
1451         err = runner.startHoststat()
1452         if err != nil {
1453                 return
1454         }
1455
1456         // set up FUSE mount and binds
1457         bindmounts, err = runner.SetupMounts()
1458         if err != nil {
1459                 runner.finalState = "Cancelled"
1460                 err = fmt.Errorf("While setting up mounts: %v", err)
1461                 return
1462         }
1463
1464         // check for and/or load image
1465         imageID, err := runner.LoadImage()
1466         if err != nil {
1467                 if !runner.checkBrokenNode(err) {
1468                         // Failed to load image but not due to a "broken node"
1469                         // condition, probably user error.
1470                         runner.finalState = "Cancelled"
1471                 }
1472                 err = fmt.Errorf("While loading container image: %v", err)
1473                 return
1474         }
1475
1476         err = runner.CreateContainer(imageID, bindmounts)
1477         if err != nil {
1478                 return
1479         }
1480         err = runner.LogHostInfo()
1481         if err != nil {
1482                 return
1483         }
1484         err = runner.LogNodeRecord()
1485         if err != nil {
1486                 return
1487         }
1488         err = runner.LogContainerRecord()
1489         if err != nil {
1490                 return
1491         }
1492
1493         if runner.IsCancelled() {
1494                 return
1495         }
1496
1497         err = runner.UpdateContainerRunning()
1498         if err != nil {
1499                 return
1500         }
1501         runner.finalState = "Cancelled"
1502
1503         err = runner.startCrunchstat()
1504         if err != nil {
1505                 return
1506         }
1507
1508         err = runner.StartContainer()
1509         if err != nil {
1510                 runner.checkBrokenNode(err)
1511                 return
1512         }
1513
1514         err = runner.WaitFinish()
1515         if err == nil && !runner.IsCancelled() {
1516                 runner.finalState = "Complete"
1517         }
1518         return
1519 }
1520
1521 // Fetch the current container record (uuid = runner.Container.UUID)
1522 // into runner.Container.
1523 func (runner *ContainerRunner) fetchContainerRecord() error {
1524         reader, err := runner.DispatcherArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1525         if err != nil {
1526                 return fmt.Errorf("error fetching container record: %v", err)
1527         }
1528         defer reader.Close()
1529
1530         dec := json.NewDecoder(reader)
1531         dec.UseNumber()
1532         err = dec.Decode(&runner.Container)
1533         if err != nil {
1534                 return fmt.Errorf("error decoding container record: %v", err)
1535         }
1536
1537         var sm struct {
1538                 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
1539         }
1540
1541         containerToken, err := runner.ContainerToken()
1542         if err != nil {
1543                 return fmt.Errorf("error getting container token: %v", err)
1544         }
1545
1546         runner.ContainerArvClient, runner.ContainerKeepClient,
1547                 runner.containerClient, err = runner.MkArvClient(containerToken)
1548         if err != nil {
1549                 return fmt.Errorf("error creating container API client: %v", err)
1550         }
1551
1552         runner.ContainerKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1553         runner.DispatcherKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1554
1555         err = runner.ContainerArvClient.Call("GET", "containers", runner.Container.UUID, "secret_mounts", nil, &sm)
1556         if err != nil {
1557                 if apierr, ok := err.(arvadosclient.APIServerError); !ok || apierr.HttpStatusCode != 404 {
1558                         return fmt.Errorf("error fetching secret_mounts: %v", err)
1559                 }
1560                 // ok && apierr.HttpStatusCode == 404, which means
1561                 // secret_mounts isn't supported by this API server.
1562         }
1563         runner.SecretMounts = sm.SecretMounts
1564
1565         return nil
1566 }
1567
1568 // NewContainerRunner creates a new container runner.
1569 func NewContainerRunner(dispatcherClient *arvados.Client,
1570         dispatcherArvClient IArvadosClient,
1571         dispatcherKeepClient IKeepClient,
1572         containerUUID string) (*ContainerRunner, error) {
1573
1574         cr := &ContainerRunner{
1575                 dispatcherClient:     dispatcherClient,
1576                 DispatcherArvClient:  dispatcherArvClient,
1577                 DispatcherKeepClient: dispatcherKeepClient,
1578         }
1579         cr.NewLogWriter = cr.NewArvLogWriter
1580         cr.RunArvMount = cr.ArvMountCmd
1581         cr.MkTempDir = ioutil.TempDir
1582         cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1583                 cl, err := arvadosclient.MakeArvadosClient()
1584                 if err != nil {
1585                         return nil, nil, nil, err
1586                 }
1587                 cl.ApiToken = token
1588                 kc, err := keepclient.MakeKeepClient(cl)
1589                 if err != nil {
1590                         return nil, nil, nil, err
1591                 }
1592                 c2 := arvados.NewClientFromEnv()
1593                 c2.AuthToken = token
1594                 return cl, kc, c2, nil
1595         }
1596         var err error
1597         cr.LogCollection, err = (&arvados.Collection{}).FileSystem(cr.dispatcherClient, cr.DispatcherKeepClient)
1598         if err != nil {
1599                 return nil, err
1600         }
1601         cr.Container.UUID = containerUUID
1602         w, err := cr.NewLogWriter("crunch-run")
1603         if err != nil {
1604                 return nil, err
1605         }
1606         cr.CrunchLog = NewThrottledLogger(w)
1607         cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1608
1609         loadLogThrottleParams(dispatcherArvClient)
1610         go cr.updateLogs()
1611
1612         return cr, nil
1613 }
1614
1615 func (command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
1616         flags := flag.NewFlagSet(prog, flag.ContinueOnError)
1617         statInterval := flags.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1618         cgroupRoot := flags.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1619         cgroupParent := flags.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1620         cgroupParentSubsystem := flags.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1621         caCertsPath := flags.String("ca-certs", "", "Path to TLS root certificates")
1622         detach := flags.Bool("detach", false, "Detach from parent process and run in the background")
1623         stdinEnv := flags.Bool("stdin-env", false, "Load environment variables from JSON message on stdin")
1624         sleep := flags.Duration("sleep", 0, "Delay before starting (testing use only)")
1625         kill := flags.Int("kill", -1, "Send signal to an existing crunch-run process for given UUID")
1626         list := flags.Bool("list", false, "List UUIDs of existing crunch-run processes")
1627         enableMemoryLimit := flags.Bool("enable-memory-limit", true, "tell container runtime to limit container's memory usage")
1628         enableNetwork := flags.String("container-enable-networking", "default", "enable networking \"always\" (for all containers) or \"default\" (for containers that request it)")
1629         networkMode := flags.String("container-network-mode", "default", `Docker network mode for container (use any argument valid for docker --net)`)
1630         memprofile := flags.String("memprofile", "", "write memory profile to `file` after running container")
1631         runtimeEngine := flags.String("runtime-engine", "docker", "container runtime: docker or singularity")
1632         flags.Duration("check-containerd", 0, "Ignored. Exists for compatibility with older versions.")
1633
1634         ignoreDetachFlag := false
1635         if len(args) > 0 && args[0] == "-no-detach" {
1636                 // This process was invoked by a parent process, which
1637                 // has passed along its own arguments, including
1638                 // -detach, after the leading -no-detach flag.  Strip
1639                 // the leading -no-detach flag (it's not recognized by
1640                 // flags.Parse()) and ignore the -detach flag that
1641                 // comes later.
1642                 args = args[1:]
1643                 ignoreDetachFlag = true
1644         }
1645
1646         if err := flags.Parse(args); err == flag.ErrHelp {
1647                 return 0
1648         } else if err != nil {
1649                 log.Print(err)
1650                 return 1
1651         }
1652
1653         if *stdinEnv && !ignoreDetachFlag {
1654                 // Load env vars on stdin if asked (but not in a
1655                 // detached child process, in which case stdin is
1656                 // /dev/null).
1657                 err := loadEnv(os.Stdin)
1658                 if err != nil {
1659                         log.Print(err)
1660                         return 1
1661                 }
1662         }
1663
1664         containerUUID := flags.Arg(0)
1665
1666         switch {
1667         case *detach && !ignoreDetachFlag:
1668                 return Detach(containerUUID, prog, args, os.Stdout, os.Stderr)
1669         case *kill >= 0:
1670                 return KillProcess(containerUUID, syscall.Signal(*kill), os.Stdout, os.Stderr)
1671         case *list:
1672                 return ListProcesses(os.Stdout, os.Stderr)
1673         }
1674
1675         if containerUUID == "" {
1676                 log.Printf("usage: %s [options] UUID", prog)
1677                 return 1
1678         }
1679
1680         log.Printf("crunch-run %s started", cmd.Version.String())
1681         time.Sleep(*sleep)
1682
1683         if *caCertsPath != "" {
1684                 arvadosclient.CertFiles = []string{*caCertsPath}
1685         }
1686
1687         api, err := arvadosclient.MakeArvadosClient()
1688         if err != nil {
1689                 log.Printf("%s: %v", containerUUID, err)
1690                 return 1
1691         }
1692         api.Retries = 8
1693
1694         kc, kcerr := keepclient.MakeKeepClient(api)
1695         if kcerr != nil {
1696                 log.Printf("%s: %v", containerUUID, kcerr)
1697                 return 1
1698         }
1699         kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1700         kc.Retries = 4
1701
1702         cr, err := NewContainerRunner(arvados.NewClientFromEnv(), api, kc, containerUUID)
1703         if err != nil {
1704                 log.Print(err)
1705                 return 1
1706         }
1707
1708         switch *runtimeEngine {
1709         case "docker":
1710                 cr.executor, err = newDockerExecutor(containerUUID, cr.CrunchLog.Printf, cr.containerWatchdogInterval)
1711         case "singularity":
1712                 cr.executor, err = newSingularityExecutor(cr.CrunchLog.Printf)
1713         default:
1714                 cr.CrunchLog.Printf("%s: unsupported RuntimeEngine %q", containerUUID, *runtimeEngine)
1715                 cr.CrunchLog.Close()
1716                 return 1
1717         }
1718         if err != nil {
1719                 cr.CrunchLog.Printf("%s: %v", containerUUID, err)
1720                 cr.checkBrokenNode(err)
1721                 cr.CrunchLog.Close()
1722                 return 1
1723         }
1724         defer cr.executor.Close()
1725
1726         gwAuthSecret := os.Getenv("GatewayAuthSecret")
1727         os.Unsetenv("GatewayAuthSecret")
1728         if gwAuthSecret == "" {
1729                 // not safe to run a gateway service without an auth
1730                 // secret
1731                 cr.CrunchLog.Printf("Not starting a gateway server (GatewayAuthSecret was not provided by dispatcher)")
1732         } else if gwListen := os.Getenv("GatewayAddress"); gwListen == "" {
1733                 // dispatcher did not tell us which external IP
1734                 // address to advertise --> no gateway service
1735                 cr.CrunchLog.Printf("Not starting a gateway server (GatewayAddress was not provided by dispatcher)")
1736         } else if de, ok := cr.executor.(*dockerExecutor); ok {
1737                 cr.gateway = Gateway{
1738                         Address:            gwListen,
1739                         AuthSecret:         gwAuthSecret,
1740                         ContainerUUID:      containerUUID,
1741                         DockerContainerID:  &de.containerID,
1742                         Log:                cr.CrunchLog,
1743                         ContainerIPAddress: dockerContainerIPAddress(&de.containerID),
1744                 }
1745                 err = cr.gateway.Start()
1746                 if err != nil {
1747                         log.Printf("error starting gateway server: %s", err)
1748                         return 1
1749                 }
1750         }
1751
1752         parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerUUID+".")
1753         if tmperr != nil {
1754                 log.Printf("%s: %v", containerUUID, tmperr)
1755                 return 1
1756         }
1757
1758         cr.parentTemp = parentTemp
1759         cr.statInterval = *statInterval
1760         cr.cgroupRoot = *cgroupRoot
1761         cr.expectCgroupParent = *cgroupParent
1762         cr.enableMemoryLimit = *enableMemoryLimit
1763         cr.enableNetwork = *enableNetwork
1764         cr.networkMode = *networkMode
1765         if *cgroupParentSubsystem != "" {
1766                 p := findCgroup(*cgroupParentSubsystem)
1767                 cr.setCgroupParent = p
1768                 cr.expectCgroupParent = p
1769         }
1770
1771         runerr := cr.Run()
1772
1773         if *memprofile != "" {
1774                 f, err := os.Create(*memprofile)
1775                 if err != nil {
1776                         log.Printf("could not create memory profile: %s", err)
1777                 }
1778                 runtime.GC() // get up-to-date statistics
1779                 if err := pprof.WriteHeapProfile(f); err != nil {
1780                         log.Printf("could not write memory profile: %s", err)
1781                 }
1782                 closeerr := f.Close()
1783                 if closeerr != nil {
1784                         log.Printf("closing memprofile file: %s", err)
1785                 }
1786         }
1787
1788         if runerr != nil {
1789                 log.Printf("%s: %v", containerUUID, runerr)
1790                 return 1
1791         }
1792         return 0
1793 }
1794
1795 func loadEnv(rdr io.Reader) error {
1796         buf, err := ioutil.ReadAll(rdr)
1797         if err != nil {
1798                 return fmt.Errorf("read stdin: %s", err)
1799         }
1800         var env map[string]string
1801         err = json.Unmarshal(buf, &env)
1802         if err != nil {
1803                 return fmt.Errorf("decode stdin: %s", err)
1804         }
1805         for k, v := range env {
1806                 err = os.Setenv(k, v)
1807                 if err != nil {
1808                         return fmt.Errorf("setenv(%q): %s", k, err)
1809                 }
1810         }
1811         return nil
1812 }