11693: Only check collection mounts when determining whether to call
[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, mnt := range runner.Container.Mounts {
925                 if mnt.Kind == "collection" {
926                         binds = append(binds, bind)
927                 }
928         }
929         sort.Strings(binds)
930
931         var manifestText string
932
933         collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
934         _, err = os.Stat(collectionMetafile)
935         if err != nil {
936                 // Regular directory
937
938                 // Find symlinks to arv-mounted files & dirs.
939                 err = filepath.Walk(runner.HostOutputDir, func(path string, info os.FileInfo, err error) error {
940                         if err != nil {
941                                 return err
942                         }
943                         if info.Mode()&os.ModeSymlink == 0 {
944                                 return nil
945                         }
946                         // read link to get container internal path
947                         // only support 1 level of symlinking here.
948                         var tgt string
949                         tgt, err = os.Readlink(path)
950                         if err != nil {
951                                 return err
952                         }
953
954                         // get path relative to output dir
955                         outputSuffix := path[len(runner.HostOutputDir):]
956
957                         if strings.HasPrefix(tgt, "/") {
958                                 // go through mounts and try reverse map to collection reference
959                                 for _, bind := range binds {
960                                         mnt := runner.Container.Mounts[bind]
961                                         if tgt == bind || strings.HasPrefix(tgt, bind+"/") {
962                                                 // get path relative to bind
963                                                 targetSuffix := tgt[len(bind):]
964
965                                                 // Copy mount and adjust the path to add path relative to the bind
966                                                 adjustedMount := mnt
967                                                 adjustedMount.Path = filepath.Join(adjustedMount.Path, targetSuffix)
968
969                                                 // get manifest text
970                                                 var m string
971                                                 m, err = runner.getCollectionManifestForPath(adjustedMount, outputSuffix)
972                                                 if err != nil {
973                                                         return err
974                                                 }
975                                                 manifestText = manifestText + m
976                                                 // delete symlink so WriteTree won't try to to dereference it.
977                                                 os.Remove(path)
978                                                 return nil
979                                         }
980                                 }
981                         }
982
983                         // Not a link to a mount.  Must be dereferencible and
984                         // point into the output directory.
985                         tgt, err = filepath.EvalSymlinks(path)
986                         if err != nil {
987                                 os.Remove(path)
988                                 return err
989                         }
990
991                         // Symlink target must be within the output directory otherwise it's an error.
992                         if !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
993                                 os.Remove(path)
994                                 return fmt.Errorf("Output directory symlink %q points to invalid location %q, must point to mount or output directory.",
995                                         outputSuffix, tgt)
996                         }
997                         return nil
998                 })
999                 if err != nil {
1000                         return fmt.Errorf("While checking output symlinks: %v", err)
1001                 }
1002
1003                 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
1004                 var m string
1005                 m, err = cw.WriteTree(runner.HostOutputDir, runner.CrunchLog.Logger)
1006                 manifestText = manifestText + m
1007                 if err != nil {
1008                         return fmt.Errorf("While uploading output files: %v", err)
1009                 }
1010         } else {
1011                 // FUSE mount directory
1012                 file, openerr := os.Open(collectionMetafile)
1013                 if openerr != nil {
1014                         return fmt.Errorf("While opening FUSE metafile: %v", err)
1015                 }
1016                 defer file.Close()
1017
1018                 var rec arvados.Collection
1019                 err = json.NewDecoder(file).Decode(&rec)
1020                 if err != nil {
1021                         return fmt.Errorf("While reading FUSE metafile: %v", err)
1022                 }
1023                 manifestText = rec.ManifestText
1024         }
1025
1026         for _, bind := range binds {
1027                 mnt := runner.Container.Mounts[bind]
1028
1029                 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
1030
1031                 if bindSuffix == bind || len(bindSuffix) <= 0 {
1032                         // either does not start with OutputPath or is OutputPath itself
1033                         continue
1034                 }
1035
1036                 if mnt.ExcludeFromOutput == true {
1037                         continue
1038                 }
1039
1040                 // append to manifest_text
1041                 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
1042                 if err != nil {
1043                         return err
1044                 }
1045
1046                 manifestText = manifestText + m
1047         }
1048
1049         // Save output
1050         var response arvados.Collection
1051         manifest := manifest.Manifest{Text: manifestText}
1052         manifestText = manifest.Extract(".", ".").Text
1053         err = runner.ArvClient.Create("collections",
1054                 arvadosclient.Dict{
1055                         "ensure_unique_name": true,
1056                         "collection": arvadosclient.Dict{
1057                                 "is_trashed":    true,
1058                                 "name":          "output for " + runner.Container.UUID,
1059                                 "manifest_text": manifestText}},
1060                 &response)
1061         if err != nil {
1062                 return fmt.Errorf("While creating output collection: %v", err)
1063         }
1064         runner.OutputPDH = &response.PortableDataHash
1065         return nil
1066 }
1067
1068 var outputCollections = make(map[string]arvados.Collection)
1069
1070 // Fetch the collection for the mnt.PortableDataHash
1071 // Return the manifest_text fragment corresponding to the specified mnt.Path
1072 //  after making any required updates.
1073 //  Ex:
1074 //    If mnt.Path is not specified,
1075 //      return the entire manifest_text after replacing any "." with bindSuffix
1076 //    If mnt.Path corresponds to one stream,
1077 //      return the manifest_text for that stream after replacing that stream name with bindSuffix
1078 //    Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1079 //      for that stream after replacing stream name with bindSuffix minus the last word
1080 //      and the file name with last word of the bindSuffix
1081 //  Allowed path examples:
1082 //    "path":"/"
1083 //    "path":"/subdir1"
1084 //    "path":"/subdir1/subdir2"
1085 //    "path":"/subdir/filename" etc
1086 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1087         collection := outputCollections[mnt.PortableDataHash]
1088         if collection.PortableDataHash == "" {
1089                 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1090                 if err != nil {
1091                         return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1092                 }
1093                 outputCollections[mnt.PortableDataHash] = collection
1094         }
1095
1096         if collection.ManifestText == "" {
1097                 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1098                 return "", nil
1099         }
1100
1101         mft := manifest.Manifest{Text: collection.ManifestText}
1102         extracted := mft.Extract(mnt.Path, bindSuffix)
1103         if extracted.Err != nil {
1104                 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1105         }
1106         return extracted.Text, nil
1107 }
1108
1109 func (runner *ContainerRunner) CleanupDirs() {
1110         if runner.ArvMount != nil {
1111                 umount := exec.Command("fusermount", "-z", "-u", runner.ArvMountPoint)
1112                 umnterr := umount.Run()
1113                 if umnterr != nil {
1114                         runner.CrunchLog.Printf("While running fusermount: %v", umnterr)
1115                 }
1116
1117                 mnterr := <-runner.ArvMountExit
1118                 if mnterr != nil {
1119                         runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
1120                 }
1121         }
1122
1123         for _, tmpdir := range runner.CleanupTempDir {
1124                 rmerr := os.RemoveAll(tmpdir)
1125                 if rmerr != nil {
1126                         runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1127                 }
1128         }
1129 }
1130
1131 // CommitLogs posts the collection containing the final container logs.
1132 func (runner *ContainerRunner) CommitLogs() error {
1133         runner.CrunchLog.Print(runner.finalState)
1134         runner.CrunchLog.Close()
1135
1136         // Closing CrunchLog above allows it to be committed to Keep at this
1137         // point, but re-open crunch log with ArvClient in case there are any
1138         // other further (such as failing to write the log to Keep!) while
1139         // shutting down
1140         runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1141                 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1142
1143         if runner.LogsPDH != nil {
1144                 // If we have already assigned something to LogsPDH,
1145                 // we must be closing the re-opened log, which won't
1146                 // end up getting attached to the container record and
1147                 // therefore doesn't need to be saved as a collection
1148                 // -- it exists only to send logs to other channels.
1149                 return nil
1150         }
1151
1152         mt, err := runner.LogCollection.ManifestText()
1153         if err != nil {
1154                 return fmt.Errorf("While creating log manifest: %v", err)
1155         }
1156
1157         var response arvados.Collection
1158         err = runner.ArvClient.Create("collections",
1159                 arvadosclient.Dict{
1160                         "ensure_unique_name": true,
1161                         "collection": arvadosclient.Dict{
1162                                 "is_trashed":    true,
1163                                 "name":          "logs for " + runner.Container.UUID,
1164                                 "manifest_text": mt}},
1165                 &response)
1166         if err != nil {
1167                 return fmt.Errorf("While creating log collection: %v", err)
1168         }
1169         runner.LogsPDH = &response.PortableDataHash
1170         return nil
1171 }
1172
1173 // UpdateContainerRunning updates the container state to "Running"
1174 func (runner *ContainerRunner) UpdateContainerRunning() error {
1175         runner.cStateLock.Lock()
1176         defer runner.cStateLock.Unlock()
1177         if runner.cCancelled {
1178                 return ErrCancelled
1179         }
1180         return runner.ArvClient.Update("containers", runner.Container.UUID,
1181                 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1182 }
1183
1184 // ContainerToken returns the api_token the container (and any
1185 // arv-mount processes) are allowed to use.
1186 func (runner *ContainerRunner) ContainerToken() (string, error) {
1187         if runner.token != "" {
1188                 return runner.token, nil
1189         }
1190
1191         var auth arvados.APIClientAuthorization
1192         err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1193         if err != nil {
1194                 return "", err
1195         }
1196         runner.token = auth.APIToken
1197         return runner.token, nil
1198 }
1199
1200 // UpdateContainerComplete updates the container record state on API
1201 // server to "Complete" or "Cancelled"
1202 func (runner *ContainerRunner) UpdateContainerFinal() error {
1203         update := arvadosclient.Dict{}
1204         update["state"] = runner.finalState
1205         if runner.LogsPDH != nil {
1206                 update["log"] = *runner.LogsPDH
1207         }
1208         if runner.finalState == "Complete" {
1209                 if runner.ExitCode != nil {
1210                         update["exit_code"] = *runner.ExitCode
1211                 }
1212                 if runner.OutputPDH != nil {
1213                         update["output"] = *runner.OutputPDH
1214                 }
1215         }
1216         return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1217 }
1218
1219 // IsCancelled returns the value of Cancelled, with goroutine safety.
1220 func (runner *ContainerRunner) IsCancelled() bool {
1221         runner.cStateLock.Lock()
1222         defer runner.cStateLock.Unlock()
1223         return runner.cCancelled
1224 }
1225
1226 // NewArvLogWriter creates an ArvLogWriter
1227 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1228         return &ArvLogWriter{ArvClient: runner.ArvClient, UUID: runner.Container.UUID, loggingStream: name,
1229                 writeCloser: runner.LogCollection.Open(name + ".txt")}
1230 }
1231
1232 // Run the full container lifecycle.
1233 func (runner *ContainerRunner) Run() (err error) {
1234         runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1235
1236         hostname, hosterr := os.Hostname()
1237         if hosterr != nil {
1238                 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1239         } else {
1240                 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1241         }
1242
1243         // Clean up temporary directories _after_ finalizing
1244         // everything (if we've made any by then)
1245         defer runner.CleanupDirs()
1246
1247         runner.finalState = "Queued"
1248
1249         defer func() {
1250                 // checkErr prints e (unless it's nil) and sets err to
1251                 // e (unless err is already non-nil). Thus, if err
1252                 // hasn't already been assigned when Run() returns,
1253                 // this cleanup func will cause Run() to return the
1254                 // first non-nil error that is passed to checkErr().
1255                 checkErr := func(e error) {
1256                         if e == nil {
1257                                 return
1258                         }
1259                         runner.CrunchLog.Print(e)
1260                         if err == nil {
1261                                 err = e
1262                         }
1263                         if runner.finalState == "Complete" {
1264                                 // There was an error in the finalization.
1265                                 runner.finalState = "Cancelled"
1266                         }
1267                 }
1268
1269                 // Log the error encountered in Run(), if any
1270                 checkErr(err)
1271
1272                 if runner.finalState == "Queued" {
1273                         runner.CrunchLog.Close()
1274                         runner.UpdateContainerFinal()
1275                         return
1276                 }
1277
1278                 if runner.IsCancelled() {
1279                         runner.finalState = "Cancelled"
1280                         // but don't return yet -- we still want to
1281                         // capture partial output and write logs
1282                 }
1283
1284                 checkErr(runner.CaptureOutput())
1285                 checkErr(runner.CommitLogs())
1286                 checkErr(runner.UpdateContainerFinal())
1287
1288                 // The real log is already closed, but then we opened
1289                 // a new one in case we needed to log anything while
1290                 // finalizing.
1291                 runner.CrunchLog.Close()
1292         }()
1293
1294         err = runner.ArvClient.Get("containers", runner.Container.UUID, nil, &runner.Container)
1295         if err != nil {
1296                 err = fmt.Errorf("While getting container record: %v", err)
1297                 return
1298         }
1299
1300         // setup signal handling
1301         runner.SetupSignals()
1302
1303         // check for and/or load image
1304         err = runner.LoadImage()
1305         if err != nil {
1306                 runner.finalState = "Cancelled"
1307                 err = fmt.Errorf("While loading container image: %v", err)
1308                 return
1309         }
1310
1311         // set up FUSE mount and binds
1312         err = runner.SetupMounts()
1313         if err != nil {
1314                 runner.finalState = "Cancelled"
1315                 err = fmt.Errorf("While setting up mounts: %v", err)
1316                 return
1317         }
1318
1319         err = runner.CreateContainer()
1320         if err != nil {
1321                 return
1322         }
1323
1324         // Gather and record node information
1325         err = runner.LogNodeInfo()
1326         if err != nil {
1327                 return
1328         }
1329         // Save container.json record on log collection
1330         err = runner.LogContainerRecord()
1331         if err != nil {
1332                 return
1333         }
1334
1335         runner.StartCrunchstat()
1336
1337         if runner.IsCancelled() {
1338                 return
1339         }
1340
1341         err = runner.UpdateContainerRunning()
1342         if err != nil {
1343                 return
1344         }
1345         runner.finalState = "Cancelled"
1346
1347         err = runner.StartContainer()
1348         if err != nil {
1349                 return
1350         }
1351
1352         err = runner.WaitFinish()
1353         if err == nil {
1354                 runner.finalState = "Complete"
1355         }
1356         return
1357 }
1358
1359 // NewContainerRunner creates a new container runner.
1360 func NewContainerRunner(api IArvadosClient,
1361         kc IKeepClient,
1362         docker ThinDockerClient,
1363         containerUUID string) *ContainerRunner {
1364
1365         cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1366         cr.NewLogWriter = cr.NewArvLogWriter
1367         cr.RunArvMount = cr.ArvMountCmd
1368         cr.MkTempDir = ioutil.TempDir
1369         cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1370         cr.Container.UUID = containerUUID
1371         cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1372         cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1373
1374         loadLogThrottleParams(api)
1375
1376         return cr
1377 }
1378
1379 func main() {
1380         statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1381         cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1382         cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1383         cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1384         caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1385         enableNetwork := flag.String("container-enable-networking", "default",
1386                 `Specify if networking should be enabled for container.  One of 'default', 'always':
1387         default: only enable networking if container requests it.
1388         always:  containers always have networking enabled
1389         `)
1390         networkMode := flag.String("container-network-mode", "default",
1391                 `Set networking mode for container.  Corresponds to Docker network mode (--net).
1392         `)
1393         flag.Parse()
1394
1395         containerId := flag.Arg(0)
1396
1397         if *caCertsPath != "" {
1398                 arvadosclient.CertFiles = []string{*caCertsPath}
1399         }
1400
1401         api, err := arvadosclient.MakeArvadosClient()
1402         if err != nil {
1403                 log.Fatalf("%s: %v", containerId, err)
1404         }
1405         api.Retries = 8
1406
1407         var kc *keepclient.KeepClient
1408         kc, err = keepclient.MakeKeepClient(api)
1409         if err != nil {
1410                 log.Fatalf("%s: %v", containerId, err)
1411         }
1412         kc.Retries = 4
1413
1414         var docker *dockerclient.Client
1415         // API version 1.21 corresponds to Docker 1.9, which is currently the
1416         // minimum version we want to support.
1417         docker, err = dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1418         if err != nil {
1419                 log.Fatalf("%s: %v", containerId, err)
1420         }
1421
1422         dockerClientProxy := ThinDockerClientProxy{Docker: docker}
1423
1424         cr := NewContainerRunner(api, kc, dockerClientProxy, containerId)
1425         cr.statInterval = *statInterval
1426         cr.cgroupRoot = *cgroupRoot
1427         cr.expectCgroupParent = *cgroupParent
1428         cr.enableNetwork = *enableNetwork
1429         cr.networkMode = *networkMode
1430         if *cgroupParentSubsystem != "" {
1431                 p := findCgroup(*cgroupParentSubsystem)
1432                 cr.setCgroupParent = p
1433                 cr.expectCgroupParent = p
1434         }
1435
1436         err = cr.Run()
1437         if err != nil {
1438                 log.Fatalf("%s: %v", containerId, err)
1439         }
1440
1441 }