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