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