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