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