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