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