Merge branch '12764-writable-file' refs #12764
[arvados.git] / services / crunch-run / crunchrun.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package main
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.curoverse.com/arvados.git/lib/crunchstat"
31         "git.curoverse.com/arvados.git/sdk/go/arvados"
32         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
33         "git.curoverse.com/arvados.git/sdk/go/keepclient"
34         "git.curoverse.com/arvados.git/sdk/go/manifest"
35         "golang.org/x/net/context"
36
37         dockertypes "github.com/docker/docker/api/types"
38         dockercontainer "github.com/docker/docker/api/types/container"
39         dockernetwork "github.com/docker/docker/api/types/network"
40         dockerclient "github.com/docker/docker/client"
41 )
42
43 var version = "dev"
44
45 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
46 type IArvadosClient interface {
47         Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
48         Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
49         Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
50         Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
51         CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
52         Discovery(key string) (interface{}, error)
53 }
54
55 // ErrCancelled is the error returned when the container is cancelled.
56 var ErrCancelled = errors.New("Cancelled")
57
58 // IKeepClient is the minimal Keep API methods used by crunch-run.
59 type IKeepClient interface {
60         PutHB(hash string, buf []byte) (string, int, error)
61         ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error)
62         ClearBlockCache()
63 }
64
65 // NewLogWriter is a factory function to create a new log writer.
66 type NewLogWriter func(name string) io.WriteCloser
67
68 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
69
70 type MkTempDir func(string, string) (string, error)
71
72 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
73 type ThinDockerClient interface {
74         ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error)
75         ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
76                 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error)
77         ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error
78         ContainerRemove(ctx context.Context, container string, options dockertypes.ContainerRemoveOptions) error
79         ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error)
80         ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error)
81         ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error)
82         ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error)
83 }
84
85 // ContainerRunner is the main stateful struct used for a single execution of a
86 // container.
87 type ContainerRunner struct {
88         Docker    ThinDockerClient
89         ArvClient IArvadosClient
90         Kc        IKeepClient
91         arvados.Container
92         ContainerConfig dockercontainer.Config
93         dockercontainer.HostConfig
94         token       string
95         ContainerID string
96         ExitCode    *int
97         NewLogWriter
98         loggingDone   chan bool
99         CrunchLog     *ThrottledLogger
100         Stdout        io.WriteCloser
101         Stderr        io.WriteCloser
102         LogCollection *CollectionWriter
103         LogsPDH       *string
104         RunArvMount
105         MkTempDir
106         ArvMount       *exec.Cmd
107         ArvMountPoint  string
108         HostOutputDir  string
109         CleanupTempDir []string
110         Binds          []string
111         Volumes        map[string]struct{}
112         OutputPDH      *string
113         SigChan        chan os.Signal
114         ArvMountExit   chan error
115         finalState     string
116
117         statLogger       io.WriteCloser
118         statReporter     *crunchstat.Reporter
119         hoststatLogger   io.WriteCloser
120         hoststatReporter *crunchstat.Reporter
121         statInterval     time.Duration
122         cgroupRoot       string
123         // What we expect the container's cgroup parent to be.
124         expectCgroupParent string
125         // What we tell docker to use as the container's cgroup
126         // parent. Note: Ideally we would use the same field for both
127         // expectCgroupParent and setCgroupParent, and just make it
128         // default to "docker". However, when using docker < 1.10 with
129         // systemd, specifying a non-empty cgroup parent (even the
130         // default value "docker") hits a docker bug
131         // (https://github.com/docker/docker/issues/17126). Using two
132         // separate fields makes it possible to use the "expect cgroup
133         // parent to be X" feature even on sites where the "specify
134         // cgroup parent" feature breaks.
135         setCgroupParent string
136
137         cStateLock sync.Mutex
138         cCancelled bool // StopContainer() invoked
139
140         enableNetwork string // one of "default" or "always"
141         networkMode   string // passed through to HostConfig.NetworkMode
142         arvMountLog   *ThrottledLogger
143 }
144
145 // setupSignals sets up signal handling to gracefully terminate the underlying
146 // Docker container and update state when receiving a TERM, INT or QUIT signal.
147 func (runner *ContainerRunner) setupSignals() {
148         runner.SigChan = make(chan os.Signal, 1)
149         signal.Notify(runner.SigChan, syscall.SIGTERM)
150         signal.Notify(runner.SigChan, syscall.SIGINT)
151         signal.Notify(runner.SigChan, syscall.SIGQUIT)
152
153         go func(sig chan os.Signal) {
154                 for s := range sig {
155                         runner.CrunchLog.Printf("caught signal: %v", s)
156                         runner.stop()
157                 }
158         }(runner.SigChan)
159 }
160
161 // stop the underlying Docker container.
162 func (runner *ContainerRunner) stop() {
163         runner.cStateLock.Lock()
164         defer runner.cStateLock.Unlock()
165         if runner.ContainerID == "" {
166                 return
167         }
168         runner.cCancelled = true
169         runner.CrunchLog.Printf("removing container")
170         err := runner.Docker.ContainerRemove(context.TODO(), runner.ContainerID, dockertypes.ContainerRemoveOptions{Force: true})
171         if err != nil {
172                 runner.CrunchLog.Printf("error removing container: %s", err)
173         }
174 }
175
176 func (runner *ContainerRunner) stopSignals() {
177         if runner.SigChan != nil {
178                 signal.Stop(runner.SigChan)
179         }
180 }
181
182 var errorBlacklist = []string{
183         "(?ms).*[Cc]annot connect to the Docker daemon.*",
184         "(?ms).*oci runtime error.*starting container process.*container init.*mounting.*to rootfs.*no such file or directory.*",
185 }
186 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)")
187
188 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
189         for _, d := range errorBlacklist {
190                 if m, e := regexp.MatchString(d, goterr.Error()); m && e == nil {
191                         runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
192                         if *brokenNodeHook == "" {
193                                 runner.CrunchLog.Printf("No broken node hook provided, cannot mark node as broken.")
194                         } else {
195                                 runner.CrunchLog.Printf("Running broken node hook %q", *brokenNodeHook)
196                                 // run killme script
197                                 c := exec.Command(*brokenNodeHook)
198                                 c.Stdout = runner.CrunchLog
199                                 c.Stderr = runner.CrunchLog
200                                 err := c.Run()
201                                 if err != nil {
202                                         runner.CrunchLog.Printf("Error running broken node hook: %v", err)
203                                 }
204                         }
205                         return true
206                 }
207         }
208         return false
209 }
210
211 // LoadImage determines the docker image id from the container record and
212 // checks if it is available in the local Docker image store.  If not, it loads
213 // the image from Keep.
214 func (runner *ContainerRunner) LoadImage() (err error) {
215
216         runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
217
218         var collection arvados.Collection
219         err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
220         if err != nil {
221                 return fmt.Errorf("While getting container image collection: %v", err)
222         }
223         manifest := manifest.Manifest{Text: collection.ManifestText}
224         var img, imageID string
225         for ms := range manifest.StreamIter() {
226                 img = ms.FileStreamSegments[0].Name
227                 if !strings.HasSuffix(img, ".tar") {
228                         return fmt.Errorf("First file in the container image collection does not end in .tar")
229                 }
230                 imageID = img[:len(img)-4]
231         }
232
233         runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
234
235         _, _, err = runner.Docker.ImageInspectWithRaw(context.TODO(), imageID)
236         if err != nil {
237                 runner.CrunchLog.Print("Loading Docker image from keep")
238
239                 var readCloser io.ReadCloser
240                 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
241                 if err != nil {
242                         return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
243                 }
244
245                 response, err := runner.Docker.ImageLoad(context.TODO(), readCloser, true)
246                 if err != nil {
247                         return fmt.Errorf("While loading container image into Docker: %v", err)
248                 }
249
250                 defer response.Body.Close()
251                 rbody, err := ioutil.ReadAll(response.Body)
252                 if err != nil {
253                         return fmt.Errorf("Reading response to image load: %v", err)
254                 }
255                 runner.CrunchLog.Printf("Docker response: %s", rbody)
256         } else {
257                 runner.CrunchLog.Print("Docker image is available")
258         }
259
260         runner.ContainerConfig.Image = imageID
261
262         runner.Kc.ClearBlockCache()
263
264         return nil
265 }
266
267 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
268         c = exec.Command("arv-mount", arvMountCmd...)
269
270         // Copy our environment, but override ARVADOS_API_TOKEN with
271         // the container auth token.
272         c.Env = nil
273         for _, s := range os.Environ() {
274                 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
275                         c.Env = append(c.Env, s)
276                 }
277         }
278         c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
279
280         runner.arvMountLog = NewThrottledLogger(runner.NewLogWriter("arv-mount"))
281         c.Stdout = runner.arvMountLog
282         c.Stderr = runner.arvMountLog
283
284         runner.CrunchLog.Printf("Running %v", c.Args)
285
286         err = c.Start()
287         if err != nil {
288                 return nil, err
289         }
290
291         statReadme := make(chan bool)
292         runner.ArvMountExit = make(chan error)
293
294         keepStatting := true
295         go func() {
296                 for keepStatting {
297                         time.Sleep(100 * time.Millisecond)
298                         _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
299                         if err == nil {
300                                 keepStatting = false
301                                 statReadme <- true
302                         }
303                 }
304                 close(statReadme)
305         }()
306
307         go func() {
308                 mnterr := c.Wait()
309                 if mnterr != nil {
310                         runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
311                 }
312                 runner.ArvMountExit <- mnterr
313                 close(runner.ArvMountExit)
314         }()
315
316         select {
317         case <-statReadme:
318                 break
319         case err := <-runner.ArvMountExit:
320                 runner.ArvMount = nil
321                 keepStatting = false
322                 return nil, err
323         }
324
325         return c, nil
326 }
327
328 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
329         if runner.ArvMountPoint == "" {
330                 runner.ArvMountPoint, err = runner.MkTempDir("", prefix)
331         }
332         return
333 }
334
335 func copyfile(src string, dst string) (err error) {
336         srcfile, err := os.Open(src)
337         if err != nil {
338                 return
339         }
340
341         os.MkdirAll(path.Dir(dst), 0770)
342
343         dstfile, err := os.Create(dst)
344         if err != nil {
345                 return
346         }
347         _, err = io.Copy(dstfile, srcfile)
348         if err != nil {
349                 return
350         }
351
352         err = srcfile.Close()
353         err2 := dstfile.Close()
354
355         if err != nil {
356                 return
357         }
358
359         if err2 != nil {
360                 return err2
361         }
362
363         return nil
364 }
365
366 func (runner *ContainerRunner) SetupMounts() (err error) {
367         err = runner.SetupArvMountPoint("keep")
368         if err != nil {
369                 return fmt.Errorf("While creating keep mount temp dir: %v", err)
370         }
371
372         token, err := runner.ContainerToken()
373         if err != nil {
374                 return fmt.Errorf("could not get container token: %s", err)
375         }
376
377         pdhOnly := true
378         tmpcount := 0
379         arvMountCmd := []string{
380                 "--foreground",
381                 "--allow-other",
382                 "--read-write",
383                 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
384
385         if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
386                 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
387         }
388
389         collectionPaths := []string{}
390         runner.Binds = nil
391         runner.Volumes = make(map[string]struct{})
392         needCertMount := true
393         type copyFile struct {
394                 src  string
395                 bind string
396         }
397         var copyFiles []copyFile
398
399         var binds []string
400         for bind := range runner.Container.Mounts {
401                 binds = append(binds, bind)
402         }
403         sort.Strings(binds)
404
405         for _, bind := range binds {
406                 mnt := runner.Container.Mounts[bind]
407                 if bind == "stdout" || bind == "stderr" {
408                         // Is it a "file" mount kind?
409                         if mnt.Kind != "file" {
410                                 return fmt.Errorf("Unsupported mount kind '%s' for %s. Only 'file' is supported.", mnt.Kind, bind)
411                         }
412
413                         // Does path start with OutputPath?
414                         prefix := runner.Container.OutputPath
415                         if !strings.HasSuffix(prefix, "/") {
416                                 prefix += "/"
417                         }
418                         if !strings.HasPrefix(mnt.Path, prefix) {
419                                 return fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
420                         }
421                 }
422
423                 if bind == "stdin" {
424                         // Is it a "collection" mount kind?
425                         if mnt.Kind != "collection" && mnt.Kind != "json" {
426                                 return fmt.Errorf("Unsupported mount kind '%s' for stdin. Only 'collection' or 'json' are supported.", mnt.Kind)
427                         }
428                 }
429
430                 if bind == "/etc/arvados/ca-certificates.crt" {
431                         needCertMount = false
432                 }
433
434                 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
435                         if mnt.Kind != "collection" {
436                                 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
437                         }
438                 }
439
440                 switch {
441                 case mnt.Kind == "collection" && bind != "stdin":
442                         var src string
443                         if mnt.UUID != "" && mnt.PortableDataHash != "" {
444                                 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
445                         }
446                         if mnt.UUID != "" {
447                                 if mnt.Writable {
448                                         return fmt.Errorf("Writing to existing collections currently not permitted.")
449                                 }
450                                 pdhOnly = false
451                                 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
452                         } else if mnt.PortableDataHash != "" {
453                                 if mnt.Writable && !strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
454                                         return fmt.Errorf("Can never write to a collection specified by portable data hash")
455                                 }
456                                 idx := strings.Index(mnt.PortableDataHash, "/")
457                                 if idx > 0 {
458                                         mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
459                                         mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
460                                         runner.Container.Mounts[bind] = mnt
461                                 }
462                                 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
463                                 if mnt.Path != "" && mnt.Path != "." {
464                                         if strings.HasPrefix(mnt.Path, "./") {
465                                                 mnt.Path = mnt.Path[2:]
466                                         } else if strings.HasPrefix(mnt.Path, "/") {
467                                                 mnt.Path = mnt.Path[1:]
468                                         }
469                                         src += "/" + mnt.Path
470                                 }
471                         } else {
472                                 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
473                                 arvMountCmd = append(arvMountCmd, "--mount-tmp")
474                                 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
475                                 tmpcount += 1
476                         }
477                         if mnt.Writable {
478                                 if bind == runner.Container.OutputPath {
479                                         runner.HostOutputDir = src
480                                         runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
481                                 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
482                                         copyFiles = append(copyFiles, copyFile{src, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
483                                 } else {
484                                         runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
485                                 }
486                         } else {
487                                 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
488                         }
489                         collectionPaths = append(collectionPaths, src)
490
491                 case mnt.Kind == "tmp":
492                         var tmpdir string
493                         tmpdir, err = runner.MkTempDir("", "")
494                         if err != nil {
495                                 return fmt.Errorf("While creating mount temp dir: %v", err)
496                         }
497                         st, staterr := os.Stat(tmpdir)
498                         if staterr != nil {
499                                 return fmt.Errorf("While Stat on temp dir: %v", staterr)
500                         }
501                         err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
502                         if staterr != nil {
503                                 return fmt.Errorf("While Chmod temp dir: %v", err)
504                         }
505                         runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
506                         runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", tmpdir, bind))
507                         if bind == runner.Container.OutputPath {
508                                 runner.HostOutputDir = tmpdir
509                         }
510
511                 case mnt.Kind == "json":
512                         jsondata, err := json.Marshal(mnt.Content)
513                         if err != nil {
514                                 return fmt.Errorf("encoding json data: %v", err)
515                         }
516                         // Create a tempdir with a single file
517                         // (instead of just a tempfile): this way we
518                         // can ensure the file is world-readable
519                         // inside the container, without having to
520                         // make it world-readable on the docker host.
521                         tmpdir, err := runner.MkTempDir("", "")
522                         if err != nil {
523                                 return fmt.Errorf("creating temp dir: %v", err)
524                         }
525                         runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
526                         tmpfn := filepath.Join(tmpdir, "mountdata.json")
527                         err = ioutil.WriteFile(tmpfn, jsondata, 0644)
528                         if err != nil {
529                                 return fmt.Errorf("writing temp file: %v", err)
530                         }
531                         runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
532
533                 case mnt.Kind == "git_tree":
534                         tmpdir, err := runner.MkTempDir("", "")
535                         if err != nil {
536                                 return fmt.Errorf("creating temp dir: %v", err)
537                         }
538                         runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
539                         err = gitMount(mnt).extractTree(runner.ArvClient, tmpdir, token)
540                         if err != nil {
541                                 return err
542                         }
543                         runner.Binds = append(runner.Binds, tmpdir+":"+bind+":ro")
544                 }
545         }
546
547         if runner.HostOutputDir == "" {
548                 return fmt.Errorf("Output path does not correspond to a writable mount point")
549         }
550
551         if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
552                 for _, certfile := range arvadosclient.CertFiles {
553                         _, err := os.Stat(certfile)
554                         if err == nil {
555                                 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
556                                 break
557                         }
558                 }
559         }
560
561         if pdhOnly {
562                 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
563         } else {
564                 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
565         }
566         arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
567
568         runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
569         if err != nil {
570                 return fmt.Errorf("While trying to start arv-mount: %v", err)
571         }
572
573         for _, p := range collectionPaths {
574                 _, err = os.Stat(p)
575                 if err != nil {
576                         return fmt.Errorf("While checking that input files exist: %v", err)
577                 }
578         }
579
580         for _, cp := range copyFiles {
581                 dir, err := os.Stat(cp.src)
582                 if err != nil {
583                         return fmt.Errorf("While staging writable file from %q to %q: %v", cp.src, cp.bind, err)
584                 }
585                 if dir.IsDir() {
586                         err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
587                                 if walkerr != nil {
588                                         return walkerr
589                                 }
590                                 if walkinfo.Mode().IsRegular() {
591                                         return copyfile(walkpath, path.Join(cp.bind, walkpath[len(cp.src):]))
592                                 } else if walkinfo.Mode().IsDir() {
593                                         return os.MkdirAll(path.Join(cp.bind, walkpath[len(cp.src):]), 0770)
594                                 } else {
595                                         return fmt.Errorf("Source %q is not a regular file or directory", cp.src)
596                                 }
597                         })
598                 } else {
599                         err = copyfile(cp.src, cp.bind)
600                 }
601                 if err != nil {
602                         return fmt.Errorf("While staging writable file from %q to %q: %v", cp.src, cp.bind, err)
603                 }
604         }
605
606         return nil
607 }
608
609 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
610         // Handle docker log protocol
611         // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
612         defer close(runner.loggingDone)
613
614         header := make([]byte, 8)
615         var err error
616         for err == nil {
617                 _, err = io.ReadAtLeast(containerReader, header, 8)
618                 if err != nil {
619                         if err == io.EOF {
620                                 err = nil
621                         }
622                         break
623                 }
624                 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
625                 if header[0] == 1 {
626                         // stdout
627                         _, err = io.CopyN(runner.Stdout, containerReader, readsize)
628                 } else {
629                         // stderr
630                         _, err = io.CopyN(runner.Stderr, containerReader, readsize)
631                 }
632         }
633
634         if err != nil {
635                 runner.CrunchLog.Printf("error reading docker logs: %v", err)
636         }
637
638         err = runner.Stdout.Close()
639         if err != nil {
640                 runner.CrunchLog.Printf("error closing stdout logs: %v", err)
641         }
642
643         err = runner.Stderr.Close()
644         if err != nil {
645                 runner.CrunchLog.Printf("error closing stderr logs: %v", err)
646         }
647
648         if runner.statReporter != nil {
649                 runner.statReporter.Stop()
650                 err = runner.statLogger.Close()
651                 if err != nil {
652                         runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
653                 }
654         }
655 }
656
657 func (runner *ContainerRunner) stopHoststat() error {
658         if runner.hoststatReporter == nil {
659                 return nil
660         }
661         runner.hoststatReporter.Stop()
662         err := runner.hoststatLogger.Close()
663         if err != nil {
664                 return fmt.Errorf("error closing hoststat logs: %v", err)
665         }
666         return nil
667 }
668
669 func (runner *ContainerRunner) startHoststat() {
670         runner.hoststatLogger = NewThrottledLogger(runner.NewLogWriter("hoststat"))
671         runner.hoststatReporter = &crunchstat.Reporter{
672                 Logger:     log.New(runner.hoststatLogger, "", 0),
673                 CgroupRoot: runner.cgroupRoot,
674                 PollPeriod: runner.statInterval,
675         }
676         runner.hoststatReporter.Start()
677 }
678
679 func (runner *ContainerRunner) startCrunchstat() {
680         runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
681         runner.statReporter = &crunchstat.Reporter{
682                 CID:          runner.ContainerID,
683                 Logger:       log.New(runner.statLogger, "", 0),
684                 CgroupParent: runner.expectCgroupParent,
685                 CgroupRoot:   runner.cgroupRoot,
686                 PollPeriod:   runner.statInterval,
687         }
688         runner.statReporter.Start()
689 }
690
691 type infoCommand struct {
692         label string
693         cmd   []string
694 }
695
696 // LogHostInfo logs info about the current host, for debugging and
697 // accounting purposes. Although it's logged as "node-info", this is
698 // about the environment where crunch-run is actually running, which
699 // might differ from what's described in the node record (see
700 // LogNodeRecord).
701 func (runner *ContainerRunner) LogHostInfo() (err error) {
702         w := runner.NewLogWriter("node-info")
703
704         commands := []infoCommand{
705                 {
706                         label: "Host Information",
707                         cmd:   []string{"uname", "-a"},
708                 },
709                 {
710                         label: "CPU Information",
711                         cmd:   []string{"cat", "/proc/cpuinfo"},
712                 },
713                 {
714                         label: "Memory Information",
715                         cmd:   []string{"cat", "/proc/meminfo"},
716                 },
717                 {
718                         label: "Disk Space",
719                         cmd:   []string{"df", "-m", "/", os.TempDir()},
720                 },
721                 {
722                         label: "Disk INodes",
723                         cmd:   []string{"df", "-i", "/", os.TempDir()},
724                 },
725         }
726
727         // Run commands with informational output to be logged.
728         for _, command := range commands {
729                 fmt.Fprintln(w, command.label)
730                 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
731                 cmd.Stdout = w
732                 cmd.Stderr = w
733                 if err := cmd.Run(); err != nil {
734                         err = fmt.Errorf("While running command %q: %v", command.cmd, err)
735                         fmt.Fprintln(w, err)
736                         return err
737                 }
738                 fmt.Fprintln(w, "")
739         }
740
741         err = w.Close()
742         if err != nil {
743                 return fmt.Errorf("While closing node-info logs: %v", err)
744         }
745         return nil
746 }
747
748 // LogContainerRecord gets and saves the raw JSON container record from the API server
749 func (runner *ContainerRunner) LogContainerRecord() error {
750         logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
751         if !logged && err == nil {
752                 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
753         }
754         return err
755 }
756
757 // LogNodeRecord logs arvados#node record corresponding to the current host.
758 func (runner *ContainerRunner) LogNodeRecord() error {
759         hostname := os.Getenv("SLURMD_NODENAME")
760         if hostname == "" {
761                 hostname, _ = os.Hostname()
762         }
763         _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
764                 // The "info" field has admin-only info when obtained
765                 // with a privileged token, and should not be logged.
766                 node, ok := resp.(map[string]interface{})
767                 if ok {
768                         delete(node, "info")
769                 }
770         })
771         return err
772 }
773
774 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
775         w := &ArvLogWriter{
776                 ArvClient:     runner.ArvClient,
777                 UUID:          runner.Container.UUID,
778                 loggingStream: label,
779                 writeCloser:   runner.LogCollection.Open(label + ".json"),
780         }
781
782         reader, err := runner.ArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
783         if err != nil {
784                 return false, fmt.Errorf("error getting %s record: %v", label, err)
785         }
786         defer reader.Close()
787
788         dec := json.NewDecoder(reader)
789         dec.UseNumber()
790         var resp map[string]interface{}
791         if err = dec.Decode(&resp); err != nil {
792                 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
793         }
794         items, ok := resp["items"].([]interface{})
795         if !ok {
796                 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
797         } else if len(items) < 1 {
798                 return false, nil
799         }
800         if munge != nil {
801                 munge(items[0])
802         }
803         // Re-encode it using indentation to improve readability
804         enc := json.NewEncoder(w)
805         enc.SetIndent("", "    ")
806         if err = enc.Encode(items[0]); err != nil {
807                 return false, fmt.Errorf("error logging %s record: %v", label, err)
808         }
809         err = w.Close()
810         if err != nil {
811                 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
812         }
813         return true, nil
814 }
815
816 // AttachStreams connects the docker container stdin, stdout and stderr logs
817 // to the Arvados logger which logs to Keep and the API server logs table.
818 func (runner *ContainerRunner) AttachStreams() (err error) {
819
820         runner.CrunchLog.Print("Attaching container streams")
821
822         // If stdin mount is provided, attach it to the docker container
823         var stdinRdr arvados.File
824         var stdinJson []byte
825         if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
826                 if stdinMnt.Kind == "collection" {
827                         var stdinColl arvados.Collection
828                         collId := stdinMnt.UUID
829                         if collId == "" {
830                                 collId = stdinMnt.PortableDataHash
831                         }
832                         err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
833                         if err != nil {
834                                 return fmt.Errorf("While getting stding collection: %v", err)
835                         }
836
837                         stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
838                         if os.IsNotExist(err) {
839                                 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
840                         } else if err != nil {
841                                 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
842                         }
843                 } else if stdinMnt.Kind == "json" {
844                         stdinJson, err = json.Marshal(stdinMnt.Content)
845                         if err != nil {
846                                 return fmt.Errorf("While encoding stdin json data: %v", err)
847                         }
848                 }
849         }
850
851         stdinUsed := stdinRdr != nil || len(stdinJson) != 0
852         response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
853                 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
854         if err != nil {
855                 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
856         }
857
858         runner.loggingDone = make(chan bool)
859
860         if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
861                 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
862                 if err != nil {
863                         return err
864                 }
865                 runner.Stdout = stdoutFile
866         } else {
867                 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
868         }
869
870         if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
871                 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
872                 if err != nil {
873                         return err
874                 }
875                 runner.Stderr = stderrFile
876         } else {
877                 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
878         }
879
880         if stdinRdr != nil {
881                 go func() {
882                         _, err := io.Copy(response.Conn, stdinRdr)
883                         if err != nil {
884                                 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
885                                 runner.stop()
886                         }
887                         stdinRdr.Close()
888                         response.CloseWrite()
889                 }()
890         } else if len(stdinJson) != 0 {
891                 go func() {
892                         _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
893                         if err != nil {
894                                 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
895                                 runner.stop()
896                         }
897                         response.CloseWrite()
898                 }()
899         }
900
901         go runner.ProcessDockerAttach(response.Reader)
902
903         return nil
904 }
905
906 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
907         stdoutPath := mntPath[len(runner.Container.OutputPath):]
908         index := strings.LastIndex(stdoutPath, "/")
909         if index > 0 {
910                 subdirs := stdoutPath[:index]
911                 if subdirs != "" {
912                         st, err := os.Stat(runner.HostOutputDir)
913                         if err != nil {
914                                 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
915                         }
916                         stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
917                         err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
918                         if err != nil {
919                                 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
920                         }
921                 }
922         }
923         stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
924         if err != nil {
925                 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
926         }
927
928         return stdoutFile, nil
929 }
930
931 // CreateContainer creates the docker container.
932 func (runner *ContainerRunner) CreateContainer() error {
933         runner.CrunchLog.Print("Creating Docker container")
934
935         runner.ContainerConfig.Cmd = runner.Container.Command
936         if runner.Container.Cwd != "." {
937                 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
938         }
939
940         for k, v := range runner.Container.Environment {
941                 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
942         }
943
944         runner.ContainerConfig.Volumes = runner.Volumes
945
946         runner.HostConfig = dockercontainer.HostConfig{
947                 Binds: runner.Binds,
948                 LogConfig: dockercontainer.LogConfig{
949                         Type: "none",
950                 },
951                 Resources: dockercontainer.Resources{
952                         CgroupParent: runner.setCgroupParent,
953                 },
954         }
955
956         if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
957                 tok, err := runner.ContainerToken()
958                 if err != nil {
959                         return err
960                 }
961                 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
962                         "ARVADOS_API_TOKEN="+tok,
963                         "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
964                         "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
965                 )
966                 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
967         } else {
968                 if runner.enableNetwork == "always" {
969                         runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
970                 } else {
971                         runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
972                 }
973         }
974
975         _, stdinUsed := runner.Container.Mounts["stdin"]
976         runner.ContainerConfig.OpenStdin = stdinUsed
977         runner.ContainerConfig.StdinOnce = stdinUsed
978         runner.ContainerConfig.AttachStdin = stdinUsed
979         runner.ContainerConfig.AttachStdout = true
980         runner.ContainerConfig.AttachStderr = true
981
982         createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
983         if err != nil {
984                 return fmt.Errorf("While creating container: %v", err)
985         }
986
987         runner.ContainerID = createdBody.ID
988
989         return runner.AttachStreams()
990 }
991
992 // StartContainer starts the docker container created by CreateContainer.
993 func (runner *ContainerRunner) StartContainer() error {
994         runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
995         runner.cStateLock.Lock()
996         defer runner.cStateLock.Unlock()
997         if runner.cCancelled {
998                 return ErrCancelled
999         }
1000         err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
1001                 dockertypes.ContainerStartOptions{})
1002         if err != nil {
1003                 var advice string
1004                 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
1005                         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])
1006                 }
1007                 return fmt.Errorf("could not start container: %v%s", err, advice)
1008         }
1009         return nil
1010 }
1011
1012 // WaitFinish waits for the container to terminate, capture the exit code, and
1013 // close the stdout/stderr logging.
1014 func (runner *ContainerRunner) WaitFinish() error {
1015         runner.CrunchLog.Print("Waiting for container to finish")
1016
1017         waitOk, waitErr := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID, dockercontainer.WaitConditionNotRunning)
1018         arvMountExit := runner.ArvMountExit
1019         for {
1020                 select {
1021                 case waitBody := <-waitOk:
1022                         runner.CrunchLog.Printf("Container exited with code: %v", waitBody.StatusCode)
1023                         code := int(waitBody.StatusCode)
1024                         runner.ExitCode = &code
1025
1026                         // wait for stdout/stderr to complete
1027                         <-runner.loggingDone
1028                         return nil
1029
1030                 case err := <-waitErr:
1031                         return fmt.Errorf("container wait: %v", err)
1032
1033                 case <-arvMountExit:
1034                         runner.CrunchLog.Printf("arv-mount exited while container is still running.  Stopping container.")
1035                         runner.stop()
1036                         // arvMountExit will always be ready now that
1037                         // it's closed, but that doesn't interest us.
1038                         arvMountExit = nil
1039                 }
1040         }
1041 }
1042
1043 var ErrNotInOutputDir = fmt.Errorf("Must point to path within the output directory")
1044
1045 func (runner *ContainerRunner) derefOutputSymlink(path string, startinfo os.FileInfo) (tgt string, readlinktgt string, info os.FileInfo, err error) {
1046         // Follow symlinks if necessary
1047         info = startinfo
1048         tgt = path
1049         readlinktgt = ""
1050         nextlink := path
1051         for followed := 0; info.Mode()&os.ModeSymlink != 0; followed++ {
1052                 if followed >= limitFollowSymlinks {
1053                         // Got stuck in a loop or just a pathological number of links, give up.
1054                         err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
1055                         return
1056                 }
1057
1058                 readlinktgt, err = os.Readlink(nextlink)
1059                 if err != nil {
1060                         return
1061                 }
1062
1063                 tgt = readlinktgt
1064                 if !strings.HasPrefix(tgt, "/") {
1065                         // Relative symlink, resolve it to host path
1066                         tgt = filepath.Join(filepath.Dir(path), tgt)
1067                 }
1068                 if strings.HasPrefix(tgt, runner.Container.OutputPath+"/") && !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
1069                         // Absolute symlink to container output path, adjust it to host output path.
1070                         tgt = filepath.Join(runner.HostOutputDir, tgt[len(runner.Container.OutputPath):])
1071                 }
1072                 if !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
1073                         // After dereferencing, symlink target must either be
1074                         // within output directory, or must point to a
1075                         // collection mount.
1076                         err = ErrNotInOutputDir
1077                         return
1078                 }
1079
1080                 info, err = os.Lstat(tgt)
1081                 if err != nil {
1082                         // tgt
1083                         err = fmt.Errorf("Symlink in output %q points to invalid location %q: %v",
1084                                 path[len(runner.HostOutputDir):], readlinktgt, err)
1085                         return
1086                 }
1087
1088                 nextlink = tgt
1089         }
1090
1091         return
1092 }
1093
1094 var limitFollowSymlinks = 10
1095
1096 // UploadFile uploads files within the output directory, with special handling
1097 // for symlinks. If the symlink leads to a keep mount, copy the manifest text
1098 // from the keep mount into the output manifestText.  Ensure that whether
1099 // symlinks are relative or absolute, every symlink target (even targets that
1100 // are symlinks themselves) must point to a path in either the output directory
1101 // or a collection mount.
1102 //
1103 // Assumes initial value of "path" is absolute, and located within runner.HostOutputDir.
1104 func (runner *ContainerRunner) UploadOutputFile(
1105         path string,
1106         info os.FileInfo,
1107         infoerr error,
1108         binds []string,
1109         walkUpload *WalkUpload,
1110         relocateFrom string,
1111         relocateTo string,
1112         followed int) (manifestText string, err error) {
1113
1114         if infoerr != nil {
1115                 return "", infoerr
1116         }
1117
1118         if info.Mode().IsDir() {
1119                 // if empty, need to create a .keep file
1120                 dir, direrr := os.Open(path)
1121                 if direrr != nil {
1122                         return "", direrr
1123                 }
1124                 defer dir.Close()
1125                 names, eof := dir.Readdirnames(1)
1126                 if len(names) == 0 && eof == io.EOF && path != runner.HostOutputDir {
1127                         containerPath := runner.OutputPath + path[len(runner.HostOutputDir):]
1128                         for _, bind := range binds {
1129                                 mnt := runner.Container.Mounts[bind]
1130                                 // Check if there is a bind for this
1131                                 // directory, in which case assume we don't need .keep
1132                                 if (containerPath == bind || strings.HasPrefix(containerPath, bind+"/")) && mnt.PortableDataHash != "d41d8cd98f00b204e9800998ecf8427e+0" {
1133                                         return
1134                                 }
1135                         }
1136                         outputSuffix := path[len(runner.HostOutputDir)+1:]
1137                         return fmt.Sprintf("./%v d41d8cd98f00b204e9800998ecf8427e+0 0:0:.keep\n", outputSuffix), nil
1138                 }
1139                 return
1140         }
1141
1142         if followed >= limitFollowSymlinks {
1143                 // Got stuck in a loop or just a pathological number of
1144                 // directory links, give up.
1145                 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
1146                 return
1147         }
1148
1149         // "path" is the actual path we are visiting
1150         // "tgt" is the target of "path" (a non-symlink) after following symlinks
1151         // "relocated" is the path in the output manifest where the file should be placed,
1152         // but has HostOutputDir as a prefix.
1153
1154         // The destination path in the output manifest may need to be
1155         // logically relocated to some other path in order to appear
1156         // in the correct location as a result of following a symlink.
1157         // Remove the relocateFrom prefix and replace it with
1158         // relocateTo.
1159         relocated := relocateTo + path[len(relocateFrom):]
1160
1161         tgt, readlinktgt, info, derefErr := runner.derefOutputSymlink(path, info)
1162         if derefErr != nil && derefErr != ErrNotInOutputDir {
1163                 return "", derefErr
1164         }
1165
1166         // go through mounts and try reverse map to collection reference
1167         for _, bind := range binds {
1168                 mnt := runner.Container.Mounts[bind]
1169                 if (tgt == bind || strings.HasPrefix(tgt, bind+"/")) && !mnt.Writable {
1170                         // get path relative to bind
1171                         targetSuffix := tgt[len(bind):]
1172
1173                         // Copy mount and adjust the path to add path relative to the bind
1174                         adjustedMount := mnt
1175                         adjustedMount.Path = filepath.Join(adjustedMount.Path, targetSuffix)
1176
1177                         // Terminates in this keep mount, so add the
1178                         // manifest text at appropriate location.
1179                         outputSuffix := relocated[len(runner.HostOutputDir):]
1180                         manifestText, err = runner.getCollectionManifestForPath(adjustedMount, outputSuffix)
1181                         return
1182                 }
1183         }
1184
1185         // If target is not a collection mount, it must be located within the
1186         // output directory, otherwise it is an error.
1187         if derefErr == ErrNotInOutputDir {
1188                 err = fmt.Errorf("Symlink in output %q points to invalid location %q, must point to path within the output directory.",
1189                         path[len(runner.HostOutputDir):], readlinktgt)
1190                 return
1191         }
1192
1193         if info.Mode().IsRegular() {
1194                 return "", walkUpload.UploadFile(relocated, tgt)
1195         }
1196
1197         if info.Mode().IsDir() {
1198                 // Symlink leads to directory.  Walk() doesn't follow
1199                 // directory symlinks, so we walk the target directory
1200                 // instead.  Within the walk, file paths are relocated
1201                 // so they appear under the original symlink path.
1202                 err = filepath.Walk(tgt, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
1203                         var m string
1204                         m, walkerr = runner.UploadOutputFile(walkpath, walkinfo, walkerr,
1205                                 binds, walkUpload, tgt, relocated, followed+1)
1206                         if walkerr == nil {
1207                                 manifestText = manifestText + m
1208                         }
1209                         return walkerr
1210                 })
1211                 return
1212         }
1213
1214         return
1215 }
1216
1217 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
1218 func (runner *ContainerRunner) CaptureOutput() error {
1219         if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
1220                 // Output may have been set directly by the container, so
1221                 // refresh the container record to check.
1222                 err := runner.ArvClient.Get("containers", runner.Container.UUID,
1223                         nil, &runner.Container)
1224                 if err != nil {
1225                         return err
1226                 }
1227                 if runner.Container.Output != "" {
1228                         // Container output is already set.
1229                         runner.OutputPDH = &runner.Container.Output
1230                         return nil
1231                 }
1232         }
1233
1234         if runner.HostOutputDir == "" {
1235                 return nil
1236         }
1237
1238         _, err := os.Stat(runner.HostOutputDir)
1239         if err != nil {
1240                 return fmt.Errorf("While checking host output path: %v", err)
1241         }
1242
1243         // Pre-populate output from the configured mount points
1244         var binds []string
1245         for bind, mnt := range runner.Container.Mounts {
1246                 if mnt.Kind == "collection" {
1247                         binds = append(binds, bind)
1248                 }
1249         }
1250         sort.Strings(binds)
1251
1252         var manifestText string
1253
1254         collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
1255         _, err = os.Stat(collectionMetafile)
1256         if err != nil {
1257                 // Regular directory
1258
1259                 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
1260                 walkUpload := cw.BeginUpload(runner.HostOutputDir, runner.CrunchLog.Logger)
1261
1262                 var m string
1263                 err = filepath.Walk(runner.HostOutputDir, func(path string, info os.FileInfo, err error) error {
1264                         m, err = runner.UploadOutputFile(path, info, err, binds, walkUpload, "", "", 0)
1265                         if err == nil {
1266                                 manifestText = manifestText + m
1267                         }
1268                         return err
1269                 })
1270
1271                 cw.EndUpload(walkUpload)
1272
1273                 if err != nil {
1274                         return fmt.Errorf("While uploading output files: %v", err)
1275                 }
1276
1277                 m, err = cw.ManifestText()
1278                 manifestText = manifestText + m
1279                 if err != nil {
1280                         return fmt.Errorf("While uploading output files: %v", err)
1281                 }
1282         } else {
1283                 // FUSE mount directory
1284                 file, openerr := os.Open(collectionMetafile)
1285                 if openerr != nil {
1286                         return fmt.Errorf("While opening FUSE metafile: %v", err)
1287                 }
1288                 defer file.Close()
1289
1290                 var rec arvados.Collection
1291                 err = json.NewDecoder(file).Decode(&rec)
1292                 if err != nil {
1293                         return fmt.Errorf("While reading FUSE metafile: %v", err)
1294                 }
1295                 manifestText = rec.ManifestText
1296         }
1297
1298         for _, bind := range binds {
1299                 mnt := runner.Container.Mounts[bind]
1300
1301                 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
1302
1303                 if bindSuffix == bind || len(bindSuffix) <= 0 {
1304                         // either does not start with OutputPath or is OutputPath itself
1305                         continue
1306                 }
1307
1308                 if mnt.ExcludeFromOutput == true || mnt.Writable {
1309                         continue
1310                 }
1311
1312                 // append to manifest_text
1313                 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
1314                 if err != nil {
1315                         return err
1316                 }
1317
1318                 manifestText = manifestText + m
1319         }
1320
1321         // Save output
1322         var response arvados.Collection
1323         manifest := manifest.Manifest{Text: manifestText}
1324         manifestText = manifest.Extract(".", ".").Text
1325         err = runner.ArvClient.Create("collections",
1326                 arvadosclient.Dict{
1327                         "ensure_unique_name": true,
1328                         "collection": arvadosclient.Dict{
1329                                 "is_trashed":    true,
1330                                 "name":          "output for " + runner.Container.UUID,
1331                                 "manifest_text": manifestText}},
1332                 &response)
1333         if err != nil {
1334                 return fmt.Errorf("While creating output collection: %v", err)
1335         }
1336         runner.OutputPDH = &response.PortableDataHash
1337         return nil
1338 }
1339
1340 var outputCollections = make(map[string]arvados.Collection)
1341
1342 // Fetch the collection for the mnt.PortableDataHash
1343 // Return the manifest_text fragment corresponding to the specified mnt.Path
1344 //  after making any required updates.
1345 //  Ex:
1346 //    If mnt.Path is not specified,
1347 //      return the entire manifest_text after replacing any "." with bindSuffix
1348 //    If mnt.Path corresponds to one stream,
1349 //      return the manifest_text for that stream after replacing that stream name with bindSuffix
1350 //    Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1351 //      for that stream after replacing stream name with bindSuffix minus the last word
1352 //      and the file name with last word of the bindSuffix
1353 //  Allowed path examples:
1354 //    "path":"/"
1355 //    "path":"/subdir1"
1356 //    "path":"/subdir1/subdir2"
1357 //    "path":"/subdir/filename" etc
1358 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1359         collection := outputCollections[mnt.PortableDataHash]
1360         if collection.PortableDataHash == "" {
1361                 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1362                 if err != nil {
1363                         return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1364                 }
1365                 outputCollections[mnt.PortableDataHash] = collection
1366         }
1367
1368         if collection.ManifestText == "" {
1369                 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1370                 return "", nil
1371         }
1372
1373         mft := manifest.Manifest{Text: collection.ManifestText}
1374         extracted := mft.Extract(mnt.Path, bindSuffix)
1375         if extracted.Err != nil {
1376                 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1377         }
1378         return extracted.Text, nil
1379 }
1380
1381 func (runner *ContainerRunner) CleanupDirs() {
1382         if runner.ArvMount != nil {
1383                 var delay int64 = 8
1384                 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1385                 umount.Stdout = runner.CrunchLog
1386                 umount.Stderr = runner.CrunchLog
1387                 runner.CrunchLog.Printf("Running %v", umount.Args)
1388                 umnterr := umount.Start()
1389
1390                 if umnterr != nil {
1391                         runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1392                 } else {
1393                         // If arv-mount --unmount gets stuck for any reason, we
1394                         // don't want to wait for it forever.  Do Wait() in a goroutine
1395                         // so it doesn't block crunch-run.
1396                         umountExit := make(chan error)
1397                         go func() {
1398                                 mnterr := umount.Wait()
1399                                 if mnterr != nil {
1400                                         runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1401                                 }
1402                                 umountExit <- mnterr
1403                         }()
1404
1405                         for again := true; again; {
1406                                 again = false
1407                                 select {
1408                                 case <-umountExit:
1409                                         umount = nil
1410                                         again = true
1411                                 case <-runner.ArvMountExit:
1412                                         break
1413                                 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1414                                         runner.CrunchLog.Printf("Timed out waiting for unmount")
1415                                         if umount != nil {
1416                                                 umount.Process.Kill()
1417                                         }
1418                                         runner.ArvMount.Process.Kill()
1419                                 }
1420                         }
1421                 }
1422         }
1423
1424         if runner.ArvMountPoint != "" {
1425                 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1426                         runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1427                 }
1428         }
1429
1430         for _, tmpdir := range runner.CleanupTempDir {
1431                 if rmerr := os.RemoveAll(tmpdir); rmerr != nil {
1432                         runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1433                 }
1434         }
1435 }
1436
1437 // CommitLogs posts the collection containing the final container logs.
1438 func (runner *ContainerRunner) CommitLogs() error {
1439         runner.CrunchLog.Print(runner.finalState)
1440
1441         if runner.arvMountLog != nil {
1442                 runner.arvMountLog.Close()
1443         }
1444         runner.CrunchLog.Close()
1445
1446         // Closing CrunchLog above allows them to be committed to Keep at this
1447         // point, but re-open crunch log with ArvClient in case there are any
1448         // other further errors (such as failing to write the log to Keep!)
1449         // while shutting down
1450         runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1451                 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1452         runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1453
1454         if runner.LogsPDH != nil {
1455                 // If we have already assigned something to LogsPDH,
1456                 // we must be closing the re-opened log, which won't
1457                 // end up getting attached to the container record and
1458                 // therefore doesn't need to be saved as a collection
1459                 // -- it exists only to send logs to other channels.
1460                 return nil
1461         }
1462
1463         mt, err := runner.LogCollection.ManifestText()
1464         if err != nil {
1465                 return fmt.Errorf("While creating log manifest: %v", err)
1466         }
1467
1468         var response arvados.Collection
1469         err = runner.ArvClient.Create("collections",
1470                 arvadosclient.Dict{
1471                         "ensure_unique_name": true,
1472                         "collection": arvadosclient.Dict{
1473                                 "is_trashed":    true,
1474                                 "name":          "logs for " + runner.Container.UUID,
1475                                 "manifest_text": mt}},
1476                 &response)
1477         if err != nil {
1478                 return fmt.Errorf("While creating log collection: %v", err)
1479         }
1480         runner.LogsPDH = &response.PortableDataHash
1481         return nil
1482 }
1483
1484 // UpdateContainerRunning updates the container state to "Running"
1485 func (runner *ContainerRunner) UpdateContainerRunning() error {
1486         runner.cStateLock.Lock()
1487         defer runner.cStateLock.Unlock()
1488         if runner.cCancelled {
1489                 return ErrCancelled
1490         }
1491         return runner.ArvClient.Update("containers", runner.Container.UUID,
1492                 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1493 }
1494
1495 // ContainerToken returns the api_token the container (and any
1496 // arv-mount processes) are allowed to use.
1497 func (runner *ContainerRunner) ContainerToken() (string, error) {
1498         if runner.token != "" {
1499                 return runner.token, nil
1500         }
1501
1502         var auth arvados.APIClientAuthorization
1503         err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1504         if err != nil {
1505                 return "", err
1506         }
1507         runner.token = auth.APIToken
1508         return runner.token, nil
1509 }
1510
1511 // UpdateContainerComplete updates the container record state on API
1512 // server to "Complete" or "Cancelled"
1513 func (runner *ContainerRunner) UpdateContainerFinal() error {
1514         update := arvadosclient.Dict{}
1515         update["state"] = runner.finalState
1516         if runner.LogsPDH != nil {
1517                 update["log"] = *runner.LogsPDH
1518         }
1519         if runner.finalState == "Complete" {
1520                 if runner.ExitCode != nil {
1521                         update["exit_code"] = *runner.ExitCode
1522                 }
1523                 if runner.OutputPDH != nil {
1524                         update["output"] = *runner.OutputPDH
1525                 }
1526         }
1527         return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1528 }
1529
1530 // IsCancelled returns the value of Cancelled, with goroutine safety.
1531 func (runner *ContainerRunner) IsCancelled() bool {
1532         runner.cStateLock.Lock()
1533         defer runner.cStateLock.Unlock()
1534         return runner.cCancelled
1535 }
1536
1537 // NewArvLogWriter creates an ArvLogWriter
1538 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1539         return &ArvLogWriter{
1540                 ArvClient:     runner.ArvClient,
1541                 UUID:          runner.Container.UUID,
1542                 loggingStream: name,
1543                 writeCloser:   runner.LogCollection.Open(name + ".txt")}
1544 }
1545
1546 // Run the full container lifecycle.
1547 func (runner *ContainerRunner) Run() (err error) {
1548         runner.CrunchLog.Printf("crunch-run %s started", version)
1549         runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1550
1551         hostname, hosterr := os.Hostname()
1552         if hosterr != nil {
1553                 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1554         } else {
1555                 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1556         }
1557
1558         runner.finalState = "Queued"
1559
1560         defer func() {
1561                 runner.stopSignals()
1562                 runner.CleanupDirs()
1563
1564                 runner.CrunchLog.Printf("crunch-run finished")
1565                 runner.CrunchLog.Close()
1566         }()
1567
1568         defer func() {
1569                 // checkErr prints e (unless it's nil) and sets err to
1570                 // e (unless err is already non-nil). Thus, if err
1571                 // hasn't already been assigned when Run() returns,
1572                 // this cleanup func will cause Run() to return the
1573                 // first non-nil error that is passed to checkErr().
1574                 checkErr := func(e error) {
1575                         if e == nil {
1576                                 return
1577                         }
1578                         runner.CrunchLog.Print(e)
1579                         if err == nil {
1580                                 err = e
1581                         }
1582                         if runner.finalState == "Complete" {
1583                                 // There was an error in the finalization.
1584                                 runner.finalState = "Cancelled"
1585                         }
1586                 }
1587
1588                 // Log the error encountered in Run(), if any
1589                 checkErr(err)
1590
1591                 if runner.finalState == "Queued" {
1592                         runner.UpdateContainerFinal()
1593                         return
1594                 }
1595
1596                 if runner.IsCancelled() {
1597                         runner.finalState = "Cancelled"
1598                         // but don't return yet -- we still want to
1599                         // capture partial output and write logs
1600                 }
1601
1602                 checkErr(runner.CaptureOutput())
1603                 checkErr(runner.stopHoststat())
1604                 checkErr(runner.CommitLogs())
1605                 checkErr(runner.UpdateContainerFinal())
1606         }()
1607
1608         err = runner.fetchContainerRecord()
1609         if err != nil {
1610                 return
1611         }
1612         runner.setupSignals()
1613         runner.startHoststat()
1614
1615         // check for and/or load image
1616         err = runner.LoadImage()
1617         if err != nil {
1618                 if !runner.checkBrokenNode(err) {
1619                         // Failed to load image but not due to a "broken node"
1620                         // condition, probably user error.
1621                         runner.finalState = "Cancelled"
1622                 }
1623                 err = fmt.Errorf("While loading container image: %v", err)
1624                 return
1625         }
1626
1627         // set up FUSE mount and binds
1628         err = runner.SetupMounts()
1629         if err != nil {
1630                 runner.finalState = "Cancelled"
1631                 err = fmt.Errorf("While setting up mounts: %v", err)
1632                 return
1633         }
1634
1635         err = runner.CreateContainer()
1636         if err != nil {
1637                 return
1638         }
1639         err = runner.LogHostInfo()
1640         if err != nil {
1641                 return
1642         }
1643         err = runner.LogNodeRecord()
1644         if err != nil {
1645                 return
1646         }
1647         err = runner.LogContainerRecord()
1648         if err != nil {
1649                 return
1650         }
1651
1652         if runner.IsCancelled() {
1653                 return
1654         }
1655
1656         err = runner.UpdateContainerRunning()
1657         if err != nil {
1658                 return
1659         }
1660         runner.finalState = "Cancelled"
1661
1662         runner.startCrunchstat()
1663
1664         err = runner.StartContainer()
1665         if err != nil {
1666                 runner.checkBrokenNode(err)
1667                 return
1668         }
1669
1670         err = runner.WaitFinish()
1671         if err == nil && !runner.IsCancelled() {
1672                 runner.finalState = "Complete"
1673         }
1674         return
1675 }
1676
1677 // Fetch the current container record (uuid = runner.Container.UUID)
1678 // into runner.Container.
1679 func (runner *ContainerRunner) fetchContainerRecord() error {
1680         reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1681         if err != nil {
1682                 return fmt.Errorf("error fetching container record: %v", err)
1683         }
1684         defer reader.Close()
1685
1686         dec := json.NewDecoder(reader)
1687         dec.UseNumber()
1688         err = dec.Decode(&runner.Container)
1689         if err != nil {
1690                 return fmt.Errorf("error decoding container record: %v", err)
1691         }
1692         return nil
1693 }
1694
1695 // NewContainerRunner creates a new container runner.
1696 func NewContainerRunner(api IArvadosClient,
1697         kc IKeepClient,
1698         docker ThinDockerClient,
1699         containerUUID string) *ContainerRunner {
1700
1701         cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1702         cr.NewLogWriter = cr.NewArvLogWriter
1703         cr.RunArvMount = cr.ArvMountCmd
1704         cr.MkTempDir = ioutil.TempDir
1705         cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1706         cr.Container.UUID = containerUUID
1707         cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1708         cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1709
1710         loadLogThrottleParams(api)
1711
1712         return cr
1713 }
1714
1715 func main() {
1716         statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1717         cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1718         cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1719         cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1720         caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1721         enableNetwork := flag.String("container-enable-networking", "default",
1722                 `Specify if networking should be enabled for container.  One of 'default', 'always':
1723         default: only enable networking if container requests it.
1724         always:  containers always have networking enabled
1725         `)
1726         networkMode := flag.String("container-network-mode", "default",
1727                 `Set networking mode for container.  Corresponds to Docker network mode (--net).
1728         `)
1729         memprofile := flag.String("memprofile", "", "write memory profile to `file` after running container")
1730         getVersion := flag.Bool("version", false, "Print version information and exit.")
1731         flag.Parse()
1732
1733         // Print version information if requested
1734         if *getVersion {
1735                 fmt.Printf("crunch-run %s\n", version)
1736                 return
1737         }
1738
1739         log.Printf("crunch-run %s started", version)
1740
1741         containerId := flag.Arg(0)
1742
1743         if *caCertsPath != "" {
1744                 arvadosclient.CertFiles = []string{*caCertsPath}
1745         }
1746
1747         api, err := arvadosclient.MakeArvadosClient()
1748         if err != nil {
1749                 log.Fatalf("%s: %v", containerId, err)
1750         }
1751         api.Retries = 8
1752
1753         kc, kcerr := keepclient.MakeKeepClient(api)
1754         if kcerr != nil {
1755                 log.Fatalf("%s: %v", containerId, kcerr)
1756         }
1757         kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1758         kc.Retries = 4
1759
1760         // API version 1.21 corresponds to Docker 1.9, which is currently the
1761         // minimum version we want to support.
1762         docker, dockererr := dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1763
1764         cr := NewContainerRunner(api, kc, docker, containerId)
1765         if dockererr != nil {
1766                 cr.CrunchLog.Printf("%s: %v", containerId, dockererr)
1767                 cr.checkBrokenNode(dockererr)
1768                 cr.CrunchLog.Close()
1769                 os.Exit(1)
1770         }
1771
1772         cr.statInterval = *statInterval
1773         cr.cgroupRoot = *cgroupRoot
1774         cr.expectCgroupParent = *cgroupParent
1775         cr.enableNetwork = *enableNetwork
1776         cr.networkMode = *networkMode
1777         if *cgroupParentSubsystem != "" {
1778                 p := findCgroup(*cgroupParentSubsystem)
1779                 cr.setCgroupParent = p
1780                 cr.expectCgroupParent = p
1781         }
1782
1783         runerr := cr.Run()
1784
1785         if *memprofile != "" {
1786                 f, err := os.Create(*memprofile)
1787                 if err != nil {
1788                         log.Printf("could not create memory profile: ", err)
1789                 }
1790                 runtime.GC() // get up-to-date statistics
1791                 if err := pprof.WriteHeapProfile(f); err != nil {
1792                         log.Printf("could not write memory profile: ", err)
1793                 }
1794                 closeerr := f.Close()
1795                 if closeerr != nil {
1796                         log.Printf("closing memprofile file: ", err)
1797                 }
1798         }
1799
1800         if runerr != nil {
1801                 log.Fatalf("%s: %v", containerId, runerr)
1802         }
1803 }