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