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