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