12991: Propagate memory and CPU limits to docker container.
[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         Binds         []string
110         Volumes       map[string]struct{}
111         OutputPDH     *string
112         SigChan       chan os.Signal
113         ArvMountExit  chan error
114         finalState    string
115         parentTemp    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(runner.parentTemp, 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), 0777)
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(runner.parentTemp, "tmp")
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.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", tmpdir, bind))
506                         if bind == runner.Container.OutputPath {
507                                 runner.HostOutputDir = tmpdir
508                         }
509
510                 case mnt.Kind == "json":
511                         jsondata, err := json.Marshal(mnt.Content)
512                         if err != nil {
513                                 return fmt.Errorf("encoding json data: %v", err)
514                         }
515                         // Create a tempdir with a single file
516                         // (instead of just a tempfile): this way we
517                         // can ensure the file is world-readable
518                         // inside the container, without having to
519                         // make it world-readable on the docker host.
520                         tmpdir, err := runner.MkTempDir(runner.parentTemp, "json")
521                         if err != nil {
522                                 return fmt.Errorf("creating temp dir: %v", err)
523                         }
524                         tmpfn := filepath.Join(tmpdir, "mountdata.json")
525                         err = ioutil.WriteFile(tmpfn, jsondata, 0644)
526                         if err != nil {
527                                 return fmt.Errorf("writing temp file: %v", err)
528                         }
529                         runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
530
531                 case mnt.Kind == "git_tree":
532                         tmpdir, err := runner.MkTempDir(runner.parentTemp, "git_tree")
533                         if err != nil {
534                                 return fmt.Errorf("creating temp dir: %v", err)
535                         }
536                         err = gitMount(mnt).extractTree(runner.ArvClient, tmpdir, token)
537                         if err != nil {
538                                 return err
539                         }
540                         runner.Binds = append(runner.Binds, tmpdir+":"+bind+":ro")
541                 }
542         }
543
544         if runner.HostOutputDir == "" {
545                 return fmt.Errorf("Output path does not correspond to a writable mount point")
546         }
547
548         if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
549                 for _, certfile := range arvadosclient.CertFiles {
550                         _, err := os.Stat(certfile)
551                         if err == nil {
552                                 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
553                                 break
554                         }
555                 }
556         }
557
558         if pdhOnly {
559                 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
560         } else {
561                 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
562         }
563         arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
564
565         runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
566         if err != nil {
567                 return fmt.Errorf("While trying to start arv-mount: %v", err)
568         }
569
570         for _, p := range collectionPaths {
571                 _, err = os.Stat(p)
572                 if err != nil {
573                         return fmt.Errorf("While checking that input files exist: %v", err)
574                 }
575         }
576
577         for _, cp := range copyFiles {
578                 st, err := os.Stat(cp.src)
579                 if err != nil {
580                         return fmt.Errorf("While staging writable file from %q to %q: %v", cp.src, cp.bind, err)
581                 }
582                 if st.IsDir() {
583                         err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
584                                 if walkerr != nil {
585                                         return walkerr
586                                 }
587                                 target := path.Join(cp.bind, walkpath[len(cp.src):])
588                                 if walkinfo.Mode().IsRegular() {
589                                         copyerr := copyfile(walkpath, target)
590                                         if copyerr != nil {
591                                                 return copyerr
592                                         }
593                                         return os.Chmod(target, walkinfo.Mode()|0777)
594                                 } else if walkinfo.Mode().IsDir() {
595                                         mkerr := os.MkdirAll(target, 0777)
596                                         if mkerr != nil {
597                                                 return mkerr
598                                         }
599                                         return os.Chmod(target, walkinfo.Mode()|os.ModeSetgid|0777)
600                                 } else {
601                                         return fmt.Errorf("Source %q is not a regular file or directory", cp.src)
602                                 }
603                         })
604                 } else if st.Mode().IsRegular() {
605                         err = copyfile(cp.src, cp.bind)
606                         if err == nil {
607                                 err = os.Chmod(cp.bind, st.Mode()|0777)
608                         }
609                 }
610                 if err != nil {
611                         return fmt.Errorf("While staging writable file from %q to %q: %v", cp.src, cp.bind, err)
612                 }
613         }
614
615         return nil
616 }
617
618 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
619         // Handle docker log protocol
620         // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
621         defer close(runner.loggingDone)
622
623         header := make([]byte, 8)
624         var err error
625         for err == nil {
626                 _, err = io.ReadAtLeast(containerReader, header, 8)
627                 if err != nil {
628                         if err == io.EOF {
629                                 err = nil
630                         }
631                         break
632                 }
633                 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
634                 if header[0] == 1 {
635                         // stdout
636                         _, err = io.CopyN(runner.Stdout, containerReader, readsize)
637                 } else {
638                         // stderr
639                         _, err = io.CopyN(runner.Stderr, containerReader, readsize)
640                 }
641         }
642
643         if err != nil {
644                 runner.CrunchLog.Printf("error reading docker logs: %v", err)
645         }
646
647         err = runner.Stdout.Close()
648         if err != nil {
649                 runner.CrunchLog.Printf("error closing stdout logs: %v", err)
650         }
651
652         err = runner.Stderr.Close()
653         if err != nil {
654                 runner.CrunchLog.Printf("error closing stderr logs: %v", err)
655         }
656
657         if runner.statReporter != nil {
658                 runner.statReporter.Stop()
659                 err = runner.statLogger.Close()
660                 if err != nil {
661                         runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
662                 }
663         }
664 }
665
666 func (runner *ContainerRunner) stopHoststat() error {
667         if runner.hoststatReporter == nil {
668                 return nil
669         }
670         runner.hoststatReporter.Stop()
671         err := runner.hoststatLogger.Close()
672         if err != nil {
673                 return fmt.Errorf("error closing hoststat logs: %v", err)
674         }
675         return nil
676 }
677
678 func (runner *ContainerRunner) startHoststat() {
679         runner.hoststatLogger = NewThrottledLogger(runner.NewLogWriter("hoststat"))
680         runner.hoststatReporter = &crunchstat.Reporter{
681                 Logger:     log.New(runner.hoststatLogger, "", 0),
682                 CgroupRoot: runner.cgroupRoot,
683                 PollPeriod: runner.statInterval,
684         }
685         runner.hoststatReporter.Start()
686 }
687
688 func (runner *ContainerRunner) startCrunchstat() {
689         runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
690         runner.statReporter = &crunchstat.Reporter{
691                 CID:          runner.ContainerID,
692                 Logger:       log.New(runner.statLogger, "", 0),
693                 CgroupParent: runner.expectCgroupParent,
694                 CgroupRoot:   runner.cgroupRoot,
695                 PollPeriod:   runner.statInterval,
696         }
697         runner.statReporter.Start()
698 }
699
700 type infoCommand struct {
701         label string
702         cmd   []string
703 }
704
705 // LogHostInfo logs info about the current host, for debugging and
706 // accounting purposes. Although it's logged as "node-info", this is
707 // about the environment where crunch-run is actually running, which
708 // might differ from what's described in the node record (see
709 // LogNodeRecord).
710 func (runner *ContainerRunner) LogHostInfo() (err error) {
711         w := runner.NewLogWriter("node-info")
712
713         commands := []infoCommand{
714                 {
715                         label: "Host Information",
716                         cmd:   []string{"uname", "-a"},
717                 },
718                 {
719                         label: "CPU Information",
720                         cmd:   []string{"cat", "/proc/cpuinfo"},
721                 },
722                 {
723                         label: "Memory Information",
724                         cmd:   []string{"cat", "/proc/meminfo"},
725                 },
726                 {
727                         label: "Disk Space",
728                         cmd:   []string{"df", "-m", "/", os.TempDir()},
729                 },
730                 {
731                         label: "Disk INodes",
732                         cmd:   []string{"df", "-i", "/", os.TempDir()},
733                 },
734         }
735
736         // Run commands with informational output to be logged.
737         for _, command := range commands {
738                 fmt.Fprintln(w, command.label)
739                 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
740                 cmd.Stdout = w
741                 cmd.Stderr = w
742                 if err := cmd.Run(); err != nil {
743                         err = fmt.Errorf("While running command %q: %v", command.cmd, err)
744                         fmt.Fprintln(w, err)
745                         return err
746                 }
747                 fmt.Fprintln(w, "")
748         }
749
750         err = w.Close()
751         if err != nil {
752                 return fmt.Errorf("While closing node-info logs: %v", err)
753         }
754         return nil
755 }
756
757 // LogContainerRecord gets and saves the raw JSON container record from the API server
758 func (runner *ContainerRunner) LogContainerRecord() error {
759         logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
760         if !logged && err == nil {
761                 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
762         }
763         return err
764 }
765
766 // LogNodeRecord logs arvados#node record corresponding to the current host.
767 func (runner *ContainerRunner) LogNodeRecord() error {
768         hostname := os.Getenv("SLURMD_NODENAME")
769         if hostname == "" {
770                 hostname, _ = os.Hostname()
771         }
772         _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
773                 // The "info" field has admin-only info when obtained
774                 // with a privileged token, and should not be logged.
775                 node, ok := resp.(map[string]interface{})
776                 if ok {
777                         delete(node, "info")
778                 }
779         })
780         return err
781 }
782
783 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
784         w := &ArvLogWriter{
785                 ArvClient:     runner.ArvClient,
786                 UUID:          runner.Container.UUID,
787                 loggingStream: label,
788                 writeCloser:   runner.LogCollection.Open(label + ".json"),
789         }
790
791         reader, err := runner.ArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
792         if err != nil {
793                 return false, fmt.Errorf("error getting %s record: %v", label, err)
794         }
795         defer reader.Close()
796
797         dec := json.NewDecoder(reader)
798         dec.UseNumber()
799         var resp map[string]interface{}
800         if err = dec.Decode(&resp); err != nil {
801                 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
802         }
803         items, ok := resp["items"].([]interface{})
804         if !ok {
805                 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
806         } else if len(items) < 1 {
807                 return false, nil
808         }
809         if munge != nil {
810                 munge(items[0])
811         }
812         // Re-encode it using indentation to improve readability
813         enc := json.NewEncoder(w)
814         enc.SetIndent("", "    ")
815         if err = enc.Encode(items[0]); err != nil {
816                 return false, fmt.Errorf("error logging %s record: %v", label, err)
817         }
818         err = w.Close()
819         if err != nil {
820                 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
821         }
822         return true, nil
823 }
824
825 // AttachStreams connects the docker container stdin, stdout and stderr logs
826 // to the Arvados logger which logs to Keep and the API server logs table.
827 func (runner *ContainerRunner) AttachStreams() (err error) {
828
829         runner.CrunchLog.Print("Attaching container streams")
830
831         // If stdin mount is provided, attach it to the docker container
832         var stdinRdr arvados.File
833         var stdinJson []byte
834         if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
835                 if stdinMnt.Kind == "collection" {
836                         var stdinColl arvados.Collection
837                         collId := stdinMnt.UUID
838                         if collId == "" {
839                                 collId = stdinMnt.PortableDataHash
840                         }
841                         err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
842                         if err != nil {
843                                 return fmt.Errorf("While getting stding collection: %v", err)
844                         }
845
846                         stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
847                         if os.IsNotExist(err) {
848                                 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
849                         } else if err != nil {
850                                 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
851                         }
852                 } else if stdinMnt.Kind == "json" {
853                         stdinJson, err = json.Marshal(stdinMnt.Content)
854                         if err != nil {
855                                 return fmt.Errorf("While encoding stdin json data: %v", err)
856                         }
857                 }
858         }
859
860         stdinUsed := stdinRdr != nil || len(stdinJson) != 0
861         response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
862                 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
863         if err != nil {
864                 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
865         }
866
867         runner.loggingDone = make(chan bool)
868
869         if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
870                 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
871                 if err != nil {
872                         return err
873                 }
874                 runner.Stdout = stdoutFile
875         } else {
876                 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
877         }
878
879         if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
880                 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
881                 if err != nil {
882                         return err
883                 }
884                 runner.Stderr = stderrFile
885         } else {
886                 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
887         }
888
889         if stdinRdr != nil {
890                 go func() {
891                         _, err := io.Copy(response.Conn, stdinRdr)
892                         if err != nil {
893                                 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
894                                 runner.stop()
895                         }
896                         stdinRdr.Close()
897                         response.CloseWrite()
898                 }()
899         } else if len(stdinJson) != 0 {
900                 go func() {
901                         _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
902                         if err != nil {
903                                 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
904                                 runner.stop()
905                         }
906                         response.CloseWrite()
907                 }()
908         }
909
910         go runner.ProcessDockerAttach(response.Reader)
911
912         return nil
913 }
914
915 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
916         stdoutPath := mntPath[len(runner.Container.OutputPath):]
917         index := strings.LastIndex(stdoutPath, "/")
918         if index > 0 {
919                 subdirs := stdoutPath[:index]
920                 if subdirs != "" {
921                         st, err := os.Stat(runner.HostOutputDir)
922                         if err != nil {
923                                 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
924                         }
925                         stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
926                         err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
927                         if err != nil {
928                                 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
929                         }
930                 }
931         }
932         stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
933         if err != nil {
934                 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
935         }
936
937         return stdoutFile, nil
938 }
939
940 // CreateContainer creates the docker container.
941 func (runner *ContainerRunner) CreateContainer() error {
942         runner.CrunchLog.Print("Creating Docker container")
943
944         runner.ContainerConfig.Cmd = runner.Container.Command
945         if runner.Container.Cwd != "." {
946                 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
947         }
948
949         for k, v := range runner.Container.Environment {
950                 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
951         }
952
953         runner.ContainerConfig.Volumes = runner.Volumes
954
955         maxRAM := int64(runner.Container.RuntimeConstraints.RAM)
956         runner.HostConfig = dockercontainer.HostConfig{
957                 Binds: runner.Binds,
958                 LogConfig: dockercontainer.LogConfig{
959                         Type: "none",
960                 },
961                 Resources: dockercontainer.Resources{
962                         CgroupParent: runner.setCgroupParent,
963                         NanoCPUs:     int64(runner.Container.RuntimeConstraints.VCPUs) * 1000000000,
964                         Memory:       maxRAM, // RAM
965                         MemorySwap:   maxRAM, // RAM+swap
966                         KernelMemory: maxRAM, // kernel portion
967                 },
968         }
969
970         if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
971                 tok, err := runner.ContainerToken()
972                 if err != nil {
973                         return err
974                 }
975                 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
976                         "ARVADOS_API_TOKEN="+tok,
977                         "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
978                         "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
979                 )
980                 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
981         } else {
982                 if runner.enableNetwork == "always" {
983                         runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
984                 } else {
985                         runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
986                 }
987         }
988
989         _, stdinUsed := runner.Container.Mounts["stdin"]
990         runner.ContainerConfig.OpenStdin = stdinUsed
991         runner.ContainerConfig.StdinOnce = stdinUsed
992         runner.ContainerConfig.AttachStdin = stdinUsed
993         runner.ContainerConfig.AttachStdout = true
994         runner.ContainerConfig.AttachStderr = true
995
996         createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
997         if err != nil {
998                 return fmt.Errorf("While creating container: %v", err)
999         }
1000
1001         runner.ContainerID = createdBody.ID
1002
1003         return runner.AttachStreams()
1004 }
1005
1006 // StartContainer starts the docker container created by CreateContainer.
1007 func (runner *ContainerRunner) StartContainer() error {
1008         runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
1009         runner.cStateLock.Lock()
1010         defer runner.cStateLock.Unlock()
1011         if runner.cCancelled {
1012                 return ErrCancelled
1013         }
1014         err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
1015                 dockertypes.ContainerStartOptions{})
1016         if err != nil {
1017                 var advice string
1018                 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
1019                         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])
1020                 }
1021                 return fmt.Errorf("could not start container: %v%s", err, advice)
1022         }
1023         return nil
1024 }
1025
1026 // WaitFinish waits for the container to terminate, capture the exit code, and
1027 // close the stdout/stderr logging.
1028 func (runner *ContainerRunner) WaitFinish() error {
1029         runner.CrunchLog.Print("Waiting for container to finish")
1030
1031         waitOk, waitErr := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID, dockercontainer.WaitConditionNotRunning)
1032         arvMountExit := runner.ArvMountExit
1033         for {
1034                 select {
1035                 case waitBody := <-waitOk:
1036                         runner.CrunchLog.Printf("Container exited with code: %v", waitBody.StatusCode)
1037                         code := int(waitBody.StatusCode)
1038                         runner.ExitCode = &code
1039
1040                         // wait for stdout/stderr to complete
1041                         <-runner.loggingDone
1042                         return nil
1043
1044                 case err := <-waitErr:
1045                         return fmt.Errorf("container wait: %v", err)
1046
1047                 case <-arvMountExit:
1048                         runner.CrunchLog.Printf("arv-mount exited while container is still running.  Stopping container.")
1049                         runner.stop()
1050                         // arvMountExit will always be ready now that
1051                         // it's closed, but that doesn't interest us.
1052                         arvMountExit = nil
1053                 }
1054         }
1055 }
1056
1057 var ErrNotInOutputDir = fmt.Errorf("Must point to path within the output directory")
1058
1059 func (runner *ContainerRunner) derefOutputSymlink(path string, startinfo os.FileInfo) (tgt string, readlinktgt string, info os.FileInfo, err error) {
1060         // Follow symlinks if necessary
1061         info = startinfo
1062         tgt = path
1063         readlinktgt = ""
1064         nextlink := path
1065         for followed := 0; info.Mode()&os.ModeSymlink != 0; followed++ {
1066                 if followed >= limitFollowSymlinks {
1067                         // Got stuck in a loop or just a pathological number of links, give up.
1068                         err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
1069                         return
1070                 }
1071
1072                 readlinktgt, err = os.Readlink(nextlink)
1073                 if err != nil {
1074                         return
1075                 }
1076
1077                 tgt = readlinktgt
1078                 if !strings.HasPrefix(tgt, "/") {
1079                         // Relative symlink, resolve it to host path
1080                         tgt = filepath.Join(filepath.Dir(path), tgt)
1081                 }
1082                 if strings.HasPrefix(tgt, runner.Container.OutputPath+"/") && !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
1083                         // Absolute symlink to container output path, adjust it to host output path.
1084                         tgt = filepath.Join(runner.HostOutputDir, tgt[len(runner.Container.OutputPath):])
1085                 }
1086                 if !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
1087                         // After dereferencing, symlink target must either be
1088                         // within output directory, or must point to a
1089                         // collection mount.
1090                         err = ErrNotInOutputDir
1091                         return
1092                 }
1093
1094                 info, err = os.Lstat(tgt)
1095                 if err != nil {
1096                         // tgt
1097                         err = fmt.Errorf("Symlink in output %q points to invalid location %q: %v",
1098                                 path[len(runner.HostOutputDir):], readlinktgt, err)
1099                         return
1100                 }
1101
1102                 nextlink = tgt
1103         }
1104
1105         return
1106 }
1107
1108 var limitFollowSymlinks = 10
1109
1110 // UploadFile uploads files within the output directory, with special handling
1111 // for symlinks. If the symlink leads to a keep mount, copy the manifest text
1112 // from the keep mount into the output manifestText.  Ensure that whether
1113 // symlinks are relative or absolute, every symlink target (even targets that
1114 // are symlinks themselves) must point to a path in either the output directory
1115 // or a collection mount.
1116 //
1117 // Assumes initial value of "path" is absolute, and located within runner.HostOutputDir.
1118 func (runner *ContainerRunner) UploadOutputFile(
1119         path string,
1120         info os.FileInfo,
1121         infoerr error,
1122         binds []string,
1123         walkUpload *WalkUpload,
1124         relocateFrom string,
1125         relocateTo string,
1126         followed int) (manifestText string, err error) {
1127
1128         if infoerr != nil {
1129                 return "", infoerr
1130         }
1131
1132         if info.Mode().IsDir() {
1133                 // if empty, need to create a .keep file
1134                 dir, direrr := os.Open(path)
1135                 if direrr != nil {
1136                         return "", direrr
1137                 }
1138                 defer dir.Close()
1139                 names, eof := dir.Readdirnames(1)
1140                 if len(names) == 0 && eof == io.EOF && path != runner.HostOutputDir {
1141                         containerPath := runner.OutputPath + path[len(runner.HostOutputDir):]
1142                         for _, bind := range binds {
1143                                 mnt := runner.Container.Mounts[bind]
1144                                 // Check if there is a bind for this
1145                                 // directory, in which case assume we don't need .keep
1146                                 if (containerPath == bind || strings.HasPrefix(containerPath, bind+"/")) && mnt.PortableDataHash != "d41d8cd98f00b204e9800998ecf8427e+0" {
1147                                         return
1148                                 }
1149                         }
1150                         outputSuffix := path[len(runner.HostOutputDir)+1:]
1151                         return fmt.Sprintf("./%v d41d8cd98f00b204e9800998ecf8427e+0 0:0:.keep\n", outputSuffix), nil
1152                 }
1153                 return
1154         }
1155
1156         if followed >= limitFollowSymlinks {
1157                 // Got stuck in a loop or just a pathological number of
1158                 // directory links, give up.
1159                 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
1160                 return
1161         }
1162
1163         // "path" is the actual path we are visiting
1164         // "tgt" is the target of "path" (a non-symlink) after following symlinks
1165         // "relocated" is the path in the output manifest where the file should be placed,
1166         // but has HostOutputDir as a prefix.
1167
1168         // The destination path in the output manifest may need to be
1169         // logically relocated to some other path in order to appear
1170         // in the correct location as a result of following a symlink.
1171         // Remove the relocateFrom prefix and replace it with
1172         // relocateTo.
1173         relocated := relocateTo + path[len(relocateFrom):]
1174
1175         tgt, readlinktgt, info, derefErr := runner.derefOutputSymlink(path, info)
1176         if derefErr != nil && derefErr != ErrNotInOutputDir {
1177                 return "", derefErr
1178         }
1179
1180         // go through mounts and try reverse map to collection reference
1181         for _, bind := range binds {
1182                 mnt := runner.Container.Mounts[bind]
1183                 if (tgt == bind || strings.HasPrefix(tgt, bind+"/")) && !mnt.Writable {
1184                         // get path relative to bind
1185                         targetSuffix := tgt[len(bind):]
1186
1187                         // Copy mount and adjust the path to add path relative to the bind
1188                         adjustedMount := mnt
1189                         adjustedMount.Path = filepath.Join(adjustedMount.Path, targetSuffix)
1190
1191                         // Terminates in this keep mount, so add the
1192                         // manifest text at appropriate location.
1193                         outputSuffix := relocated[len(runner.HostOutputDir):]
1194                         manifestText, err = runner.getCollectionManifestForPath(adjustedMount, outputSuffix)
1195                         return
1196                 }
1197         }
1198
1199         // If target is not a collection mount, it must be located within the
1200         // output directory, otherwise it is an error.
1201         if derefErr == ErrNotInOutputDir {
1202                 err = fmt.Errorf("Symlink in output %q points to invalid location %q, must point to path within the output directory.",
1203                         path[len(runner.HostOutputDir):], readlinktgt)
1204                 return
1205         }
1206
1207         if info.Mode().IsRegular() {
1208                 return "", walkUpload.UploadFile(relocated, tgt)
1209         }
1210
1211         if info.Mode().IsDir() {
1212                 // Symlink leads to directory.  Walk() doesn't follow
1213                 // directory symlinks, so we walk the target directory
1214                 // instead.  Within the walk, file paths are relocated
1215                 // so they appear under the original symlink path.
1216                 err = filepath.Walk(tgt, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
1217                         var m string
1218                         m, walkerr = runner.UploadOutputFile(walkpath, walkinfo, walkerr,
1219                                 binds, walkUpload, tgt, relocated, followed+1)
1220                         if walkerr == nil {
1221                                 manifestText = manifestText + m
1222                         }
1223                         return walkerr
1224                 })
1225                 return
1226         }
1227
1228         return
1229 }
1230
1231 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
1232 func (runner *ContainerRunner) CaptureOutput() error {
1233         if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
1234                 // Output may have been set directly by the container, so
1235                 // refresh the container record to check.
1236                 err := runner.ArvClient.Get("containers", runner.Container.UUID,
1237                         nil, &runner.Container)
1238                 if err != nil {
1239                         return err
1240                 }
1241                 if runner.Container.Output != "" {
1242                         // Container output is already set.
1243                         runner.OutputPDH = &runner.Container.Output
1244                         return nil
1245                 }
1246         }
1247
1248         if runner.HostOutputDir == "" {
1249                 return nil
1250         }
1251
1252         _, err := os.Stat(runner.HostOutputDir)
1253         if err != nil {
1254                 return fmt.Errorf("While checking host output path: %v", err)
1255         }
1256
1257         // Pre-populate output from the configured mount points
1258         var binds []string
1259         for bind, mnt := range runner.Container.Mounts {
1260                 if mnt.Kind == "collection" {
1261                         binds = append(binds, bind)
1262                 }
1263         }
1264         sort.Strings(binds)
1265
1266         var manifestText string
1267
1268         collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
1269         _, err = os.Stat(collectionMetafile)
1270         if err != nil {
1271                 // Regular directory
1272
1273                 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
1274                 walkUpload := cw.BeginUpload(runner.HostOutputDir, runner.CrunchLog.Logger)
1275
1276                 var m string
1277                 err = filepath.Walk(runner.HostOutputDir, func(path string, info os.FileInfo, err error) error {
1278                         m, err = runner.UploadOutputFile(path, info, err, binds, walkUpload, "", "", 0)
1279                         if err == nil {
1280                                 manifestText = manifestText + m
1281                         }
1282                         return err
1283                 })
1284
1285                 cw.EndUpload(walkUpload)
1286
1287                 if err != nil {
1288                         return fmt.Errorf("While uploading output files: %v", err)
1289                 }
1290
1291                 m, err = cw.ManifestText()
1292                 manifestText = manifestText + m
1293                 if err != nil {
1294                         return fmt.Errorf("While uploading output files: %v", err)
1295                 }
1296         } else {
1297                 // FUSE mount directory
1298                 file, openerr := os.Open(collectionMetafile)
1299                 if openerr != nil {
1300                         return fmt.Errorf("While opening FUSE metafile: %v", err)
1301                 }
1302                 defer file.Close()
1303
1304                 var rec arvados.Collection
1305                 err = json.NewDecoder(file).Decode(&rec)
1306                 if err != nil {
1307                         return fmt.Errorf("While reading FUSE metafile: %v", err)
1308                 }
1309                 manifestText = rec.ManifestText
1310         }
1311
1312         for _, bind := range binds {
1313                 mnt := runner.Container.Mounts[bind]
1314
1315                 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
1316
1317                 if bindSuffix == bind || len(bindSuffix) <= 0 {
1318                         // either does not start with OutputPath or is OutputPath itself
1319                         continue
1320                 }
1321
1322                 if mnt.ExcludeFromOutput == true || mnt.Writable {
1323                         continue
1324                 }
1325
1326                 // append to manifest_text
1327                 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
1328                 if err != nil {
1329                         return err
1330                 }
1331
1332                 manifestText = manifestText + m
1333         }
1334
1335         // Save output
1336         var response arvados.Collection
1337         manifest := manifest.Manifest{Text: manifestText}
1338         manifestText = manifest.Extract(".", ".").Text
1339         err = runner.ArvClient.Create("collections",
1340                 arvadosclient.Dict{
1341                         "ensure_unique_name": true,
1342                         "collection": arvadosclient.Dict{
1343                                 "is_trashed":    true,
1344                                 "name":          "output for " + runner.Container.UUID,
1345                                 "manifest_text": manifestText}},
1346                 &response)
1347         if err != nil {
1348                 return fmt.Errorf("While creating output collection: %v", err)
1349         }
1350         runner.OutputPDH = &response.PortableDataHash
1351         return nil
1352 }
1353
1354 var outputCollections = make(map[string]arvados.Collection)
1355
1356 // Fetch the collection for the mnt.PortableDataHash
1357 // Return the manifest_text fragment corresponding to the specified mnt.Path
1358 //  after making any required updates.
1359 //  Ex:
1360 //    If mnt.Path is not specified,
1361 //      return the entire manifest_text after replacing any "." with bindSuffix
1362 //    If mnt.Path corresponds to one stream,
1363 //      return the manifest_text for that stream after replacing that stream name with bindSuffix
1364 //    Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1365 //      for that stream after replacing stream name with bindSuffix minus the last word
1366 //      and the file name with last word of the bindSuffix
1367 //  Allowed path examples:
1368 //    "path":"/"
1369 //    "path":"/subdir1"
1370 //    "path":"/subdir1/subdir2"
1371 //    "path":"/subdir/filename" etc
1372 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1373         collection := outputCollections[mnt.PortableDataHash]
1374         if collection.PortableDataHash == "" {
1375                 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1376                 if err != nil {
1377                         return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1378                 }
1379                 outputCollections[mnt.PortableDataHash] = collection
1380         }
1381
1382         if collection.ManifestText == "" {
1383                 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1384                 return "", nil
1385         }
1386
1387         mft := manifest.Manifest{Text: collection.ManifestText}
1388         extracted := mft.Extract(mnt.Path, bindSuffix)
1389         if extracted.Err != nil {
1390                 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1391         }
1392         return extracted.Text, nil
1393 }
1394
1395 func (runner *ContainerRunner) CleanupDirs() {
1396         if runner.ArvMount != nil {
1397                 var delay int64 = 8
1398                 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1399                 umount.Stdout = runner.CrunchLog
1400                 umount.Stderr = runner.CrunchLog
1401                 runner.CrunchLog.Printf("Running %v", umount.Args)
1402                 umnterr := umount.Start()
1403
1404                 if umnterr != nil {
1405                         runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1406                 } else {
1407                         // If arv-mount --unmount gets stuck for any reason, we
1408                         // don't want to wait for it forever.  Do Wait() in a goroutine
1409                         // so it doesn't block crunch-run.
1410                         umountExit := make(chan error)
1411                         go func() {
1412                                 mnterr := umount.Wait()
1413                                 if mnterr != nil {
1414                                         runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1415                                 }
1416                                 umountExit <- mnterr
1417                         }()
1418
1419                         for again := true; again; {
1420                                 again = false
1421                                 select {
1422                                 case <-umountExit:
1423                                         umount = nil
1424                                         again = true
1425                                 case <-runner.ArvMountExit:
1426                                         break
1427                                 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1428                                         runner.CrunchLog.Printf("Timed out waiting for unmount")
1429                                         if umount != nil {
1430                                                 umount.Process.Kill()
1431                                         }
1432                                         runner.ArvMount.Process.Kill()
1433                                 }
1434                         }
1435                 }
1436         }
1437
1438         if runner.ArvMountPoint != "" {
1439                 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1440                         runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1441                 }
1442         }
1443
1444         if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1445                 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1446         }
1447 }
1448
1449 // CommitLogs posts the collection containing the final container logs.
1450 func (runner *ContainerRunner) CommitLogs() error {
1451         runner.CrunchLog.Print(runner.finalState)
1452
1453         if runner.arvMountLog != nil {
1454                 runner.arvMountLog.Close()
1455         }
1456         runner.CrunchLog.Close()
1457
1458         // Closing CrunchLog above allows them to be committed to Keep at this
1459         // point, but re-open crunch log with ArvClient in case there are any
1460         // other further errors (such as failing to write the log to Keep!)
1461         // while shutting down
1462         runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1463                 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1464         runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1465
1466         if runner.LogsPDH != nil {
1467                 // If we have already assigned something to LogsPDH,
1468                 // we must be closing the re-opened log, which won't
1469                 // end up getting attached to the container record and
1470                 // therefore doesn't need to be saved as a collection
1471                 // -- it exists only to send logs to other channels.
1472                 return nil
1473         }
1474
1475         mt, err := runner.LogCollection.ManifestText()
1476         if err != nil {
1477                 return fmt.Errorf("While creating log manifest: %v", err)
1478         }
1479
1480         var response arvados.Collection
1481         err = runner.ArvClient.Create("collections",
1482                 arvadosclient.Dict{
1483                         "ensure_unique_name": true,
1484                         "collection": arvadosclient.Dict{
1485                                 "is_trashed":    true,
1486                                 "name":          "logs for " + runner.Container.UUID,
1487                                 "manifest_text": mt}},
1488                 &response)
1489         if err != nil {
1490                 return fmt.Errorf("While creating log collection: %v", err)
1491         }
1492         runner.LogsPDH = &response.PortableDataHash
1493         return nil
1494 }
1495
1496 // UpdateContainerRunning updates the container state to "Running"
1497 func (runner *ContainerRunner) UpdateContainerRunning() error {
1498         runner.cStateLock.Lock()
1499         defer runner.cStateLock.Unlock()
1500         if runner.cCancelled {
1501                 return ErrCancelled
1502         }
1503         return runner.ArvClient.Update("containers", runner.Container.UUID,
1504                 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1505 }
1506
1507 // ContainerToken returns the api_token the container (and any
1508 // arv-mount processes) are allowed to use.
1509 func (runner *ContainerRunner) ContainerToken() (string, error) {
1510         if runner.token != "" {
1511                 return runner.token, nil
1512         }
1513
1514         var auth arvados.APIClientAuthorization
1515         err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1516         if err != nil {
1517                 return "", err
1518         }
1519         runner.token = auth.APIToken
1520         return runner.token, nil
1521 }
1522
1523 // UpdateContainerComplete updates the container record state on API
1524 // server to "Complete" or "Cancelled"
1525 func (runner *ContainerRunner) UpdateContainerFinal() error {
1526         update := arvadosclient.Dict{}
1527         update["state"] = runner.finalState
1528         if runner.LogsPDH != nil {
1529                 update["log"] = *runner.LogsPDH
1530         }
1531         if runner.finalState == "Complete" {
1532                 if runner.ExitCode != nil {
1533                         update["exit_code"] = *runner.ExitCode
1534                 }
1535                 if runner.OutputPDH != nil {
1536                         update["output"] = *runner.OutputPDH
1537                 }
1538         }
1539         return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1540 }
1541
1542 // IsCancelled returns the value of Cancelled, with goroutine safety.
1543 func (runner *ContainerRunner) IsCancelled() bool {
1544         runner.cStateLock.Lock()
1545         defer runner.cStateLock.Unlock()
1546         return runner.cCancelled
1547 }
1548
1549 // NewArvLogWriter creates an ArvLogWriter
1550 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1551         return &ArvLogWriter{
1552                 ArvClient:     runner.ArvClient,
1553                 UUID:          runner.Container.UUID,
1554                 loggingStream: name,
1555                 writeCloser:   runner.LogCollection.Open(name + ".txt")}
1556 }
1557
1558 // Run the full container lifecycle.
1559 func (runner *ContainerRunner) Run() (err error) {
1560         runner.CrunchLog.Printf("crunch-run %s started", version)
1561         runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1562
1563         hostname, hosterr := os.Hostname()
1564         if hosterr != nil {
1565                 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1566         } else {
1567                 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1568         }
1569
1570         runner.finalState = "Queued"
1571
1572         defer func() {
1573                 runner.stopSignals()
1574                 runner.CleanupDirs()
1575
1576                 runner.CrunchLog.Printf("crunch-run finished")
1577                 runner.CrunchLog.Close()
1578         }()
1579
1580         defer func() {
1581                 // checkErr prints e (unless it's nil) and sets err to
1582                 // e (unless err is already non-nil). Thus, if err
1583                 // hasn't already been assigned when Run() returns,
1584                 // this cleanup func will cause Run() to return the
1585                 // first non-nil error that is passed to checkErr().
1586                 checkErr := func(e error) {
1587                         if e == nil {
1588                                 return
1589                         }
1590                         runner.CrunchLog.Print(e)
1591                         if err == nil {
1592                                 err = e
1593                         }
1594                         if runner.finalState == "Complete" {
1595                                 // There was an error in the finalization.
1596                                 runner.finalState = "Cancelled"
1597                         }
1598                 }
1599
1600                 // Log the error encountered in Run(), if any
1601                 checkErr(err)
1602
1603                 if runner.finalState == "Queued" {
1604                         runner.UpdateContainerFinal()
1605                         return
1606                 }
1607
1608                 if runner.IsCancelled() {
1609                         runner.finalState = "Cancelled"
1610                         // but don't return yet -- we still want to
1611                         // capture partial output and write logs
1612                 }
1613
1614                 checkErr(runner.CaptureOutput())
1615                 checkErr(runner.stopHoststat())
1616                 checkErr(runner.CommitLogs())
1617                 checkErr(runner.UpdateContainerFinal())
1618         }()
1619
1620         err = runner.fetchContainerRecord()
1621         if err != nil {
1622                 return
1623         }
1624         runner.setupSignals()
1625         runner.startHoststat()
1626
1627         // check for and/or load image
1628         err = runner.LoadImage()
1629         if err != nil {
1630                 if !runner.checkBrokenNode(err) {
1631                         // Failed to load image but not due to a "broken node"
1632                         // condition, probably user error.
1633                         runner.finalState = "Cancelled"
1634                 }
1635                 err = fmt.Errorf("While loading container image: %v", err)
1636                 return
1637         }
1638
1639         // set up FUSE mount and binds
1640         err = runner.SetupMounts()
1641         if err != nil {
1642                 runner.finalState = "Cancelled"
1643                 err = fmt.Errorf("While setting up mounts: %v", err)
1644                 return
1645         }
1646
1647         err = runner.CreateContainer()
1648         if err != nil {
1649                 return
1650         }
1651         err = runner.LogHostInfo()
1652         if err != nil {
1653                 return
1654         }
1655         err = runner.LogNodeRecord()
1656         if err != nil {
1657                 return
1658         }
1659         err = runner.LogContainerRecord()
1660         if err != nil {
1661                 return
1662         }
1663
1664         if runner.IsCancelled() {
1665                 return
1666         }
1667
1668         err = runner.UpdateContainerRunning()
1669         if err != nil {
1670                 return
1671         }
1672         runner.finalState = "Cancelled"
1673
1674         runner.startCrunchstat()
1675
1676         err = runner.StartContainer()
1677         if err != nil {
1678                 runner.checkBrokenNode(err)
1679                 return
1680         }
1681
1682         err = runner.WaitFinish()
1683         if err == nil && !runner.IsCancelled() {
1684                 runner.finalState = "Complete"
1685         }
1686         return
1687 }
1688
1689 // Fetch the current container record (uuid = runner.Container.UUID)
1690 // into runner.Container.
1691 func (runner *ContainerRunner) fetchContainerRecord() error {
1692         reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1693         if err != nil {
1694                 return fmt.Errorf("error fetching container record: %v", err)
1695         }
1696         defer reader.Close()
1697
1698         dec := json.NewDecoder(reader)
1699         dec.UseNumber()
1700         err = dec.Decode(&runner.Container)
1701         if err != nil {
1702                 return fmt.Errorf("error decoding container record: %v", err)
1703         }
1704         return nil
1705 }
1706
1707 // NewContainerRunner creates a new container runner.
1708 func NewContainerRunner(api IArvadosClient,
1709         kc IKeepClient,
1710         docker ThinDockerClient,
1711         containerUUID string) *ContainerRunner {
1712
1713         cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1714         cr.NewLogWriter = cr.NewArvLogWriter
1715         cr.RunArvMount = cr.ArvMountCmd
1716         cr.MkTempDir = ioutil.TempDir
1717         cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1718         cr.Container.UUID = containerUUID
1719         cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1720         cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1721
1722         loadLogThrottleParams(api)
1723
1724         return cr
1725 }
1726
1727 func main() {
1728         statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1729         cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1730         cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1731         cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1732         caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1733         enableNetwork := flag.String("container-enable-networking", "default",
1734                 `Specify if networking should be enabled for container.  One of 'default', 'always':
1735         default: only enable networking if container requests it.
1736         always:  containers always have networking enabled
1737         `)
1738         networkMode := flag.String("container-network-mode", "default",
1739                 `Set networking mode for container.  Corresponds to Docker network mode (--net).
1740         `)
1741         memprofile := flag.String("memprofile", "", "write memory profile to `file` after running container")
1742         getVersion := flag.Bool("version", false, "Print version information and exit.")
1743         flag.Parse()
1744
1745         // Print version information if requested
1746         if *getVersion {
1747                 fmt.Printf("crunch-run %s\n", version)
1748                 return
1749         }
1750
1751         log.Printf("crunch-run %s started", version)
1752
1753         containerId := flag.Arg(0)
1754
1755         if *caCertsPath != "" {
1756                 arvadosclient.CertFiles = []string{*caCertsPath}
1757         }
1758
1759         api, err := arvadosclient.MakeArvadosClient()
1760         if err != nil {
1761                 log.Fatalf("%s: %v", containerId, err)
1762         }
1763         api.Retries = 8
1764
1765         kc, kcerr := keepclient.MakeKeepClient(api)
1766         if kcerr != nil {
1767                 log.Fatalf("%s: %v", containerId, kcerr)
1768         }
1769         kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1770         kc.Retries = 4
1771
1772         // API version 1.21 corresponds to Docker 1.9, which is currently the
1773         // minimum version we want to support.
1774         docker, dockererr := dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1775
1776         cr := NewContainerRunner(api, kc, docker, containerId)
1777         if dockererr != nil {
1778                 cr.CrunchLog.Printf("%s: %v", containerId, dockererr)
1779                 cr.checkBrokenNode(dockererr)
1780                 cr.CrunchLog.Close()
1781                 os.Exit(1)
1782         }
1783
1784         parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerId+".")
1785         if tmperr != nil {
1786                 log.Fatalf("%s: %v", containerId, tmperr)
1787         }
1788
1789         cr.parentTemp = parentTemp
1790         cr.statInterval = *statInterval
1791         cr.cgroupRoot = *cgroupRoot
1792         cr.expectCgroupParent = *cgroupParent
1793         cr.enableNetwork = *enableNetwork
1794         cr.networkMode = *networkMode
1795         if *cgroupParentSubsystem != "" {
1796                 p := findCgroup(*cgroupParentSubsystem)
1797                 cr.setCgroupParent = p
1798                 cr.expectCgroupParent = p
1799         }
1800
1801         runerr := cr.Run()
1802
1803         if *memprofile != "" {
1804                 f, err := os.Create(*memprofile)
1805                 if err != nil {
1806                         log.Printf("could not create memory profile: ", err)
1807                 }
1808                 runtime.GC() // get up-to-date statistics
1809                 if err := pprof.WriteHeapProfile(f); err != nil {
1810                         log.Printf("could not write memory profile: ", err)
1811                 }
1812                 closeerr := f.Close()
1813                 if closeerr != nil {
1814                         log.Printf("closing memprofile file: ", err)
1815                 }
1816         }
1817
1818         if runerr != nil {
1819                 log.Fatalf("%s: %v", containerId, runerr)
1820         }
1821 }