11693: Add test that error capturing output results in cancelled container.
[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":
434                         var tmpdir string
435                         tmpdir, err = runner.MkTempDir("", "")
436                         if err != nil {
437                                 return fmt.Errorf("While creating mount temp dir: %v", err)
438                         }
439                         st, staterr := os.Stat(tmpdir)
440                         if staterr != nil {
441                                 return fmt.Errorf("While Stat on temp dir: %v", staterr)
442                         }
443                         err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
444                         if staterr != nil {
445                                 return fmt.Errorf("While Chmod temp dir: %v", err)
446                         }
447                         runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
448                         runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", tmpdir, bind))
449                         if bind == runner.Container.OutputPath {
450                                 runner.HostOutputDir = tmpdir
451                         }
452
453                 case mnt.Kind == "json":
454                         jsondata, err := json.Marshal(mnt.Content)
455                         if err != nil {
456                                 return fmt.Errorf("encoding json data: %v", err)
457                         }
458                         // Create a tempdir with a single file
459                         // (instead of just a tempfile): this way we
460                         // can ensure the file is world-readable
461                         // inside the container, without having to
462                         // make it world-readable on the docker host.
463                         tmpdir, err := runner.MkTempDir("", "")
464                         if err != nil {
465                                 return fmt.Errorf("creating temp dir: %v", err)
466                         }
467                         runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
468                         tmpfn := filepath.Join(tmpdir, "mountdata.json")
469                         err = ioutil.WriteFile(tmpfn, jsondata, 0644)
470                         if err != nil {
471                                 return fmt.Errorf("writing temp file: %v", err)
472                         }
473                         runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
474                 }
475         }
476
477         if runner.HostOutputDir == "" {
478                 return fmt.Errorf("Output path does not correspond to a writable mount point")
479         }
480
481         if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
482                 for _, certfile := range arvadosclient.CertFiles {
483                         _, err := os.Stat(certfile)
484                         if err == nil {
485                                 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
486                                 break
487                         }
488                 }
489         }
490
491         if pdhOnly {
492                 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
493         } else {
494                 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
495         }
496         arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
497
498         token, err := runner.ContainerToken()
499         if err != nil {
500                 return fmt.Errorf("could not get container token: %s", err)
501         }
502
503         runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
504         if err != nil {
505                 return fmt.Errorf("While trying to start arv-mount: %v", err)
506         }
507
508         for _, p := range collectionPaths {
509                 _, err = os.Stat(p)
510                 if err != nil {
511                         return fmt.Errorf("While checking that input files exist: %v", err)
512                 }
513         }
514
515         return nil
516 }
517
518 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
519         // Handle docker log protocol
520         // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
521
522         header := make([]byte, 8)
523         for {
524                 _, readerr := io.ReadAtLeast(containerReader, header, 8)
525
526                 if readerr == nil {
527                         readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
528                         if header[0] == 1 {
529                                 // stdout
530                                 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
531                         } else {
532                                 // stderr
533                                 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
534                         }
535                 }
536
537                 if readerr != nil {
538                         if readerr != io.EOF {
539                                 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
540                         }
541
542                         closeerr := runner.Stdout.Close()
543                         if closeerr != nil {
544                                 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
545                         }
546
547                         closeerr = runner.Stderr.Close()
548                         if closeerr != nil {
549                                 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
550                         }
551
552                         if runner.statReporter != nil {
553                                 runner.statReporter.Stop()
554                                 closeerr = runner.statLogger.Close()
555                                 if closeerr != nil {
556                                         runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
557                                 }
558                         }
559
560                         runner.loggingDone <- true
561                         close(runner.loggingDone)
562                         return
563                 }
564         }
565 }
566
567 func (runner *ContainerRunner) StartCrunchstat() {
568         runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
569         runner.statReporter = &crunchstat.Reporter{
570                 CID:          runner.ContainerID,
571                 Logger:       log.New(runner.statLogger, "", 0),
572                 CgroupParent: runner.expectCgroupParent,
573                 CgroupRoot:   runner.cgroupRoot,
574                 PollPeriod:   runner.statInterval,
575         }
576         runner.statReporter.Start()
577 }
578
579 type infoCommand struct {
580         label string
581         cmd   []string
582 }
583
584 // Gather node information and store it on the log for debugging
585 // purposes.
586 func (runner *ContainerRunner) LogNodeInfo() (err error) {
587         w := runner.NewLogWriter("node-info")
588         logger := log.New(w, "node-info", 0)
589
590         commands := []infoCommand{
591                 infoCommand{
592                         label: "Host Information",
593                         cmd:   []string{"uname", "-a"},
594                 },
595                 infoCommand{
596                         label: "CPU Information",
597                         cmd:   []string{"cat", "/proc/cpuinfo"},
598                 },
599                 infoCommand{
600                         label: "Memory Information",
601                         cmd:   []string{"cat", "/proc/meminfo"},
602                 },
603                 infoCommand{
604                         label: "Disk Space",
605                         cmd:   []string{"df", "-m", "/", os.TempDir()},
606                 },
607                 infoCommand{
608                         label: "Disk INodes",
609                         cmd:   []string{"df", "-i", "/", os.TempDir()},
610                 },
611         }
612
613         // Run commands with informational output to be logged.
614         var out []byte
615         for _, command := range commands {
616                 out, err = exec.Command(command.cmd[0], command.cmd[1:]...).CombinedOutput()
617                 if err != nil {
618                         return fmt.Errorf("While running command %q: %v",
619                                 command.cmd, err)
620                 }
621                 logger.Println(command.label)
622                 for _, line := range strings.Split(string(out), "\n") {
623                         logger.Println(" ", line)
624                 }
625         }
626
627         err = w.Close()
628         if err != nil {
629                 return fmt.Errorf("While closing node-info logs: %v", err)
630         }
631         return nil
632 }
633
634 // Get and save the raw JSON container record from the API server
635 func (runner *ContainerRunner) LogContainerRecord() (err error) {
636         w := &ArvLogWriter{
637                 ArvClient:     runner.ArvClient,
638                 UUID:          runner.Container.UUID,
639                 loggingStream: "container",
640                 writeCloser:   runner.LogCollection.Open("container.json"),
641         }
642
643         // Get Container record JSON from the API Server
644         reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
645         if err != nil {
646                 return fmt.Errorf("While retrieving container record from the API server: %v", err)
647         }
648         defer reader.Close()
649         // Read the API server response as []byte
650         json_bytes, err := ioutil.ReadAll(reader)
651         if err != nil {
652                 return fmt.Errorf("While reading container record API server response: %v", err)
653         }
654         // Decode the JSON []byte
655         var cr map[string]interface{}
656         if err = json.Unmarshal(json_bytes, &cr); err != nil {
657                 return fmt.Errorf("While decoding the container record JSON response: %v", err)
658         }
659         // Re-encode it using indentation to improve readability
660         enc := json.NewEncoder(w)
661         enc.SetIndent("", "    ")
662         if err = enc.Encode(cr); err != nil {
663                 return fmt.Errorf("While logging the JSON container record: %v", err)
664         }
665         err = w.Close()
666         if err != nil {
667                 return fmt.Errorf("While closing container.json log: %v", err)
668         }
669         return nil
670 }
671
672 // AttachStreams connects the docker container stdin, stdout and stderr logs
673 // to the Arvados logger which logs to Keep and the API server logs table.
674 func (runner *ContainerRunner) AttachStreams() (err error) {
675
676         runner.CrunchLog.Print("Attaching container streams")
677
678         // If stdin mount is provided, attach it to the docker container
679         var stdinRdr keepclient.Reader
680         var stdinJson []byte
681         if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
682                 if stdinMnt.Kind == "collection" {
683                         var stdinColl arvados.Collection
684                         collId := stdinMnt.UUID
685                         if collId == "" {
686                                 collId = stdinMnt.PortableDataHash
687                         }
688                         err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
689                         if err != nil {
690                                 return fmt.Errorf("While getting stding collection: %v", err)
691                         }
692
693                         stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
694                         if os.IsNotExist(err) {
695                                 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
696                         } else if err != nil {
697                                 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
698                         }
699                 } else if stdinMnt.Kind == "json" {
700                         stdinJson, err = json.Marshal(stdinMnt.Content)
701                         if err != nil {
702                                 return fmt.Errorf("While encoding stdin json data: %v", err)
703                         }
704                 }
705         }
706
707         stdinUsed := stdinRdr != nil || len(stdinJson) != 0
708         response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
709                 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
710         if err != nil {
711                 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
712         }
713
714         runner.loggingDone = make(chan bool)
715
716         if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
717                 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
718                 if err != nil {
719                         return err
720                 }
721                 runner.Stdout = stdoutFile
722         } else {
723                 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
724         }
725
726         if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
727                 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
728                 if err != nil {
729                         return err
730                 }
731                 runner.Stderr = stderrFile
732         } else {
733                 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
734         }
735
736         if stdinRdr != nil {
737                 go func() {
738                         _, err := io.Copy(response.Conn, stdinRdr)
739                         if err != nil {
740                                 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
741                                 runner.stop()
742                         }
743                         stdinRdr.Close()
744                         response.CloseWrite()
745                 }()
746         } else if len(stdinJson) != 0 {
747                 go func() {
748                         _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
749                         if err != nil {
750                                 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
751                                 runner.stop()
752                         }
753                         response.CloseWrite()
754                 }()
755         }
756
757         go runner.ProcessDockerAttach(response.Reader)
758
759         return nil
760 }
761
762 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
763         stdoutPath := mntPath[len(runner.Container.OutputPath):]
764         index := strings.LastIndex(stdoutPath, "/")
765         if index > 0 {
766                 subdirs := stdoutPath[:index]
767                 if subdirs != "" {
768                         st, err := os.Stat(runner.HostOutputDir)
769                         if err != nil {
770                                 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
771                         }
772                         stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
773                         err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
774                         if err != nil {
775                                 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
776                         }
777                 }
778         }
779         stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
780         if err != nil {
781                 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
782         }
783
784         return stdoutFile, nil
785 }
786
787 // CreateContainer creates the docker container.
788 func (runner *ContainerRunner) CreateContainer() error {
789         runner.CrunchLog.Print("Creating Docker container")
790
791         runner.ContainerConfig.Cmd = runner.Container.Command
792         if runner.Container.Cwd != "." {
793                 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
794         }
795
796         for k, v := range runner.Container.Environment {
797                 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
798         }
799
800         runner.ContainerConfig.Volumes = runner.Volumes
801
802         runner.HostConfig = dockercontainer.HostConfig{
803                 Binds:  runner.Binds,
804                 Cgroup: dockercontainer.CgroupSpec(runner.setCgroupParent),
805                 LogConfig: dockercontainer.LogConfig{
806                         Type: "none",
807                 },
808         }
809
810         if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
811                 tok, err := runner.ContainerToken()
812                 if err != nil {
813                         return err
814                 }
815                 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
816                         "ARVADOS_API_TOKEN="+tok,
817                         "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
818                         "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
819                 )
820                 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
821         } else {
822                 if runner.enableNetwork == "always" {
823                         runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
824                 } else {
825                         runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
826                 }
827         }
828
829         _, stdinUsed := runner.Container.Mounts["stdin"]
830         runner.ContainerConfig.OpenStdin = stdinUsed
831         runner.ContainerConfig.StdinOnce = stdinUsed
832         runner.ContainerConfig.AttachStdin = stdinUsed
833         runner.ContainerConfig.AttachStdout = true
834         runner.ContainerConfig.AttachStderr = true
835
836         createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
837         if err != nil {
838                 return fmt.Errorf("While creating container: %v", err)
839         }
840
841         runner.ContainerID = createdBody.ID
842
843         return runner.AttachStreams()
844 }
845
846 // StartContainer starts the docker container created by CreateContainer.
847 func (runner *ContainerRunner) StartContainer() error {
848         runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
849         runner.cStateLock.Lock()
850         defer runner.cStateLock.Unlock()
851         if runner.cCancelled {
852                 return ErrCancelled
853         }
854         err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
855                 dockertypes.ContainerStartOptions{})
856         if err != nil {
857                 return fmt.Errorf("could not start container: %v", err)
858         }
859         runner.cStarted = true
860         return nil
861 }
862
863 // WaitFinish waits for the container to terminate, capture the exit code, and
864 // close the stdout/stderr logging.
865 func (runner *ContainerRunner) WaitFinish() error {
866         runner.CrunchLog.Print("Waiting for container to finish")
867
868         waitDocker, err := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID)
869         if err != nil {
870                 return fmt.Errorf("container wait: %v", err)
871         }
872
873         runner.CrunchLog.Printf("Container exited with code: %v", waitDocker)
874         code := int(waitDocker)
875         runner.ExitCode = &code
876
877         waitMount := runner.ArvMountExit
878         select {
879         case err := <-waitMount:
880                 runner.CrunchLog.Printf("arv-mount exited before container finished: %v", err)
881                 waitMount = nil
882                 runner.stop()
883         default:
884         }
885
886         // wait for stdout/stderr to complete
887         <-runner.loggingDone
888
889         return nil
890 }
891
892 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
893 func (runner *ContainerRunner) CaptureOutput() error {
894         if runner.finalState != "Complete" {
895                 return nil
896         }
897
898         if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
899                 // Output may have been set directly by the container, so
900                 // refresh the container record to check.
901                 err := runner.ArvClient.Get("containers", runner.Container.UUID,
902                         nil, &runner.Container)
903                 if err != nil {
904                         return err
905                 }
906                 if runner.Container.Output != "" {
907                         // Container output is already set.
908                         runner.OutputPDH = &runner.Container.Output
909                         return nil
910                 }
911         }
912
913         if runner.HostOutputDir == "" {
914                 return nil
915         }
916
917         _, err := os.Stat(runner.HostOutputDir)
918         if err != nil {
919                 return fmt.Errorf("While checking host output path: %v", err)
920         }
921
922         // Pre-populate output from the configured mount points
923         var binds []string
924         for bind, _ := range runner.Container.Mounts {
925                 binds = append(binds, bind)
926         }
927         sort.Strings(binds)
928
929         var manifestText string
930
931         collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
932         _, err = os.Stat(collectionMetafile)
933         if err != nil {
934                 // Regular directory
935
936                 // Find symlinks to arv-mounted files & dirs.
937                 err = filepath.Walk(runner.HostOutputDir, func(path string, info os.FileInfo, err error) error {
938                         if err != nil {
939                                 return err
940                         }
941                         if info.Mode()&os.ModeSymlink == 0 {
942                                 return nil
943                         }
944                         // read link to get container internal path
945                         var tgt string
946                         tgt, err = os.Readlink(path)
947                         if err != nil {
948                                 return err
949                         }
950                         if !strings.HasPrefix(tgt, "/") {
951                                 // Link is relative, don't handle it
952                                 return nil
953                         }
954                         // go through mounts and reverse map to collection reference
955                         for _, bind := range binds {
956                                 mnt := runner.Container.Mounts[bind]
957                                 if tgt == bind || strings.HasPrefix(tgt, bind+"/") && mnt.Kind == "collection" {
958                                         // get path relative to bind
959                                         sourceSuffix := tgt[len(bind):]
960                                         // get path relative to output dir
961                                         bindSuffix := path[len(runner.HostOutputDir):]
962
963                                         // Copy mount and adjust the path to add path relative to the bind
964                                         adjustedMount := mnt
965                                         adjustedMount.Path = filepath.Join(adjustedMount.Path, sourceSuffix)
966
967                                         // get manifest text
968                                         var m string
969                                         m, err = runner.getCollectionManifestForPath(adjustedMount, bindSuffix)
970                                         if err != nil {
971                                                 return err
972                                         }
973                                         manifestText = manifestText + m
974                                         // delete symlink so WriteTree won't try to to dereference it.
975                                         os.Remove(path)
976                                         return nil
977                                 }
978                         }
979                         return nil
980                 })
981                 if err != nil {
982                         return fmt.Errorf("While checking output symlinks: %v", err)
983                 }
984
985                 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
986                 var m string
987                 m, err = cw.WriteTree(runner.HostOutputDir, runner.CrunchLog.Logger)
988                 manifestText = manifestText + m
989                 if err != nil {
990                         return fmt.Errorf("While uploading output files: %v", err)
991                 }
992         } else {
993                 // FUSE mount directory
994                 file, openerr := os.Open(collectionMetafile)
995                 if openerr != nil {
996                         return fmt.Errorf("While opening FUSE metafile: %v", err)
997                 }
998                 defer file.Close()
999
1000                 var rec arvados.Collection
1001                 err = json.NewDecoder(file).Decode(&rec)
1002                 if err != nil {
1003                         return fmt.Errorf("While reading FUSE metafile: %v", err)
1004                 }
1005                 manifestText = rec.ManifestText
1006         }
1007
1008         for _, bind := range binds {
1009                 mnt := runner.Container.Mounts[bind]
1010
1011                 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
1012
1013                 if bindSuffix == bind || len(bindSuffix) <= 0 {
1014                         // either does not start with OutputPath or is OutputPath itself
1015                         continue
1016                 }
1017
1018                 if mnt.ExcludeFromOutput == true {
1019                         continue
1020                 }
1021
1022                 // append to manifest_text
1023                 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
1024                 if err != nil {
1025                         return err
1026                 }
1027
1028                 manifestText = manifestText + m
1029         }
1030
1031         // Save output
1032         var response arvados.Collection
1033         manifest := manifest.Manifest{Text: manifestText}
1034         manifestText = manifest.Extract(".", ".").Text
1035         err = runner.ArvClient.Create("collections",
1036                 arvadosclient.Dict{
1037                         "ensure_unique_name": true,
1038                         "collection": arvadosclient.Dict{
1039                                 "is_trashed":    true,
1040                                 "name":          "output for " + runner.Container.UUID,
1041                                 "manifest_text": manifestText}},
1042                 &response)
1043         if err != nil {
1044                 return fmt.Errorf("While creating output collection: %v", err)
1045         }
1046         runner.OutputPDH = &response.PortableDataHash
1047         return nil
1048 }
1049
1050 var outputCollections = make(map[string]arvados.Collection)
1051
1052 // Fetch the collection for the mnt.PortableDataHash
1053 // Return the manifest_text fragment corresponding to the specified mnt.Path
1054 //  after making any required updates.
1055 //  Ex:
1056 //    If mnt.Path is not specified,
1057 //      return the entire manifest_text after replacing any "." with bindSuffix
1058 //    If mnt.Path corresponds to one stream,
1059 //      return the manifest_text for that stream after replacing that stream name with bindSuffix
1060 //    Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1061 //      for that stream after replacing stream name with bindSuffix minus the last word
1062 //      and the file name with last word of the bindSuffix
1063 //  Allowed path examples:
1064 //    "path":"/"
1065 //    "path":"/subdir1"
1066 //    "path":"/subdir1/subdir2"
1067 //    "path":"/subdir/filename" etc
1068 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1069         collection := outputCollections[mnt.PortableDataHash]
1070         if collection.PortableDataHash == "" {
1071                 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1072                 if err != nil {
1073                         return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1074                 }
1075                 outputCollections[mnt.PortableDataHash] = collection
1076         }
1077
1078         if collection.ManifestText == "" {
1079                 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1080                 return "", nil
1081         }
1082
1083         mft := manifest.Manifest{Text: collection.ManifestText}
1084         extracted := mft.Extract(mnt.Path, bindSuffix)
1085         if extracted.Err != nil {
1086                 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1087         }
1088         return extracted.Text, nil
1089 }
1090
1091 func (runner *ContainerRunner) CleanupDirs() {
1092         if runner.ArvMount != nil {
1093                 umount := exec.Command("fusermount", "-z", "-u", runner.ArvMountPoint)
1094                 umnterr := umount.Run()
1095                 if umnterr != nil {
1096                         runner.CrunchLog.Printf("While running fusermount: %v", umnterr)
1097                 }
1098
1099                 mnterr := <-runner.ArvMountExit
1100                 if mnterr != nil {
1101                         runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
1102                 }
1103         }
1104
1105         for _, tmpdir := range runner.CleanupTempDir {
1106                 rmerr := os.RemoveAll(tmpdir)
1107                 if rmerr != nil {
1108                         runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1109                 }
1110         }
1111 }
1112
1113 // CommitLogs posts the collection containing the final container logs.
1114 func (runner *ContainerRunner) CommitLogs() error {
1115         runner.CrunchLog.Print(runner.finalState)
1116         runner.CrunchLog.Close()
1117
1118         // Closing CrunchLog above allows it to be committed to Keep at this
1119         // point, but re-open crunch log with ArvClient in case there are any
1120         // other further (such as failing to write the log to Keep!) while
1121         // shutting down
1122         runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1123                 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1124
1125         if runner.LogsPDH != nil {
1126                 // If we have already assigned something to LogsPDH,
1127                 // we must be closing the re-opened log, which won't
1128                 // end up getting attached to the container record and
1129                 // therefore doesn't need to be saved as a collection
1130                 // -- it exists only to send logs to other channels.
1131                 return nil
1132         }
1133
1134         mt, err := runner.LogCollection.ManifestText()
1135         if err != nil {
1136                 return fmt.Errorf("While creating log manifest: %v", err)
1137         }
1138
1139         var response arvados.Collection
1140         err = runner.ArvClient.Create("collections",
1141                 arvadosclient.Dict{
1142                         "ensure_unique_name": true,
1143                         "collection": arvadosclient.Dict{
1144                                 "is_trashed":    true,
1145                                 "name":          "logs for " + runner.Container.UUID,
1146                                 "manifest_text": mt}},
1147                 &response)
1148         if err != nil {
1149                 return fmt.Errorf("While creating log collection: %v", err)
1150         }
1151         runner.LogsPDH = &response.PortableDataHash
1152         return nil
1153 }
1154
1155 // UpdateContainerRunning updates the container state to "Running"
1156 func (runner *ContainerRunner) UpdateContainerRunning() error {
1157         runner.cStateLock.Lock()
1158         defer runner.cStateLock.Unlock()
1159         if runner.cCancelled {
1160                 return ErrCancelled
1161         }
1162         return runner.ArvClient.Update("containers", runner.Container.UUID,
1163                 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1164 }
1165
1166 // ContainerToken returns the api_token the container (and any
1167 // arv-mount processes) are allowed to use.
1168 func (runner *ContainerRunner) ContainerToken() (string, error) {
1169         if runner.token != "" {
1170                 return runner.token, nil
1171         }
1172
1173         var auth arvados.APIClientAuthorization
1174         err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1175         if err != nil {
1176                 return "", err
1177         }
1178         runner.token = auth.APIToken
1179         return runner.token, nil
1180 }
1181
1182 // UpdateContainerComplete updates the container record state on API
1183 // server to "Complete" or "Cancelled"
1184 func (runner *ContainerRunner) UpdateContainerFinal() error {
1185         update := arvadosclient.Dict{}
1186         update["state"] = runner.finalState
1187         if runner.LogsPDH != nil {
1188                 update["log"] = *runner.LogsPDH
1189         }
1190         if runner.finalState == "Complete" {
1191                 if runner.ExitCode != nil {
1192                         update["exit_code"] = *runner.ExitCode
1193                 }
1194                 if runner.OutputPDH != nil {
1195                         update["output"] = *runner.OutputPDH
1196                 }
1197         }
1198         return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1199 }
1200
1201 // IsCancelled returns the value of Cancelled, with goroutine safety.
1202 func (runner *ContainerRunner) IsCancelled() bool {
1203         runner.cStateLock.Lock()
1204         defer runner.cStateLock.Unlock()
1205         return runner.cCancelled
1206 }
1207
1208 // NewArvLogWriter creates an ArvLogWriter
1209 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1210         return &ArvLogWriter{ArvClient: runner.ArvClient, UUID: runner.Container.UUID, loggingStream: name,
1211                 writeCloser: runner.LogCollection.Open(name + ".txt")}
1212 }
1213
1214 // Run the full container lifecycle.
1215 func (runner *ContainerRunner) Run() (err error) {
1216         runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1217
1218         hostname, hosterr := os.Hostname()
1219         if hosterr != nil {
1220                 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1221         } else {
1222                 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1223         }
1224
1225         // Clean up temporary directories _after_ finalizing
1226         // everything (if we've made any by then)
1227         defer runner.CleanupDirs()
1228
1229         runner.finalState = "Queued"
1230
1231         defer func() {
1232                 // checkErr prints e (unless it's nil) and sets err to
1233                 // e (unless err is already non-nil). Thus, if err
1234                 // hasn't already been assigned when Run() returns,
1235                 // this cleanup func will cause Run() to return the
1236                 // first non-nil error that is passed to checkErr().
1237                 checkErr := func(e error) {
1238                         if e == nil {
1239                                 return
1240                         }
1241                         runner.CrunchLog.Print(e)
1242                         if err == nil {
1243                                 err = e
1244                         }
1245                         if runner.finalState == "Complete" {
1246                                 // There was an error in the finalization.
1247                                 runner.finalState = "Cancelled"
1248                         }
1249                 }
1250
1251                 // Log the error encountered in Run(), if any
1252                 checkErr(err)
1253
1254                 if runner.finalState == "Queued" {
1255                         runner.CrunchLog.Close()
1256                         runner.UpdateContainerFinal()
1257                         return
1258                 }
1259
1260                 if runner.IsCancelled() {
1261                         runner.finalState = "Cancelled"
1262                         // but don't return yet -- we still want to
1263                         // capture partial output and write logs
1264                 }
1265
1266                 checkErr(runner.CaptureOutput())
1267                 checkErr(runner.CommitLogs())
1268                 checkErr(runner.UpdateContainerFinal())
1269
1270                 // The real log is already closed, but then we opened
1271                 // a new one in case we needed to log anything while
1272                 // finalizing.
1273                 runner.CrunchLog.Close()
1274         }()
1275
1276         err = runner.ArvClient.Get("containers", runner.Container.UUID, nil, &runner.Container)
1277         if err != nil {
1278                 err = fmt.Errorf("While getting container record: %v", err)
1279                 return
1280         }
1281
1282         // setup signal handling
1283         runner.SetupSignals()
1284
1285         // check for and/or load image
1286         err = runner.LoadImage()
1287         if err != nil {
1288                 runner.finalState = "Cancelled"
1289                 err = fmt.Errorf("While loading container image: %v", err)
1290                 return
1291         }
1292
1293         // set up FUSE mount and binds
1294         err = runner.SetupMounts()
1295         if err != nil {
1296                 runner.finalState = "Cancelled"
1297                 err = fmt.Errorf("While setting up mounts: %v", err)
1298                 return
1299         }
1300
1301         err = runner.CreateContainer()
1302         if err != nil {
1303                 return
1304         }
1305
1306         // Gather and record node information
1307         err = runner.LogNodeInfo()
1308         if err != nil {
1309                 return
1310         }
1311         // Save container.json record on log collection
1312         err = runner.LogContainerRecord()
1313         if err != nil {
1314                 return
1315         }
1316
1317         runner.StartCrunchstat()
1318
1319         if runner.IsCancelled() {
1320                 return
1321         }
1322
1323         err = runner.UpdateContainerRunning()
1324         if err != nil {
1325                 return
1326         }
1327         runner.finalState = "Cancelled"
1328
1329         err = runner.StartContainer()
1330         if err != nil {
1331                 return
1332         }
1333
1334         err = runner.WaitFinish()
1335         if err == nil {
1336                 runner.finalState = "Complete"
1337         }
1338         return
1339 }
1340
1341 // NewContainerRunner creates a new container runner.
1342 func NewContainerRunner(api IArvadosClient,
1343         kc IKeepClient,
1344         docker ThinDockerClient,
1345         containerUUID string) *ContainerRunner {
1346
1347         cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1348         cr.NewLogWriter = cr.NewArvLogWriter
1349         cr.RunArvMount = cr.ArvMountCmd
1350         cr.MkTempDir = ioutil.TempDir
1351         cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1352         cr.Container.UUID = containerUUID
1353         cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1354         cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1355
1356         loadLogThrottleParams(api)
1357
1358         return cr
1359 }
1360
1361 func main() {
1362         statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1363         cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1364         cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1365         cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1366         caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1367         enableNetwork := flag.String("container-enable-networking", "default",
1368                 `Specify if networking should be enabled for container.  One of 'default', 'always':
1369         default: only enable networking if container requests it.
1370         always:  containers always have networking enabled
1371         `)
1372         networkMode := flag.String("container-network-mode", "default",
1373                 `Set networking mode for container.  Corresponds to Docker network mode (--net).
1374         `)
1375         flag.Parse()
1376
1377         containerId := flag.Arg(0)
1378
1379         if *caCertsPath != "" {
1380                 arvadosclient.CertFiles = []string{*caCertsPath}
1381         }
1382
1383         api, err := arvadosclient.MakeArvadosClient()
1384         if err != nil {
1385                 log.Fatalf("%s: %v", containerId, err)
1386         }
1387         api.Retries = 8
1388
1389         var kc *keepclient.KeepClient
1390         kc, err = keepclient.MakeKeepClient(api)
1391         if err != nil {
1392                 log.Fatalf("%s: %v", containerId, err)
1393         }
1394         kc.Retries = 4
1395
1396         var docker *dockerclient.Client
1397         // API version 1.21 corresponds to Docker 1.9, which is currently the
1398         // minimum version we want to support.
1399         docker, err = dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1400         if err != nil {
1401                 log.Fatalf("%s: %v", containerId, err)
1402         }
1403
1404         dockerClientProxy := ThinDockerClientProxy{Docker: docker}
1405
1406         cr := NewContainerRunner(api, kc, dockerClientProxy, containerId)
1407         cr.statInterval = *statInterval
1408         cr.cgroupRoot = *cgroupRoot
1409         cr.expectCgroupParent = *cgroupParent
1410         cr.enableNetwork = *enableNetwork
1411         cr.networkMode = *networkMode
1412         if *cgroupParentSubsystem != "" {
1413                 p := findCgroup(*cgroupParentSubsystem)
1414                 cr.setCgroupParent = p
1415                 cr.expectCgroupParent = p
1416         }
1417
1418         err = cr.Run()
1419         if err != nil {
1420                 log.Fatalf("%s: %v", containerId, err)
1421         }
1422
1423 }