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