11308: Merge branch 'master' into 11308-python3
[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                 runner.ArvClient,
637                 runner.Container.UUID,
638                 "container",
639                 runner.LogCollection.Open("container.json"),
640         }
641         // Get Container record JSON from the API Server
642         reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
643         if err != nil {
644                 return fmt.Errorf("While retrieving container record from the API server: %v", err)
645         }
646         defer reader.Close()
647         // Read the API server response as []byte
648         json_bytes, err := ioutil.ReadAll(reader)
649         if err != nil {
650                 return fmt.Errorf("While reading container record API server response: %v", err)
651         }
652         // Decode the JSON []byte
653         var cr map[string]interface{}
654         if err = json.Unmarshal(json_bytes, &cr); err != nil {
655                 return fmt.Errorf("While decoding the container record JSON response: %v", err)
656         }
657         // Re-encode it using indentation to improve readability
658         enc := json.NewEncoder(w)
659         enc.SetIndent("", "    ")
660         if err = enc.Encode(cr); err != nil {
661                 return fmt.Errorf("While logging the JSON container record: %v", err)
662         }
663         err = w.Close()
664         if err != nil {
665                 return fmt.Errorf("While closing container.json log: %v", err)
666         }
667         return nil
668 }
669
670 // AttachStreams connects the docker container stdin, stdout and stderr logs
671 // to the Arvados logger which logs to Keep and the API server logs table.
672 func (runner *ContainerRunner) AttachStreams() (err error) {
673
674         runner.CrunchLog.Print("Attaching container streams")
675
676         // If stdin mount is provided, attach it to the docker container
677         var stdinRdr keepclient.Reader
678         var stdinJson []byte
679         if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
680                 if stdinMnt.Kind == "collection" {
681                         var stdinColl arvados.Collection
682                         collId := stdinMnt.UUID
683                         if collId == "" {
684                                 collId = stdinMnt.PortableDataHash
685                         }
686                         err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
687                         if err != nil {
688                                 return fmt.Errorf("While getting stding collection: %v", err)
689                         }
690
691                         stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
692                         if os.IsNotExist(err) {
693                                 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
694                         } else if err != nil {
695                                 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
696                         }
697                 } else if stdinMnt.Kind == "json" {
698                         stdinJson, err = json.Marshal(stdinMnt.Content)
699                         if err != nil {
700                                 return fmt.Errorf("While encoding stdin json data: %v", err)
701                         }
702                 }
703         }
704
705         stdinUsed := stdinRdr != nil || len(stdinJson) != 0
706         response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
707                 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
708         if err != nil {
709                 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
710         }
711
712         runner.loggingDone = make(chan bool)
713
714         if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
715                 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
716                 if err != nil {
717                         return err
718                 }
719                 runner.Stdout = stdoutFile
720         } else {
721                 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
722         }
723
724         if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
725                 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
726                 if err != nil {
727                         return err
728                 }
729                 runner.Stderr = stderrFile
730         } else {
731                 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
732         }
733
734         if stdinRdr != nil {
735                 go func() {
736                         _, err := io.Copy(response.Conn, stdinRdr)
737                         if err != nil {
738                                 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
739                                 runner.stop()
740                         }
741                         stdinRdr.Close()
742                         response.CloseWrite()
743                 }()
744         } else if len(stdinJson) != 0 {
745                 go func() {
746                         _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
747                         if err != nil {
748                                 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
749                                 runner.stop()
750                         }
751                         response.CloseWrite()
752                 }()
753         }
754
755         go runner.ProcessDockerAttach(response.Reader)
756
757         return nil
758 }
759
760 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
761         stdoutPath := mntPath[len(runner.Container.OutputPath):]
762         index := strings.LastIndex(stdoutPath, "/")
763         if index > 0 {
764                 subdirs := stdoutPath[:index]
765                 if subdirs != "" {
766                         st, err := os.Stat(runner.HostOutputDir)
767                         if err != nil {
768                                 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
769                         }
770                         stdoutPath := path.Join(runner.HostOutputDir, subdirs)
771                         err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
772                         if err != nil {
773                                 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
774                         }
775                 }
776         }
777         stdoutFile, err := os.Create(path.Join(runner.HostOutputDir, stdoutPath))
778         if err != nil {
779                 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
780         }
781
782         return stdoutFile, nil
783 }
784
785 // CreateContainer creates the docker container.
786 func (runner *ContainerRunner) CreateContainer() error {
787         runner.CrunchLog.Print("Creating Docker container")
788
789         runner.ContainerConfig.Cmd = runner.Container.Command
790         if runner.Container.Cwd != "." {
791                 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
792         }
793
794         for k, v := range runner.Container.Environment {
795                 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
796         }
797
798         runner.ContainerConfig.Volumes = runner.Volumes
799
800         runner.HostConfig = dockercontainer.HostConfig{
801                 Binds:  runner.Binds,
802                 Cgroup: dockercontainer.CgroupSpec(runner.setCgroupParent),
803                 LogConfig: dockercontainer.LogConfig{
804                         Type: "none",
805                 },
806         }
807
808         if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
809                 tok, err := runner.ContainerToken()
810                 if err != nil {
811                         return err
812                 }
813                 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
814                         "ARVADOS_API_TOKEN="+tok,
815                         "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
816                         "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
817                 )
818                 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
819         } else {
820                 if runner.enableNetwork == "always" {
821                         runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
822                 } else {
823                         runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
824                 }
825         }
826
827         _, stdinUsed := runner.Container.Mounts["stdin"]
828         runner.ContainerConfig.OpenStdin = stdinUsed
829         runner.ContainerConfig.StdinOnce = stdinUsed
830         runner.ContainerConfig.AttachStdin = stdinUsed
831         runner.ContainerConfig.AttachStdout = true
832         runner.ContainerConfig.AttachStderr = true
833
834         createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
835         if err != nil {
836                 return fmt.Errorf("While creating container: %v", err)
837         }
838
839         runner.ContainerID = createdBody.ID
840
841         return runner.AttachStreams()
842 }
843
844 // StartContainer starts the docker container created by CreateContainer.
845 func (runner *ContainerRunner) StartContainer() error {
846         runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
847         runner.cStateLock.Lock()
848         defer runner.cStateLock.Unlock()
849         if runner.cCancelled {
850                 return ErrCancelled
851         }
852         err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
853                 dockertypes.ContainerStartOptions{})
854         if err != nil {
855                 return fmt.Errorf("could not start container: %v", err)
856         }
857         runner.cStarted = true
858         return nil
859 }
860
861 // WaitFinish waits for the container to terminate, capture the exit code, and
862 // close the stdout/stderr logging.
863 func (runner *ContainerRunner) WaitFinish() error {
864         runner.CrunchLog.Print("Waiting for container to finish")
865
866         waitDocker, err := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID)
867         if err != nil {
868                 return fmt.Errorf("container wait: %v", err)
869         }
870
871         runner.CrunchLog.Printf("Container exited with code: %v", waitDocker)
872         code := int(waitDocker)
873         runner.ExitCode = &code
874
875         waitMount := runner.ArvMountExit
876         select {
877         case err := <-waitMount:
878                 runner.CrunchLog.Printf("arv-mount exited before container finished: %v", err)
879                 waitMount = nil
880                 runner.stop()
881         default:
882         }
883
884         // wait for stdout/stderr to complete
885         <-runner.loggingDone
886
887         return nil
888 }
889
890 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
891 func (runner *ContainerRunner) CaptureOutput() error {
892         if runner.finalState != "Complete" {
893                 return nil
894         }
895
896         if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
897                 // Output may have been set directly by the container, so
898                 // refresh the container record to check.
899                 err := runner.ArvClient.Get("containers", runner.Container.UUID,
900                         nil, &runner.Container)
901                 if err != nil {
902                         return err
903                 }
904                 if runner.Container.Output != "" {
905                         // Container output is already set.
906                         runner.OutputPDH = &runner.Container.Output
907                         return nil
908                 }
909         }
910
911         if runner.HostOutputDir == "" {
912                 return nil
913         }
914
915         _, err := os.Stat(runner.HostOutputDir)
916         if err != nil {
917                 return fmt.Errorf("While checking host output path: %v", err)
918         }
919
920         var manifestText string
921
922         collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
923         _, err = os.Stat(collectionMetafile)
924         if err != nil {
925                 // Regular directory
926                 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
927                 manifestText, err = cw.WriteTree(runner.HostOutputDir, runner.CrunchLog.Logger)
928                 if err != nil {
929                         return fmt.Errorf("While uploading output files: %v", err)
930                 }
931         } else {
932                 // FUSE mount directory
933                 file, openerr := os.Open(collectionMetafile)
934                 if openerr != nil {
935                         return fmt.Errorf("While opening FUSE metafile: %v", err)
936                 }
937                 defer file.Close()
938
939                 var rec arvados.Collection
940                 err = json.NewDecoder(file).Decode(&rec)
941                 if err != nil {
942                         return fmt.Errorf("While reading FUSE metafile: %v", err)
943                 }
944                 manifestText = rec.ManifestText
945         }
946
947         // Pre-populate output from the configured mount points
948         var binds []string
949         for bind, _ := range runner.Container.Mounts {
950                 binds = append(binds, bind)
951         }
952         sort.Strings(binds)
953
954         for _, bind := range binds {
955                 mnt := runner.Container.Mounts[bind]
956
957                 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
958
959                 if bindSuffix == bind || len(bindSuffix) <= 0 {
960                         // either does not start with OutputPath or is OutputPath itself
961                         continue
962                 }
963
964                 if mnt.ExcludeFromOutput == true {
965                         continue
966                 }
967
968                 // append to manifest_text
969                 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
970                 if err != nil {
971                         return err
972                 }
973
974                 manifestText = manifestText + m
975         }
976
977         // Save output
978         var response arvados.Collection
979         manifest := manifest.Manifest{Text: manifestText}
980         manifestText = manifest.Extract(".", ".").Text
981         err = runner.ArvClient.Create("collections",
982                 arvadosclient.Dict{
983                         "ensure_unique_name": true,
984                         "collection": arvadosclient.Dict{
985                                 "is_trashed":    true,
986                                 "name":          "output for " + runner.Container.UUID,
987                                 "manifest_text": manifestText}},
988                 &response)
989         if err != nil {
990                 return fmt.Errorf("While creating output collection: %v", err)
991         }
992         runner.OutputPDH = &response.PortableDataHash
993         return nil
994 }
995
996 var outputCollections = make(map[string]arvados.Collection)
997
998 // Fetch the collection for the mnt.PortableDataHash
999 // Return the manifest_text fragment corresponding to the specified mnt.Path
1000 //  after making any required updates.
1001 //  Ex:
1002 //    If mnt.Path is not specified,
1003 //      return the entire manifest_text after replacing any "." with bindSuffix
1004 //    If mnt.Path corresponds to one stream,
1005 //      return the manifest_text for that stream after replacing that stream name with bindSuffix
1006 //    Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1007 //      for that stream after replacing stream name with bindSuffix minus the last word
1008 //      and the file name with last word of the bindSuffix
1009 //  Allowed path examples:
1010 //    "path":"/"
1011 //    "path":"/subdir1"
1012 //    "path":"/subdir1/subdir2"
1013 //    "path":"/subdir/filename" etc
1014 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1015         collection := outputCollections[mnt.PortableDataHash]
1016         if collection.PortableDataHash == "" {
1017                 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1018                 if err != nil {
1019                         return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1020                 }
1021                 outputCollections[mnt.PortableDataHash] = collection
1022         }
1023
1024         if collection.ManifestText == "" {
1025                 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1026                 return "", nil
1027         }
1028
1029         mft := manifest.Manifest{Text: collection.ManifestText}
1030         extracted := mft.Extract(mnt.Path, bindSuffix)
1031         if extracted.Err != nil {
1032                 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1033         }
1034         return extracted.Text, nil
1035 }
1036
1037 func (runner *ContainerRunner) CleanupDirs() {
1038         if runner.ArvMount != nil {
1039                 umount := exec.Command("fusermount", "-z", "-u", runner.ArvMountPoint)
1040                 umnterr := umount.Run()
1041                 if umnterr != nil {
1042                         runner.CrunchLog.Printf("While running fusermount: %v", umnterr)
1043                 }
1044
1045                 mnterr := <-runner.ArvMountExit
1046                 if mnterr != nil {
1047                         runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
1048                 }
1049         }
1050
1051         for _, tmpdir := range runner.CleanupTempDir {
1052                 rmerr := os.RemoveAll(tmpdir)
1053                 if rmerr != nil {
1054                         runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1055                 }
1056         }
1057 }
1058
1059 // CommitLogs posts the collection containing the final container logs.
1060 func (runner *ContainerRunner) CommitLogs() error {
1061         runner.CrunchLog.Print(runner.finalState)
1062         runner.CrunchLog.Close()
1063
1064         // Closing CrunchLog above allows it to be committed to Keep at this
1065         // point, but re-open crunch log with ArvClient in case there are any
1066         // other further (such as failing to write the log to Keep!) while
1067         // shutting down
1068         runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{runner.ArvClient, runner.Container.UUID,
1069                 "crunch-run", nil})
1070
1071         if runner.LogsPDH != nil {
1072                 // If we have already assigned something to LogsPDH,
1073                 // we must be closing the re-opened log, which won't
1074                 // end up getting attached to the container record and
1075                 // therefore doesn't need to be saved as a collection
1076                 // -- it exists only to send logs to other channels.
1077                 return nil
1078         }
1079
1080         mt, err := runner.LogCollection.ManifestText()
1081         if err != nil {
1082                 return fmt.Errorf("While creating log manifest: %v", err)
1083         }
1084
1085         var response arvados.Collection
1086         err = runner.ArvClient.Create("collections",
1087                 arvadosclient.Dict{
1088                         "ensure_unique_name": true,
1089                         "collection": arvadosclient.Dict{
1090                                 "is_trashed":    true,
1091                                 "name":          "logs for " + runner.Container.UUID,
1092                                 "manifest_text": mt}},
1093                 &response)
1094         if err != nil {
1095                 return fmt.Errorf("While creating log collection: %v", err)
1096         }
1097         runner.LogsPDH = &response.PortableDataHash
1098         return nil
1099 }
1100
1101 // UpdateContainerRunning updates the container state to "Running"
1102 func (runner *ContainerRunner) UpdateContainerRunning() error {
1103         runner.cStateLock.Lock()
1104         defer runner.cStateLock.Unlock()
1105         if runner.cCancelled {
1106                 return ErrCancelled
1107         }
1108         return runner.ArvClient.Update("containers", runner.Container.UUID,
1109                 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1110 }
1111
1112 // ContainerToken returns the api_token the container (and any
1113 // arv-mount processes) are allowed to use.
1114 func (runner *ContainerRunner) ContainerToken() (string, error) {
1115         if runner.token != "" {
1116                 return runner.token, nil
1117         }
1118
1119         var auth arvados.APIClientAuthorization
1120         err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1121         if err != nil {
1122                 return "", err
1123         }
1124         runner.token = auth.APIToken
1125         return runner.token, nil
1126 }
1127
1128 // UpdateContainerComplete updates the container record state on API
1129 // server to "Complete" or "Cancelled"
1130 func (runner *ContainerRunner) UpdateContainerFinal() error {
1131         update := arvadosclient.Dict{}
1132         update["state"] = runner.finalState
1133         if runner.LogsPDH != nil {
1134                 update["log"] = *runner.LogsPDH
1135         }
1136         if runner.finalState == "Complete" {
1137                 if runner.ExitCode != nil {
1138                         update["exit_code"] = *runner.ExitCode
1139                 }
1140                 if runner.OutputPDH != nil {
1141                         update["output"] = *runner.OutputPDH
1142                 }
1143         }
1144         return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1145 }
1146
1147 // IsCancelled returns the value of Cancelled, with goroutine safety.
1148 func (runner *ContainerRunner) IsCancelled() bool {
1149         runner.cStateLock.Lock()
1150         defer runner.cStateLock.Unlock()
1151         return runner.cCancelled
1152 }
1153
1154 // NewArvLogWriter creates an ArvLogWriter
1155 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1156         return &ArvLogWriter{runner.ArvClient, runner.Container.UUID, name, runner.LogCollection.Open(name + ".txt")}
1157 }
1158
1159 // Run the full container lifecycle.
1160 func (runner *ContainerRunner) Run() (err error) {
1161         runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1162
1163         hostname, hosterr := os.Hostname()
1164         if hosterr != nil {
1165                 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1166         } else {
1167                 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1168         }
1169
1170         // Clean up temporary directories _after_ finalizing
1171         // everything (if we've made any by then)
1172         defer runner.CleanupDirs()
1173
1174         runner.finalState = "Queued"
1175
1176         defer func() {
1177                 // checkErr prints e (unless it's nil) and sets err to
1178                 // e (unless err is already non-nil). Thus, if err
1179                 // hasn't already been assigned when Run() returns,
1180                 // this cleanup func will cause Run() to return the
1181                 // first non-nil error that is passed to checkErr().
1182                 checkErr := func(e error) {
1183                         if e == nil {
1184                                 return
1185                         }
1186                         runner.CrunchLog.Print(e)
1187                         if err == nil {
1188                                 err = e
1189                         }
1190                 }
1191
1192                 // Log the error encountered in Run(), if any
1193                 checkErr(err)
1194
1195                 if runner.finalState == "Queued" {
1196                         runner.CrunchLog.Close()
1197                         runner.UpdateContainerFinal()
1198                         return
1199                 }
1200
1201                 if runner.IsCancelled() {
1202                         runner.finalState = "Cancelled"
1203                         // but don't return yet -- we still want to
1204                         // capture partial output and write logs
1205                 }
1206
1207                 checkErr(runner.CaptureOutput())
1208                 checkErr(runner.CommitLogs())
1209                 checkErr(runner.UpdateContainerFinal())
1210
1211                 // The real log is already closed, but then we opened
1212                 // a new one in case we needed to log anything while
1213                 // finalizing.
1214                 runner.CrunchLog.Close()
1215         }()
1216
1217         err = runner.ArvClient.Get("containers", runner.Container.UUID, nil, &runner.Container)
1218         if err != nil {
1219                 err = fmt.Errorf("While getting container record: %v", err)
1220                 return
1221         }
1222
1223         // setup signal handling
1224         runner.SetupSignals()
1225
1226         // check for and/or load image
1227         err = runner.LoadImage()
1228         if err != nil {
1229                 runner.finalState = "Cancelled"
1230                 err = fmt.Errorf("While loading container image: %v", err)
1231                 return
1232         }
1233
1234         // set up FUSE mount and binds
1235         err = runner.SetupMounts()
1236         if err != nil {
1237                 runner.finalState = "Cancelled"
1238                 err = fmt.Errorf("While setting up mounts: %v", err)
1239                 return
1240         }
1241
1242         err = runner.CreateContainer()
1243         if err != nil {
1244                 return
1245         }
1246
1247         // Gather and record node information
1248         err = runner.LogNodeInfo()
1249         if err != nil {
1250                 return
1251         }
1252         // Save container.json record on log collection
1253         err = runner.LogContainerRecord()
1254         if err != nil {
1255                 return
1256         }
1257
1258         runner.StartCrunchstat()
1259
1260         if runner.IsCancelled() {
1261                 return
1262         }
1263
1264         err = runner.UpdateContainerRunning()
1265         if err != nil {
1266                 return
1267         }
1268         runner.finalState = "Cancelled"
1269
1270         err = runner.StartContainer()
1271         if err != nil {
1272                 return
1273         }
1274
1275         err = runner.WaitFinish()
1276         if err == nil {
1277                 runner.finalState = "Complete"
1278         }
1279         return
1280 }
1281
1282 // NewContainerRunner creates a new container runner.
1283 func NewContainerRunner(api IArvadosClient,
1284         kc IKeepClient,
1285         docker ThinDockerClient,
1286         containerUUID string) *ContainerRunner {
1287
1288         cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1289         cr.NewLogWriter = cr.NewArvLogWriter
1290         cr.RunArvMount = cr.ArvMountCmd
1291         cr.MkTempDir = ioutil.TempDir
1292         cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1293         cr.Container.UUID = containerUUID
1294         cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1295         cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1296         return cr
1297 }
1298
1299 func main() {
1300         statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1301         cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1302         cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1303         cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1304         caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1305         enableNetwork := flag.String("container-enable-networking", "default",
1306                 `Specify if networking should be enabled for container.  One of 'default', 'always':
1307         default: only enable networking if container requests it.
1308         always:  containers always have networking enabled
1309         `)
1310         networkMode := flag.String("container-network-mode", "default",
1311                 `Set networking mode for container.  Corresponds to Docker network mode (--net).
1312         `)
1313         flag.Parse()
1314
1315         containerId := flag.Arg(0)
1316
1317         if *caCertsPath != "" {
1318                 arvadosclient.CertFiles = []string{*caCertsPath}
1319         }
1320
1321         api, err := arvadosclient.MakeArvadosClient()
1322         if err != nil {
1323                 log.Fatalf("%s: %v", containerId, err)
1324         }
1325         api.Retries = 8
1326
1327         var kc *keepclient.KeepClient
1328         kc, err = keepclient.MakeKeepClient(api)
1329         if err != nil {
1330                 log.Fatalf("%s: %v", containerId, err)
1331         }
1332         kc.Retries = 4
1333
1334         var docker *dockerclient.Client
1335         // API version 1.21 corresponds to Docker 1.9, which is currently the
1336         // minimum version we want to support.
1337         docker, err = dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1338         if err != nil {
1339                 log.Fatalf("%s: %v", containerId, err)
1340         }
1341
1342         dockerClientProxy := ThinDockerClientProxy{Docker: docker}
1343
1344         cr := NewContainerRunner(api, kc, dockerClientProxy, containerId)
1345         cr.statInterval = *statInterval
1346         cr.cgroupRoot = *cgroupRoot
1347         cr.expectCgroupParent = *cgroupParent
1348         cr.enableNetwork = *enableNetwork
1349         cr.networkMode = *networkMode
1350         if *cgroupParentSubsystem != "" {
1351                 p := findCgroup(*cgroupParentSubsystem)
1352                 cr.setCgroupParent = p
1353                 cr.expectCgroupParent = p
1354         }
1355
1356         err = cr.Run()
1357         if err != nil {
1358                 log.Fatalf("%s: %v", containerId, err)
1359         }
1360
1361 }