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