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