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