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