Merge branch 'master' of git.curoverse.com:arvados into 11876-r-sdk
[arvados.git] / services / crunch-run / crunchrun.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package main
6
7 import (
8         "bytes"
9         "context"
10         "encoding/json"
11         "errors"
12         "flag"
13         "fmt"
14         "io"
15         "io/ioutil"
16         "log"
17         "os"
18         "os/exec"
19         "os/signal"
20         "path"
21         "path/filepath"
22         "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 // LogHostInfo logs info about the current host, for debugging and
664 // accounting purposes. Although it's logged as "node-info", this is
665 // about the environment where crunch-run is actually running, which
666 // might differ from what's described in the node record (see
667 // LogNodeRecord).
668 func (runner *ContainerRunner) LogHostInfo() (err error) {
669         w := runner.NewLogWriter("node-info")
670
671         commands := []infoCommand{
672                 {
673                         label: "Host Information",
674                         cmd:   []string{"uname", "-a"},
675                 },
676                 {
677                         label: "CPU Information",
678                         cmd:   []string{"cat", "/proc/cpuinfo"},
679                 },
680                 {
681                         label: "Memory Information",
682                         cmd:   []string{"cat", "/proc/meminfo"},
683                 },
684                 {
685                         label: "Disk Space",
686                         cmd:   []string{"df", "-m", "/", os.TempDir()},
687                 },
688                 {
689                         label: "Disk INodes",
690                         cmd:   []string{"df", "-i", "/", os.TempDir()},
691                 },
692         }
693
694         // Run commands with informational output to be logged.
695         for _, command := range commands {
696                 fmt.Fprintln(w, command.label)
697                 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
698                 cmd.Stdout = w
699                 cmd.Stderr = w
700                 if err := cmd.Run(); err != nil {
701                         err = fmt.Errorf("While running command %q: %v", command.cmd, err)
702                         fmt.Fprintln(w, err)
703                         return err
704                 }
705                 fmt.Fprintln(w, "")
706         }
707
708         err = w.Close()
709         if err != nil {
710                 return fmt.Errorf("While closing node-info logs: %v", err)
711         }
712         return nil
713 }
714
715 // LogContainerRecord gets and saves the raw JSON container record from the API server
716 func (runner *ContainerRunner) LogContainerRecord() error {
717         logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
718         if !logged && err == nil {
719                 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
720         }
721         return err
722 }
723
724 // LogNodeRecord logs arvados#node record corresponding to the current host.
725 func (runner *ContainerRunner) LogNodeRecord() error {
726         hostname := os.Getenv("SLURMD_NODENAME")
727         if hostname == "" {
728                 hostname, _ = os.Hostname()
729         }
730         _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
731                 // The "info" field has admin-only info when obtained
732                 // with a privileged token, and should not be logged.
733                 node, ok := resp.(map[string]interface{})
734                 if ok {
735                         delete(node, "info")
736                 }
737         })
738         return err
739 }
740
741 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
742         w := &ArvLogWriter{
743                 ArvClient:     runner.ArvClient,
744                 UUID:          runner.Container.UUID,
745                 loggingStream: label,
746                 writeCloser:   runner.LogCollection.Open(label + ".json"),
747         }
748
749         reader, err := runner.ArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
750         if err != nil {
751                 return false, fmt.Errorf("error getting %s record: %v", label, err)
752         }
753         defer reader.Close()
754
755         dec := json.NewDecoder(reader)
756         dec.UseNumber()
757         var resp map[string]interface{}
758         if err = dec.Decode(&resp); err != nil {
759                 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
760         }
761         items, ok := resp["items"].([]interface{})
762         if !ok {
763                 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
764         } else if len(items) < 1 {
765                 return false, nil
766         }
767         if munge != nil {
768                 munge(items[0])
769         }
770         // Re-encode it using indentation to improve readability
771         enc := json.NewEncoder(w)
772         enc.SetIndent("", "    ")
773         if err = enc.Encode(items[0]); err != nil {
774                 return false, fmt.Errorf("error logging %s record: %v", label, err)
775         }
776         err = w.Close()
777         if err != nil {
778                 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
779         }
780         return true, nil
781 }
782
783 // AttachStreams connects the docker container stdin, stdout and stderr logs
784 // to the Arvados logger which logs to Keep and the API server logs table.
785 func (runner *ContainerRunner) AttachStreams() (err error) {
786
787         runner.CrunchLog.Print("Attaching container streams")
788
789         // If stdin mount is provided, attach it to the docker container
790         var stdinRdr arvados.File
791         var stdinJson []byte
792         if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
793                 if stdinMnt.Kind == "collection" {
794                         var stdinColl arvados.Collection
795                         collId := stdinMnt.UUID
796                         if collId == "" {
797                                 collId = stdinMnt.PortableDataHash
798                         }
799                         err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
800                         if err != nil {
801                                 return fmt.Errorf("While getting stding collection: %v", err)
802                         }
803
804                         stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
805                         if os.IsNotExist(err) {
806                                 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
807                         } else if err != nil {
808                                 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
809                         }
810                 } else if stdinMnt.Kind == "json" {
811                         stdinJson, err = json.Marshal(stdinMnt.Content)
812                         if err != nil {
813                                 return fmt.Errorf("While encoding stdin json data: %v", err)
814                         }
815                 }
816         }
817
818         stdinUsed := stdinRdr != nil || len(stdinJson) != 0
819         response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
820                 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
821         if err != nil {
822                 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
823         }
824
825         runner.loggingDone = make(chan bool)
826
827         if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
828                 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
829                 if err != nil {
830                         return err
831                 }
832                 runner.Stdout = stdoutFile
833         } else {
834                 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
835         }
836
837         if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
838                 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
839                 if err != nil {
840                         return err
841                 }
842                 runner.Stderr = stderrFile
843         } else {
844                 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
845         }
846
847         if stdinRdr != nil {
848                 go func() {
849                         _, err := io.Copy(response.Conn, stdinRdr)
850                         if err != nil {
851                                 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
852                                 runner.stop()
853                         }
854                         stdinRdr.Close()
855                         response.CloseWrite()
856                 }()
857         } else if len(stdinJson) != 0 {
858                 go func() {
859                         _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
860                         if err != nil {
861                                 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
862                                 runner.stop()
863                         }
864                         response.CloseWrite()
865                 }()
866         }
867
868         go runner.ProcessDockerAttach(response.Reader)
869
870         return nil
871 }
872
873 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
874         stdoutPath := mntPath[len(runner.Container.OutputPath):]
875         index := strings.LastIndex(stdoutPath, "/")
876         if index > 0 {
877                 subdirs := stdoutPath[:index]
878                 if subdirs != "" {
879                         st, err := os.Stat(runner.HostOutputDir)
880                         if err != nil {
881                                 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
882                         }
883                         stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
884                         err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
885                         if err != nil {
886                                 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
887                         }
888                 }
889         }
890         stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
891         if err != nil {
892                 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
893         }
894
895         return stdoutFile, nil
896 }
897
898 // CreateContainer creates the docker container.
899 func (runner *ContainerRunner) CreateContainer() error {
900         runner.CrunchLog.Print("Creating Docker container")
901
902         runner.ContainerConfig.Cmd = runner.Container.Command
903         if runner.Container.Cwd != "." {
904                 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
905         }
906
907         for k, v := range runner.Container.Environment {
908                 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
909         }
910
911         runner.ContainerConfig.Volumes = runner.Volumes
912
913         runner.HostConfig = dockercontainer.HostConfig{
914                 Binds: runner.Binds,
915                 LogConfig: dockercontainer.LogConfig{
916                         Type: "none",
917                 },
918                 Resources: dockercontainer.Resources{
919                         CgroupParent: runner.setCgroupParent,
920                 },
921         }
922
923         if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
924                 tok, err := runner.ContainerToken()
925                 if err != nil {
926                         return err
927                 }
928                 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
929                         "ARVADOS_API_TOKEN="+tok,
930                         "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
931                         "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
932                 )
933                 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
934         } else {
935                 if runner.enableNetwork == "always" {
936                         runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
937                 } else {
938                         runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
939                 }
940         }
941
942         _, stdinUsed := runner.Container.Mounts["stdin"]
943         runner.ContainerConfig.OpenStdin = stdinUsed
944         runner.ContainerConfig.StdinOnce = stdinUsed
945         runner.ContainerConfig.AttachStdin = stdinUsed
946         runner.ContainerConfig.AttachStdout = true
947         runner.ContainerConfig.AttachStderr = true
948
949         createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
950         if err != nil {
951                 return fmt.Errorf("While creating container: %v", err)
952         }
953
954         runner.ContainerID = createdBody.ID
955
956         return runner.AttachStreams()
957 }
958
959 // StartContainer starts the docker container created by CreateContainer.
960 func (runner *ContainerRunner) StartContainer() error {
961         runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
962         runner.cStateLock.Lock()
963         defer runner.cStateLock.Unlock()
964         if runner.cCancelled {
965                 return ErrCancelled
966         }
967         err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
968                 dockertypes.ContainerStartOptions{})
969         if err != nil {
970                 var advice string
971                 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
972                         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])
973                 }
974                 return fmt.Errorf("could not start container: %v%s", err, advice)
975         }
976         runner.cStarted = true
977         return nil
978 }
979
980 // WaitFinish waits for the container to terminate, capture the exit code, and
981 // close the stdout/stderr logging.
982 func (runner *ContainerRunner) WaitFinish() (err error) {
983         runner.CrunchLog.Print("Waiting for container to finish")
984
985         waitOk, waitErr := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID, "not-running")
986
987         go func() {
988                 <-runner.ArvMountExit
989                 if runner.cStarted {
990                         runner.CrunchLog.Printf("arv-mount exited while container is still running.  Stopping container.")
991                         runner.stop()
992                 }
993         }()
994
995         var waitBody dockercontainer.ContainerWaitOKBody
996         select {
997         case waitBody = <-waitOk:
998         case err = <-waitErr:
999         }
1000
1001         // Container isn't running any more
1002         runner.cStarted = false
1003
1004         if err != nil {
1005                 return fmt.Errorf("container wait: %v", err)
1006         }
1007
1008         runner.CrunchLog.Printf("Container exited with code: %v", waitBody.StatusCode)
1009         code := int(waitBody.StatusCode)
1010         runner.ExitCode = &code
1011
1012         // wait for stdout/stderr to complete
1013         <-runner.loggingDone
1014
1015         return nil
1016 }
1017
1018 var ErrNotInOutputDir = fmt.Errorf("Must point to path within the output directory")
1019
1020 func (runner *ContainerRunner) derefOutputSymlink(path string, startinfo os.FileInfo) (tgt string, readlinktgt string, info os.FileInfo, err error) {
1021         // Follow symlinks if necessary
1022         info = startinfo
1023         tgt = path
1024         readlinktgt = ""
1025         nextlink := path
1026         for followed := 0; info.Mode()&os.ModeSymlink != 0; followed++ {
1027                 if followed >= limitFollowSymlinks {
1028                         // Got stuck in a loop or just a pathological number of links, give up.
1029                         err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
1030                         return
1031                 }
1032
1033                 readlinktgt, err = os.Readlink(nextlink)
1034                 if err != nil {
1035                         return
1036                 }
1037
1038                 tgt = readlinktgt
1039                 if !strings.HasPrefix(tgt, "/") {
1040                         // Relative symlink, resolve it to host path
1041                         tgt = filepath.Join(filepath.Dir(path), tgt)
1042                 }
1043                 if strings.HasPrefix(tgt, runner.Container.OutputPath+"/") && !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
1044                         // Absolute symlink to container output path, adjust it to host output path.
1045                         tgt = filepath.Join(runner.HostOutputDir, tgt[len(runner.Container.OutputPath):])
1046                 }
1047                 if !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
1048                         // After dereferencing, symlink target must either be
1049                         // within output directory, or must point to a
1050                         // collection mount.
1051                         err = ErrNotInOutputDir
1052                         return
1053                 }
1054
1055                 info, err = os.Lstat(tgt)
1056                 if err != nil {
1057                         // tgt
1058                         err = fmt.Errorf("Symlink in output %q points to invalid location %q: %v",
1059                                 path[len(runner.HostOutputDir):], readlinktgt, err)
1060                         return
1061                 }
1062
1063                 nextlink = tgt
1064         }
1065
1066         return
1067 }
1068
1069 var limitFollowSymlinks = 10
1070
1071 // UploadFile uploads files within the output directory, with special handling
1072 // for symlinks. If the symlink leads to a keep mount, copy the manifest text
1073 // from the keep mount into the output manifestText.  Ensure that whether
1074 // symlinks are relative or absolute, every symlink target (even targets that
1075 // are symlinks themselves) must point to a path in either the output directory
1076 // or a collection mount.
1077 //
1078 // Assumes initial value of "path" is absolute, and located within runner.HostOutputDir.
1079 func (runner *ContainerRunner) UploadOutputFile(
1080         path string,
1081         info os.FileInfo,
1082         infoerr error,
1083         binds []string,
1084         walkUpload *WalkUpload,
1085         relocateFrom string,
1086         relocateTo string,
1087         followed int) (manifestText string, err error) {
1088
1089         if infoerr != nil {
1090                 return "", infoerr
1091         }
1092
1093         if info.Mode().IsDir() {
1094                 // if empty, need to create a .keep file
1095                 dir, direrr := os.Open(path)
1096                 if direrr != nil {
1097                         return "", direrr
1098                 }
1099                 defer dir.Close()
1100                 names, eof := dir.Readdirnames(1)
1101                 if len(names) == 0 && eof == io.EOF && path != runner.HostOutputDir {
1102                         containerPath := runner.OutputPath + path[len(runner.HostOutputDir):]
1103                         for _, bind := range binds {
1104                                 mnt := runner.Container.Mounts[bind]
1105                                 // Check if there is a bind for this
1106                                 // directory, in which case assume we don't need .keep
1107                                 if (containerPath == bind || strings.HasPrefix(containerPath, bind+"/")) && mnt.PortableDataHash != "d41d8cd98f00b204e9800998ecf8427e+0" {
1108                                         return
1109                                 }
1110                         }
1111                         outputSuffix := path[len(runner.HostOutputDir)+1:]
1112                         return fmt.Sprintf("./%v d41d8cd98f00b204e9800998ecf8427e+0 0:0:.keep\n", outputSuffix), nil
1113                 }
1114                 return
1115         }
1116
1117         if followed >= limitFollowSymlinks {
1118                 // Got stuck in a loop or just a pathological number of
1119                 // directory links, give up.
1120                 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
1121                 return
1122         }
1123
1124         // "path" is the actual path we are visiting
1125         // "tgt" is the target of "path" (a non-symlink) after following symlinks
1126         // "relocated" is the path in the output manifest where the file should be placed,
1127         // but has HostOutputDir as a prefix.
1128
1129         // The destination path in the output manifest may need to be
1130         // logically relocated to some other path in order to appear
1131         // in the correct location as a result of following a symlink.
1132         // Remove the relocateFrom prefix and replace it with
1133         // relocateTo.
1134         relocated := relocateTo + path[len(relocateFrom):]
1135
1136         tgt, readlinktgt, info, derefErr := runner.derefOutputSymlink(path, info)
1137         if derefErr != nil && derefErr != ErrNotInOutputDir {
1138                 return "", derefErr
1139         }
1140
1141         // go through mounts and try reverse map to collection reference
1142         for _, bind := range binds {
1143                 mnt := runner.Container.Mounts[bind]
1144                 if tgt == bind || strings.HasPrefix(tgt, bind+"/") {
1145                         // get path relative to bind
1146                         targetSuffix := tgt[len(bind):]
1147
1148                         // Copy mount and adjust the path to add path relative to the bind
1149                         adjustedMount := mnt
1150                         adjustedMount.Path = filepath.Join(adjustedMount.Path, targetSuffix)
1151
1152                         // Terminates in this keep mount, so add the
1153                         // manifest text at appropriate location.
1154                         outputSuffix := relocated[len(runner.HostOutputDir):]
1155                         manifestText, err = runner.getCollectionManifestForPath(adjustedMount, outputSuffix)
1156                         return
1157                 }
1158         }
1159
1160         // If target is not a collection mount, it must be located within the
1161         // output directory, otherwise it is an error.
1162         if derefErr == ErrNotInOutputDir {
1163                 err = fmt.Errorf("Symlink in output %q points to invalid location %q, must point to path within the output directory.",
1164                         path[len(runner.HostOutputDir):], readlinktgt)
1165                 return
1166         }
1167
1168         if info.Mode().IsRegular() {
1169                 return "", walkUpload.UploadFile(relocated, tgt)
1170         }
1171
1172         if info.Mode().IsDir() {
1173                 // Symlink leads to directory.  Walk() doesn't follow
1174                 // directory symlinks, so we walk the target directory
1175                 // instead.  Within the walk, file paths are relocated
1176                 // so they appear under the original symlink path.
1177                 err = filepath.Walk(tgt, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
1178                         var m string
1179                         m, walkerr = runner.UploadOutputFile(walkpath, walkinfo, walkerr,
1180                                 binds, walkUpload, tgt, relocated, followed+1)
1181                         if walkerr == nil {
1182                                 manifestText = manifestText + m
1183                         }
1184                         return walkerr
1185                 })
1186                 return
1187         }
1188
1189         return
1190 }
1191
1192 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
1193 func (runner *ContainerRunner) CaptureOutput() error {
1194         if runner.finalState != "Complete" {
1195                 return nil
1196         }
1197
1198         if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
1199                 // Output may have been set directly by the container, so
1200                 // refresh the container record to check.
1201                 err := runner.ArvClient.Get("containers", runner.Container.UUID,
1202                         nil, &runner.Container)
1203                 if err != nil {
1204                         return err
1205                 }
1206                 if runner.Container.Output != "" {
1207                         // Container output is already set.
1208                         runner.OutputPDH = &runner.Container.Output
1209                         return nil
1210                 }
1211         }
1212
1213         if runner.HostOutputDir == "" {
1214                 return nil
1215         }
1216
1217         _, err := os.Stat(runner.HostOutputDir)
1218         if err != nil {
1219                 return fmt.Errorf("While checking host output path: %v", err)
1220         }
1221
1222         // Pre-populate output from the configured mount points
1223         var binds []string
1224         for bind, mnt := range runner.Container.Mounts {
1225                 if mnt.Kind == "collection" {
1226                         binds = append(binds, bind)
1227                 }
1228         }
1229         sort.Strings(binds)
1230
1231         var manifestText string
1232
1233         collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
1234         _, err = os.Stat(collectionMetafile)
1235         if err != nil {
1236                 // Regular directory
1237
1238                 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
1239                 walkUpload := cw.BeginUpload(runner.HostOutputDir, runner.CrunchLog.Logger)
1240
1241                 var m string
1242                 err = filepath.Walk(runner.HostOutputDir, func(path string, info os.FileInfo, err error) error {
1243                         m, err = runner.UploadOutputFile(path, info, err, binds, walkUpload, "", "", 0)
1244                         if err == nil {
1245                                 manifestText = manifestText + m
1246                         }
1247                         return err
1248                 })
1249
1250                 cw.EndUpload(walkUpload)
1251
1252                 if err != nil {
1253                         return fmt.Errorf("While uploading output files: %v", err)
1254                 }
1255
1256                 m, err = cw.ManifestText()
1257                 manifestText = manifestText + m
1258                 if err != nil {
1259                         return fmt.Errorf("While uploading output files: %v", err)
1260                 }
1261         } else {
1262                 // FUSE mount directory
1263                 file, openerr := os.Open(collectionMetafile)
1264                 if openerr != nil {
1265                         return fmt.Errorf("While opening FUSE metafile: %v", err)
1266                 }
1267                 defer file.Close()
1268
1269                 var rec arvados.Collection
1270                 err = json.NewDecoder(file).Decode(&rec)
1271                 if err != nil {
1272                         return fmt.Errorf("While reading FUSE metafile: %v", err)
1273                 }
1274                 manifestText = rec.ManifestText
1275         }
1276
1277         for _, bind := range binds {
1278                 mnt := runner.Container.Mounts[bind]
1279
1280                 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
1281
1282                 if bindSuffix == bind || len(bindSuffix) <= 0 {
1283                         // either does not start with OutputPath or is OutputPath itself
1284                         continue
1285                 }
1286
1287                 if mnt.ExcludeFromOutput == true {
1288                         continue
1289                 }
1290
1291                 // append to manifest_text
1292                 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
1293                 if err != nil {
1294                         return err
1295                 }
1296
1297                 manifestText = manifestText + m
1298         }
1299
1300         // Save output
1301         var response arvados.Collection
1302         manifest := manifest.Manifest{Text: manifestText}
1303         manifestText = manifest.Extract(".", ".").Text
1304         err = runner.ArvClient.Create("collections",
1305                 arvadosclient.Dict{
1306                         "ensure_unique_name": true,
1307                         "collection": arvadosclient.Dict{
1308                                 "is_trashed":    true,
1309                                 "name":          "output for " + runner.Container.UUID,
1310                                 "manifest_text": manifestText}},
1311                 &response)
1312         if err != nil {
1313                 return fmt.Errorf("While creating output collection: %v", err)
1314         }
1315         runner.OutputPDH = &response.PortableDataHash
1316         return nil
1317 }
1318
1319 var outputCollections = make(map[string]arvados.Collection)
1320
1321 // Fetch the collection for the mnt.PortableDataHash
1322 // Return the manifest_text fragment corresponding to the specified mnt.Path
1323 //  after making any required updates.
1324 //  Ex:
1325 //    If mnt.Path is not specified,
1326 //      return the entire manifest_text after replacing any "." with bindSuffix
1327 //    If mnt.Path corresponds to one stream,
1328 //      return the manifest_text for that stream after replacing that stream name with bindSuffix
1329 //    Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1330 //      for that stream after replacing stream name with bindSuffix minus the last word
1331 //      and the file name with last word of the bindSuffix
1332 //  Allowed path examples:
1333 //    "path":"/"
1334 //    "path":"/subdir1"
1335 //    "path":"/subdir1/subdir2"
1336 //    "path":"/subdir/filename" etc
1337 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1338         collection := outputCollections[mnt.PortableDataHash]
1339         if collection.PortableDataHash == "" {
1340                 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1341                 if err != nil {
1342                         return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1343                 }
1344                 outputCollections[mnt.PortableDataHash] = collection
1345         }
1346
1347         if collection.ManifestText == "" {
1348                 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1349                 return "", nil
1350         }
1351
1352         mft := manifest.Manifest{Text: collection.ManifestText}
1353         extracted := mft.Extract(mnt.Path, bindSuffix)
1354         if extracted.Err != nil {
1355                 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1356         }
1357         return extracted.Text, nil
1358 }
1359
1360 func (runner *ContainerRunner) CleanupDirs() {
1361         if runner.ArvMount != nil {
1362                 var delay int64 = 8
1363                 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1364                 umount.Stdout = runner.CrunchLog
1365                 umount.Stderr = runner.CrunchLog
1366                 runner.CrunchLog.Printf("Running %v", umount.Args)
1367                 umnterr := umount.Start()
1368
1369                 if umnterr != nil {
1370                         runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1371                 } else {
1372                         // If arv-mount --unmount gets stuck for any reason, we
1373                         // don't want to wait for it forever.  Do Wait() in a goroutine
1374                         // so it doesn't block crunch-run.
1375                         umountExit := make(chan error)
1376                         go func() {
1377                                 mnterr := umount.Wait()
1378                                 if mnterr != nil {
1379                                         runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1380                                 }
1381                                 umountExit <- mnterr
1382                         }()
1383
1384                         for again := true; again; {
1385                                 again = false
1386                                 select {
1387                                 case <-umountExit:
1388                                         umount = nil
1389                                         again = true
1390                                 case <-runner.ArvMountExit:
1391                                         break
1392                                 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1393                                         runner.CrunchLog.Printf("Timed out waiting for unmount")
1394                                         if umount != nil {
1395                                                 umount.Process.Kill()
1396                                         }
1397                                         runner.ArvMount.Process.Kill()
1398                                 }
1399                         }
1400                 }
1401         }
1402
1403         if runner.ArvMountPoint != "" {
1404                 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1405                         runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1406                 }
1407         }
1408
1409         for _, tmpdir := range runner.CleanupTempDir {
1410                 if rmerr := os.RemoveAll(tmpdir); rmerr != nil {
1411                         runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1412                 }
1413         }
1414 }
1415
1416 // CommitLogs posts the collection containing the final container logs.
1417 func (runner *ContainerRunner) CommitLogs() error {
1418         runner.CrunchLog.Print(runner.finalState)
1419
1420         if runner.arvMountLog != nil {
1421                 runner.arvMountLog.Close()
1422         }
1423         runner.CrunchLog.Close()
1424
1425         // Closing CrunchLog above allows them to be committed to Keep at this
1426         // point, but re-open crunch log with ArvClient in case there are any
1427         // other further errors (such as failing to write the log to Keep!)
1428         // while shutting down
1429         runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1430                 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1431         runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1432
1433         if runner.LogsPDH != nil {
1434                 // If we have already assigned something to LogsPDH,
1435                 // we must be closing the re-opened log, which won't
1436                 // end up getting attached to the container record and
1437                 // therefore doesn't need to be saved as a collection
1438                 // -- it exists only to send logs to other channels.
1439                 return nil
1440         }
1441
1442         mt, err := runner.LogCollection.ManifestText()
1443         if err != nil {
1444                 return fmt.Errorf("While creating log manifest: %v", err)
1445         }
1446
1447         var response arvados.Collection
1448         err = runner.ArvClient.Create("collections",
1449                 arvadosclient.Dict{
1450                         "ensure_unique_name": true,
1451                         "collection": arvadosclient.Dict{
1452                                 "is_trashed":    true,
1453                                 "name":          "logs for " + runner.Container.UUID,
1454                                 "manifest_text": mt}},
1455                 &response)
1456         if err != nil {
1457                 return fmt.Errorf("While creating log collection: %v", err)
1458         }
1459         runner.LogsPDH = &response.PortableDataHash
1460         return nil
1461 }
1462
1463 // UpdateContainerRunning updates the container state to "Running"
1464 func (runner *ContainerRunner) UpdateContainerRunning() error {
1465         runner.cStateLock.Lock()
1466         defer runner.cStateLock.Unlock()
1467         if runner.cCancelled {
1468                 return ErrCancelled
1469         }
1470         return runner.ArvClient.Update("containers", runner.Container.UUID,
1471                 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1472 }
1473
1474 // ContainerToken returns the api_token the container (and any
1475 // arv-mount processes) are allowed to use.
1476 func (runner *ContainerRunner) ContainerToken() (string, error) {
1477         if runner.token != "" {
1478                 return runner.token, nil
1479         }
1480
1481         var auth arvados.APIClientAuthorization
1482         err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1483         if err != nil {
1484                 return "", err
1485         }
1486         runner.token = auth.APIToken
1487         return runner.token, nil
1488 }
1489
1490 // UpdateContainerComplete updates the container record state on API
1491 // server to "Complete" or "Cancelled"
1492 func (runner *ContainerRunner) UpdateContainerFinal() error {
1493         update := arvadosclient.Dict{}
1494         update["state"] = runner.finalState
1495         if runner.LogsPDH != nil {
1496                 update["log"] = *runner.LogsPDH
1497         }
1498         if runner.finalState == "Complete" {
1499                 if runner.ExitCode != nil {
1500                         update["exit_code"] = *runner.ExitCode
1501                 }
1502                 if runner.OutputPDH != nil {
1503                         update["output"] = *runner.OutputPDH
1504                 }
1505         }
1506         return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1507 }
1508
1509 // IsCancelled returns the value of Cancelled, with goroutine safety.
1510 func (runner *ContainerRunner) IsCancelled() bool {
1511         runner.cStateLock.Lock()
1512         defer runner.cStateLock.Unlock()
1513         return runner.cCancelled
1514 }
1515
1516 // NewArvLogWriter creates an ArvLogWriter
1517 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1518         return &ArvLogWriter{
1519                 ArvClient:     runner.ArvClient,
1520                 UUID:          runner.Container.UUID,
1521                 loggingStream: name,
1522                 writeCloser:   runner.LogCollection.Open(name + ".txt")}
1523 }
1524
1525 // Run the full container lifecycle.
1526 func (runner *ContainerRunner) Run() (err error) {
1527         runner.CrunchLog.Printf("crunch-run %s started", version)
1528         runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1529
1530         hostname, hosterr := os.Hostname()
1531         if hosterr != nil {
1532                 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1533         } else {
1534                 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1535         }
1536
1537         runner.finalState = "Queued"
1538
1539         defer func() {
1540                 runner.stopSignals()
1541                 runner.CleanupDirs()
1542
1543                 runner.CrunchLog.Printf("crunch-run finished")
1544                 runner.CrunchLog.Close()
1545         }()
1546
1547         defer func() {
1548                 // checkErr prints e (unless it's nil) and sets err to
1549                 // e (unless err is already non-nil). Thus, if err
1550                 // hasn't already been assigned when Run() returns,
1551                 // this cleanup func will cause Run() to return the
1552                 // first non-nil error that is passed to checkErr().
1553                 checkErr := func(e error) {
1554                         if e == nil {
1555                                 return
1556                         }
1557                         runner.CrunchLog.Print(e)
1558                         if err == nil {
1559                                 err = e
1560                         }
1561                         if runner.finalState == "Complete" {
1562                                 // There was an error in the finalization.
1563                                 runner.finalState = "Cancelled"
1564                         }
1565                 }
1566
1567                 // Log the error encountered in Run(), if any
1568                 checkErr(err)
1569
1570                 if runner.finalState == "Queued" {
1571                         runner.UpdateContainerFinal()
1572                         return
1573                 }
1574
1575                 if runner.IsCancelled() {
1576                         runner.finalState = "Cancelled"
1577                         // but don't return yet -- we still want to
1578                         // capture partial output and write logs
1579                 }
1580
1581                 checkErr(runner.CaptureOutput())
1582                 checkErr(runner.CommitLogs())
1583                 checkErr(runner.UpdateContainerFinal())
1584         }()
1585
1586         err = runner.fetchContainerRecord()
1587         if err != nil {
1588                 return
1589         }
1590
1591         // setup signal handling
1592         runner.setupSignals()
1593
1594         // check for and/or load image
1595         err = runner.LoadImage()
1596         if err != nil {
1597                 if !runner.checkBrokenNode(err) {
1598                         // Failed to load image but not due to a "broken node"
1599                         // condition, probably user error.
1600                         runner.finalState = "Cancelled"
1601                 }
1602                 err = fmt.Errorf("While loading container image: %v", err)
1603                 return
1604         }
1605
1606         // set up FUSE mount and binds
1607         err = runner.SetupMounts()
1608         if err != nil {
1609                 runner.finalState = "Cancelled"
1610                 err = fmt.Errorf("While setting up mounts: %v", err)
1611                 return
1612         }
1613
1614         err = runner.CreateContainer()
1615         if err != nil {
1616                 return
1617         }
1618         err = runner.LogHostInfo()
1619         if err != nil {
1620                 return
1621         }
1622         err = runner.LogNodeRecord()
1623         if err != nil {
1624                 return
1625         }
1626         err = runner.LogContainerRecord()
1627         if err != nil {
1628                 return
1629         }
1630
1631         if runner.IsCancelled() {
1632                 return
1633         }
1634
1635         err = runner.UpdateContainerRunning()
1636         if err != nil {
1637                 return
1638         }
1639         runner.finalState = "Cancelled"
1640
1641         runner.StartCrunchstat()
1642
1643         err = runner.StartContainer()
1644         if err != nil {
1645                 runner.checkBrokenNode(err)
1646                 return
1647         }
1648
1649         err = runner.WaitFinish()
1650         if err == nil {
1651                 runner.finalState = "Complete"
1652         }
1653         return
1654 }
1655
1656 // Fetch the current container record (uuid = runner.Container.UUID)
1657 // into runner.Container.
1658 func (runner *ContainerRunner) fetchContainerRecord() error {
1659         reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1660         if err != nil {
1661                 return fmt.Errorf("error fetching container record: %v", err)
1662         }
1663         defer reader.Close()
1664
1665         dec := json.NewDecoder(reader)
1666         dec.UseNumber()
1667         err = dec.Decode(&runner.Container)
1668         if err != nil {
1669                 return fmt.Errorf("error decoding container record: %v", err)
1670         }
1671         return nil
1672 }
1673
1674 // NewContainerRunner creates a new container runner.
1675 func NewContainerRunner(api IArvadosClient,
1676         kc IKeepClient,
1677         docker ThinDockerClient,
1678         containerUUID string) *ContainerRunner {
1679
1680         cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1681         cr.NewLogWriter = cr.NewArvLogWriter
1682         cr.RunArvMount = cr.ArvMountCmd
1683         cr.MkTempDir = ioutil.TempDir
1684         cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1685         cr.Container.UUID = containerUUID
1686         cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1687         cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1688
1689         loadLogThrottleParams(api)
1690
1691         return cr
1692 }
1693
1694 func main() {
1695         statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1696         cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1697         cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1698         cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1699         caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1700         enableNetwork := flag.String("container-enable-networking", "default",
1701                 `Specify if networking should be enabled for container.  One of 'default', 'always':
1702         default: only enable networking if container requests it.
1703         always:  containers always have networking enabled
1704         `)
1705         networkMode := flag.String("container-network-mode", "default",
1706                 `Set networking mode for container.  Corresponds to Docker network mode (--net).
1707         `)
1708         memprofile := flag.String("memprofile", "", "write memory profile to `file` after running container")
1709         getVersion := flag.Bool("version", false, "Print version information and exit.")
1710         flag.Parse()
1711
1712         // Print version information if requested
1713         if *getVersion {
1714                 fmt.Printf("crunch-run %s\n", version)
1715                 return
1716         }
1717
1718         log.Printf("crunch-run %s started", version)
1719
1720         containerId := flag.Arg(0)
1721
1722         if *caCertsPath != "" {
1723                 arvadosclient.CertFiles = []string{*caCertsPath}
1724         }
1725
1726         api, err := arvadosclient.MakeArvadosClient()
1727         if err != nil {
1728                 log.Fatalf("%s: %v", containerId, err)
1729         }
1730         api.Retries = 8
1731
1732         kc, kcerr := keepclient.MakeKeepClient(api)
1733         if kcerr != nil {
1734                 log.Fatalf("%s: %v", containerId, kcerr)
1735         }
1736         kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1737         kc.Retries = 4
1738
1739         // API version 1.21 corresponds to Docker 1.9, which is currently the
1740         // minimum version we want to support.
1741         docker, dockererr := dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1742         dockerClientProxy := ThinDockerClientProxy{Docker: docker}
1743
1744         cr := NewContainerRunner(api, kc, dockerClientProxy, containerId)
1745
1746         if dockererr != nil {
1747                 cr.CrunchLog.Printf("%s: %v", containerId, dockererr)
1748                 cr.checkBrokenNode(dockererr)
1749                 cr.CrunchLog.Close()
1750                 os.Exit(1)
1751         }
1752
1753         cr.statInterval = *statInterval
1754         cr.cgroupRoot = *cgroupRoot
1755         cr.expectCgroupParent = *cgroupParent
1756         cr.enableNetwork = *enableNetwork
1757         cr.networkMode = *networkMode
1758         if *cgroupParentSubsystem != "" {
1759                 p := findCgroup(*cgroupParentSubsystem)
1760                 cr.setCgroupParent = p
1761                 cr.expectCgroupParent = p
1762         }
1763
1764         runerr := cr.Run()
1765
1766         if *memprofile != "" {
1767                 f, err := os.Create(*memprofile)
1768                 if err != nil {
1769                         log.Printf("could not create memory profile: ", err)
1770                 }
1771                 runtime.GC() // get up-to-date statistics
1772                 if err := pprof.WriteHeapProfile(f); err != nil {
1773                         log.Printf("could not write memory profile: ", err)
1774                 }
1775                 closeerr := f.Close()
1776                 if closeerr != nil {
1777                         log.Printf("closing memprofile file: ", err)
1778                 }
1779         }
1780
1781         if runerr != nil {
1782                 log.Fatalf("%s: %v", containerId, runerr)
1783         }
1784 }