Merge branch '11807-yaml-to-json'
[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                 infoCommand{
596                         label: "Host Information",
597                         cmd:   []string{"uname", "-a"},
598                 },
599                 infoCommand{
600                         label: "CPU Information",
601                         cmd:   []string{"cat", "/proc/cpuinfo"},
602                 },
603                 infoCommand{
604                         label: "Memory Information",
605                         cmd:   []string{"cat", "/proc/meminfo"},
606                 },
607                 infoCommand{
608                         label: "Disk Space",
609                         cmd:   []string{"df", "-m", "/", os.TempDir()},
610                 },
611                 infoCommand{
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         // Read the API server response as []byte
654         json_bytes, err := ioutil.ReadAll(reader)
655         if err != nil {
656                 return fmt.Errorf("While reading container record API server response: %v", err)
657         }
658         // Decode the JSON []byte
659         var cr map[string]interface{}
660         if err = json.Unmarshal(json_bytes, &cr); err != nil {
661                 return fmt.Errorf("While decoding the container record JSON response: %v", err)
662         }
663         // Re-encode it using indentation to improve readability
664         enc := json.NewEncoder(w)
665         enc.SetIndent("", "    ")
666         if err = enc.Encode(cr); err != nil {
667                 return fmt.Errorf("While logging the JSON container record: %v", err)
668         }
669         err = w.Close()
670         if err != nil {
671                 return fmt.Errorf("While closing container.json log: %v", err)
672         }
673         return nil
674 }
675
676 // AttachStreams connects the docker container stdin, stdout and stderr logs
677 // to the Arvados logger which logs to Keep and the API server logs table.
678 func (runner *ContainerRunner) AttachStreams() (err error) {
679
680         runner.CrunchLog.Print("Attaching container streams")
681
682         // If stdin mount is provided, attach it to the docker container
683         var stdinRdr arvados.File
684         var stdinJson []byte
685         if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
686                 if stdinMnt.Kind == "collection" {
687                         var stdinColl arvados.Collection
688                         collId := stdinMnt.UUID
689                         if collId == "" {
690                                 collId = stdinMnt.PortableDataHash
691                         }
692                         err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
693                         if err != nil {
694                                 return fmt.Errorf("While getting stding collection: %v", err)
695                         }
696
697                         stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
698                         if os.IsNotExist(err) {
699                                 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
700                         } else if err != nil {
701                                 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
702                         }
703                 } else if stdinMnt.Kind == "json" {
704                         stdinJson, err = json.Marshal(stdinMnt.Content)
705                         if err != nil {
706                                 return fmt.Errorf("While encoding stdin json data: %v", err)
707                         }
708                 }
709         }
710
711         stdinUsed := stdinRdr != nil || len(stdinJson) != 0
712         response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
713                 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
714         if err != nil {
715                 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
716         }
717
718         runner.loggingDone = make(chan bool)
719
720         if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
721                 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
722                 if err != nil {
723                         return err
724                 }
725                 runner.Stdout = stdoutFile
726         } else {
727                 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
728         }
729
730         if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
731                 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
732                 if err != nil {
733                         return err
734                 }
735                 runner.Stderr = stderrFile
736         } else {
737                 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
738         }
739
740         if stdinRdr != nil {
741                 go func() {
742                         _, err := io.Copy(response.Conn, stdinRdr)
743                         if err != nil {
744                                 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
745                                 runner.stop()
746                         }
747                         stdinRdr.Close()
748                         response.CloseWrite()
749                 }()
750         } else if len(stdinJson) != 0 {
751                 go func() {
752                         _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
753                         if err != nil {
754                                 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
755                                 runner.stop()
756                         }
757                         response.CloseWrite()
758                 }()
759         }
760
761         go runner.ProcessDockerAttach(response.Reader)
762
763         return nil
764 }
765
766 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
767         stdoutPath := mntPath[len(runner.Container.OutputPath):]
768         index := strings.LastIndex(stdoutPath, "/")
769         if index > 0 {
770                 subdirs := stdoutPath[:index]
771                 if subdirs != "" {
772                         st, err := os.Stat(runner.HostOutputDir)
773                         if err != nil {
774                                 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
775                         }
776                         stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
777                         err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
778                         if err != nil {
779                                 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
780                         }
781                 }
782         }
783         stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
784         if err != nil {
785                 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
786         }
787
788         return stdoutFile, nil
789 }
790
791 // CreateContainer creates the docker container.
792 func (runner *ContainerRunner) CreateContainer() error {
793         runner.CrunchLog.Print("Creating Docker container")
794
795         runner.ContainerConfig.Cmd = runner.Container.Command
796         if runner.Container.Cwd != "." {
797                 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
798         }
799
800         for k, v := range runner.Container.Environment {
801                 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
802         }
803
804         runner.ContainerConfig.Volumes = runner.Volumes
805
806         runner.HostConfig = dockercontainer.HostConfig{
807                 Binds: runner.Binds,
808                 LogConfig: dockercontainer.LogConfig{
809                         Type: "none",
810                 },
811                 Resources: dockercontainer.Resources{
812                         CgroupParent: runner.setCgroupParent,
813                 },
814         }
815
816         if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
817                 tok, err := runner.ContainerToken()
818                 if err != nil {
819                         return err
820                 }
821                 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
822                         "ARVADOS_API_TOKEN="+tok,
823                         "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
824                         "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
825                 )
826                 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
827         } else {
828                 if runner.enableNetwork == "always" {
829                         runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
830                 } else {
831                         runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
832                 }
833         }
834
835         _, stdinUsed := runner.Container.Mounts["stdin"]
836         runner.ContainerConfig.OpenStdin = stdinUsed
837         runner.ContainerConfig.StdinOnce = stdinUsed
838         runner.ContainerConfig.AttachStdin = stdinUsed
839         runner.ContainerConfig.AttachStdout = true
840         runner.ContainerConfig.AttachStderr = true
841
842         createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
843         if err != nil {
844                 return fmt.Errorf("While creating container: %v", err)
845         }
846
847         runner.ContainerID = createdBody.ID
848
849         return runner.AttachStreams()
850 }
851
852 // StartContainer starts the docker container created by CreateContainer.
853 func (runner *ContainerRunner) StartContainer() error {
854         runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
855         runner.cStateLock.Lock()
856         defer runner.cStateLock.Unlock()
857         if runner.cCancelled {
858                 return ErrCancelled
859         }
860         err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
861                 dockertypes.ContainerStartOptions{})
862         if err != nil {
863                 return fmt.Errorf("could not start container: %v", err)
864         }
865         runner.cStarted = true
866         return nil
867 }
868
869 // WaitFinish waits for the container to terminate, capture the exit code, and
870 // close the stdout/stderr logging.
871 func (runner *ContainerRunner) WaitFinish() (err error) {
872         runner.CrunchLog.Print("Waiting for container to finish")
873
874         waitOk, waitErr := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID, "not-running")
875
876         var waitBody dockercontainer.ContainerWaitOKBody
877         select {
878         case waitBody = <-waitOk:
879         case err = <-waitErr:
880         }
881
882         if err != nil {
883                 return fmt.Errorf("container wait: %v", err)
884         }
885
886         runner.CrunchLog.Printf("Container exited with code: %v", waitBody.StatusCode)
887         code := int(waitBody.StatusCode)
888         runner.ExitCode = &code
889
890         waitMount := runner.ArvMountExit
891         select {
892         case err = <-waitMount:
893                 runner.CrunchLog.Printf("arv-mount exited before container finished: %v", err)
894                 waitMount = nil
895                 runner.stop()
896         default:
897         }
898
899         // wait for stdout/stderr to complete
900         <-runner.loggingDone
901
902         return nil
903 }
904
905 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
906 func (runner *ContainerRunner) CaptureOutput() error {
907         if runner.finalState != "Complete" {
908                 return nil
909         }
910
911         if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
912                 // Output may have been set directly by the container, so
913                 // refresh the container record to check.
914                 err := runner.ArvClient.Get("containers", runner.Container.UUID,
915                         nil, &runner.Container)
916                 if err != nil {
917                         return err
918                 }
919                 if runner.Container.Output != "" {
920                         // Container output is already set.
921                         runner.OutputPDH = &runner.Container.Output
922                         return nil
923                 }
924         }
925
926         if runner.HostOutputDir == "" {
927                 return nil
928         }
929
930         _, err := os.Stat(runner.HostOutputDir)
931         if err != nil {
932                 return fmt.Errorf("While checking host output path: %v", err)
933         }
934
935         // Pre-populate output from the configured mount points
936         var binds []string
937         for bind, mnt := range runner.Container.Mounts {
938                 if mnt.Kind == "collection" {
939                         binds = append(binds, bind)
940                 }
941         }
942         sort.Strings(binds)
943
944         var manifestText string
945
946         collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
947         _, err = os.Stat(collectionMetafile)
948         if err != nil {
949                 // Regular directory
950
951                 // Find symlinks to arv-mounted files & dirs.
952                 err = filepath.Walk(runner.HostOutputDir, func(path string, info os.FileInfo, err error) error {
953                         if err != nil {
954                                 return err
955                         }
956                         if info.Mode()&os.ModeSymlink == 0 {
957                                 return nil
958                         }
959                         // read link to get container internal path
960                         // only support 1 level of symlinking here.
961                         var tgt string
962                         tgt, err = os.Readlink(path)
963                         if err != nil {
964                                 return err
965                         }
966
967                         // get path relative to output dir
968                         outputSuffix := path[len(runner.HostOutputDir):]
969
970                         if strings.HasPrefix(tgt, "/") {
971                                 // go through mounts and try reverse map to collection reference
972                                 for _, bind := range binds {
973                                         mnt := runner.Container.Mounts[bind]
974                                         if tgt == bind || strings.HasPrefix(tgt, bind+"/") {
975                                                 // get path relative to bind
976                                                 targetSuffix := tgt[len(bind):]
977
978                                                 // Copy mount and adjust the path to add path relative to the bind
979                                                 adjustedMount := mnt
980                                                 adjustedMount.Path = filepath.Join(adjustedMount.Path, targetSuffix)
981
982                                                 // get manifest text
983                                                 var m string
984                                                 m, err = runner.getCollectionManifestForPath(adjustedMount, outputSuffix)
985                                                 if err != nil {
986                                                         return err
987                                                 }
988                                                 manifestText = manifestText + m
989                                                 // delete symlink so WriteTree won't try to to dereference it.
990                                                 os.Remove(path)
991                                                 return nil
992                                         }
993                                 }
994                         }
995
996                         // Not a link to a mount.  Must be dereferencible and
997                         // point into the output directory.
998                         tgt, err = filepath.EvalSymlinks(path)
999                         if err != nil {
1000                                 os.Remove(path)
1001                                 return err
1002                         }
1003
1004                         // Symlink target must be within the output directory otherwise it's an error.
1005                         if !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
1006                                 os.Remove(path)
1007                                 return fmt.Errorf("Output directory symlink %q points to invalid location %q, must point to mount or output directory.",
1008                                         outputSuffix, tgt)
1009                         }
1010                         return nil
1011                 })
1012                 if err != nil {
1013                         return fmt.Errorf("While checking output symlinks: %v", err)
1014                 }
1015
1016                 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
1017                 var m string
1018                 m, err = cw.WriteTree(runner.HostOutputDir, runner.CrunchLog.Logger)
1019                 manifestText = manifestText + m
1020                 if err != nil {
1021                         return fmt.Errorf("While uploading output files: %v", err)
1022                 }
1023         } else {
1024                 // FUSE mount directory
1025                 file, openerr := os.Open(collectionMetafile)
1026                 if openerr != nil {
1027                         return fmt.Errorf("While opening FUSE metafile: %v", err)
1028                 }
1029                 defer file.Close()
1030
1031                 var rec arvados.Collection
1032                 err = json.NewDecoder(file).Decode(&rec)
1033                 if err != nil {
1034                         return fmt.Errorf("While reading FUSE metafile: %v", err)
1035                 }
1036                 manifestText = rec.ManifestText
1037         }
1038
1039         for _, bind := range binds {
1040                 mnt := runner.Container.Mounts[bind]
1041
1042                 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
1043
1044                 if bindSuffix == bind || len(bindSuffix) <= 0 {
1045                         // either does not start with OutputPath or is OutputPath itself
1046                         continue
1047                 }
1048
1049                 if mnt.ExcludeFromOutput == true {
1050                         continue
1051                 }
1052
1053                 // append to manifest_text
1054                 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
1055                 if err != nil {
1056                         return err
1057                 }
1058
1059                 manifestText = manifestText + m
1060         }
1061
1062         // Save output
1063         var response arvados.Collection
1064         manifest := manifest.Manifest{Text: manifestText}
1065         manifestText = manifest.Extract(".", ".").Text
1066         err = runner.ArvClient.Create("collections",
1067                 arvadosclient.Dict{
1068                         "ensure_unique_name": true,
1069                         "collection": arvadosclient.Dict{
1070                                 "is_trashed":    true,
1071                                 "name":          "output for " + runner.Container.UUID,
1072                                 "manifest_text": manifestText}},
1073                 &response)
1074         if err != nil {
1075                 return fmt.Errorf("While creating output collection: %v", err)
1076         }
1077         runner.OutputPDH = &response.PortableDataHash
1078         return nil
1079 }
1080
1081 var outputCollections = make(map[string]arvados.Collection)
1082
1083 // Fetch the collection for the mnt.PortableDataHash
1084 // Return the manifest_text fragment corresponding to the specified mnt.Path
1085 //  after making any required updates.
1086 //  Ex:
1087 //    If mnt.Path is not specified,
1088 //      return the entire manifest_text after replacing any "." with bindSuffix
1089 //    If mnt.Path corresponds to one stream,
1090 //      return the manifest_text for that stream after replacing that stream name with bindSuffix
1091 //    Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1092 //      for that stream after replacing stream name with bindSuffix minus the last word
1093 //      and the file name with last word of the bindSuffix
1094 //  Allowed path examples:
1095 //    "path":"/"
1096 //    "path":"/subdir1"
1097 //    "path":"/subdir1/subdir2"
1098 //    "path":"/subdir/filename" etc
1099 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1100         collection := outputCollections[mnt.PortableDataHash]
1101         if collection.PortableDataHash == "" {
1102                 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1103                 if err != nil {
1104                         return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1105                 }
1106                 outputCollections[mnt.PortableDataHash] = collection
1107         }
1108
1109         if collection.ManifestText == "" {
1110                 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1111                 return "", nil
1112         }
1113
1114         mft := manifest.Manifest{Text: collection.ManifestText}
1115         extracted := mft.Extract(mnt.Path, bindSuffix)
1116         if extracted.Err != nil {
1117                 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1118         }
1119         return extracted.Text, nil
1120 }
1121
1122 func (runner *ContainerRunner) CleanupDirs() {
1123         if runner.ArvMount != nil {
1124                 umount := exec.Command("fusermount", "-z", "-u", runner.ArvMountPoint)
1125                 umnterr := umount.Run()
1126                 if umnterr != nil {
1127                         runner.CrunchLog.Printf("While running fusermount: %v", umnterr)
1128                 }
1129
1130                 mnterr := <-runner.ArvMountExit
1131                 if mnterr != nil {
1132                         runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
1133                 }
1134         }
1135
1136         for _, tmpdir := range runner.CleanupTempDir {
1137                 rmerr := os.RemoveAll(tmpdir)
1138                 if rmerr != nil {
1139                         runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1140                 }
1141         }
1142 }
1143
1144 // CommitLogs posts the collection containing the final container logs.
1145 func (runner *ContainerRunner) CommitLogs() error {
1146         runner.CrunchLog.Print(runner.finalState)
1147         runner.CrunchLog.Close()
1148
1149         // Closing CrunchLog above allows it to be committed to Keep at this
1150         // point, but re-open crunch log with ArvClient in case there are any
1151         // other further (such as failing to write the log to Keep!) while
1152         // shutting down
1153         runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1154                 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1155
1156         if runner.LogsPDH != nil {
1157                 // If we have already assigned something to LogsPDH,
1158                 // we must be closing the re-opened log, which won't
1159                 // end up getting attached to the container record and
1160                 // therefore doesn't need to be saved as a collection
1161                 // -- it exists only to send logs to other channels.
1162                 return nil
1163         }
1164
1165         mt, err := runner.LogCollection.ManifestText()
1166         if err != nil {
1167                 return fmt.Errorf("While creating log manifest: %v", err)
1168         }
1169
1170         var response arvados.Collection
1171         err = runner.ArvClient.Create("collections",
1172                 arvadosclient.Dict{
1173                         "ensure_unique_name": true,
1174                         "collection": arvadosclient.Dict{
1175                                 "is_trashed":    true,
1176                                 "name":          "logs for " + runner.Container.UUID,
1177                                 "manifest_text": mt}},
1178                 &response)
1179         if err != nil {
1180                 return fmt.Errorf("While creating log collection: %v", err)
1181         }
1182         runner.LogsPDH = &response.PortableDataHash
1183         return nil
1184 }
1185
1186 // UpdateContainerRunning updates the container state to "Running"
1187 func (runner *ContainerRunner) UpdateContainerRunning() error {
1188         runner.cStateLock.Lock()
1189         defer runner.cStateLock.Unlock()
1190         if runner.cCancelled {
1191                 return ErrCancelled
1192         }
1193         return runner.ArvClient.Update("containers", runner.Container.UUID,
1194                 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1195 }
1196
1197 // ContainerToken returns the api_token the container (and any
1198 // arv-mount processes) are allowed to use.
1199 func (runner *ContainerRunner) ContainerToken() (string, error) {
1200         if runner.token != "" {
1201                 return runner.token, nil
1202         }
1203
1204         var auth arvados.APIClientAuthorization
1205         err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1206         if err != nil {
1207                 return "", err
1208         }
1209         runner.token = auth.APIToken
1210         return runner.token, nil
1211 }
1212
1213 // UpdateContainerComplete updates the container record state on API
1214 // server to "Complete" or "Cancelled"
1215 func (runner *ContainerRunner) UpdateContainerFinal() error {
1216         update := arvadosclient.Dict{}
1217         update["state"] = runner.finalState
1218         if runner.LogsPDH != nil {
1219                 update["log"] = *runner.LogsPDH
1220         }
1221         if runner.finalState == "Complete" {
1222                 if runner.ExitCode != nil {
1223                         update["exit_code"] = *runner.ExitCode
1224                 }
1225                 if runner.OutputPDH != nil {
1226                         update["output"] = *runner.OutputPDH
1227                 }
1228         }
1229         return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1230 }
1231
1232 // IsCancelled returns the value of Cancelled, with goroutine safety.
1233 func (runner *ContainerRunner) IsCancelled() bool {
1234         runner.cStateLock.Lock()
1235         defer runner.cStateLock.Unlock()
1236         return runner.cCancelled
1237 }
1238
1239 // NewArvLogWriter creates an ArvLogWriter
1240 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1241         return &ArvLogWriter{ArvClient: runner.ArvClient, UUID: runner.Container.UUID, loggingStream: name,
1242                 writeCloser: runner.LogCollection.Open(name + ".txt")}
1243 }
1244
1245 // Run the full container lifecycle.
1246 func (runner *ContainerRunner) Run() (err error) {
1247         runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1248
1249         hostname, hosterr := os.Hostname()
1250         if hosterr != nil {
1251                 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1252         } else {
1253                 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1254         }
1255
1256         // Clean up temporary directories _after_ finalizing
1257         // everything (if we've made any by then)
1258         defer runner.CleanupDirs()
1259
1260         runner.finalState = "Queued"
1261
1262         defer func() {
1263                 // checkErr prints e (unless it's nil) and sets err to
1264                 // e (unless err is already non-nil). Thus, if err
1265                 // hasn't already been assigned when Run() returns,
1266                 // this cleanup func will cause Run() to return the
1267                 // first non-nil error that is passed to checkErr().
1268                 checkErr := func(e error) {
1269                         if e == nil {
1270                                 return
1271                         }
1272                         runner.CrunchLog.Print(e)
1273                         if err == nil {
1274                                 err = e
1275                         }
1276                         if runner.finalState == "Complete" {
1277                                 // There was an error in the finalization.
1278                                 runner.finalState = "Cancelled"
1279                         }
1280                 }
1281
1282                 // Log the error encountered in Run(), if any
1283                 checkErr(err)
1284
1285                 if runner.finalState == "Queued" {
1286                         runner.CrunchLog.Close()
1287                         runner.UpdateContainerFinal()
1288                         return
1289                 }
1290
1291                 if runner.IsCancelled() {
1292                         runner.finalState = "Cancelled"
1293                         // but don't return yet -- we still want to
1294                         // capture partial output and write logs
1295                 }
1296
1297                 checkErr(runner.CaptureOutput())
1298                 checkErr(runner.CommitLogs())
1299                 checkErr(runner.UpdateContainerFinal())
1300
1301                 // The real log is already closed, but then we opened
1302                 // a new one in case we needed to log anything while
1303                 // finalizing.
1304                 runner.CrunchLog.Close()
1305         }()
1306
1307         err = runner.ArvClient.Get("containers", runner.Container.UUID, nil, &runner.Container)
1308         if err != nil {
1309                 err = fmt.Errorf("While getting container record: %v", err)
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 // NewContainerRunner creates a new container runner.
1373 func NewContainerRunner(api IArvadosClient,
1374         kc IKeepClient,
1375         docker ThinDockerClient,
1376         containerUUID string) *ContainerRunner {
1377
1378         cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1379         cr.NewLogWriter = cr.NewArvLogWriter
1380         cr.RunArvMount = cr.ArvMountCmd
1381         cr.MkTempDir = ioutil.TempDir
1382         cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1383         cr.Container.UUID = containerUUID
1384         cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1385         cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1386
1387         loadLogThrottleParams(api)
1388
1389         return cr
1390 }
1391
1392 func main() {
1393         statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1394         cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1395         cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1396         cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1397         caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1398         enableNetwork := flag.String("container-enable-networking", "default",
1399                 `Specify if networking should be enabled for container.  One of 'default', 'always':
1400         default: only enable networking if container requests it.
1401         always:  containers always have networking enabled
1402         `)
1403         networkMode := flag.String("container-network-mode", "default",
1404                 `Set networking mode for container.  Corresponds to Docker network mode (--net).
1405         `)
1406         flag.Parse()
1407
1408         containerId := flag.Arg(0)
1409
1410         if *caCertsPath != "" {
1411                 arvadosclient.CertFiles = []string{*caCertsPath}
1412         }
1413
1414         api, err := arvadosclient.MakeArvadosClient()
1415         if err != nil {
1416                 log.Fatalf("%s: %v", containerId, err)
1417         }
1418         api.Retries = 8
1419
1420         var kc *keepclient.KeepClient
1421         kc, err = keepclient.MakeKeepClient(api)
1422         if err != nil {
1423                 log.Fatalf("%s: %v", containerId, err)
1424         }
1425         kc.Retries = 4
1426
1427         var docker *dockerclient.Client
1428         // API version 1.21 corresponds to Docker 1.9, which is currently the
1429         // minimum version we want to support.
1430         docker, err = dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1431         if err != nil {
1432                 log.Fatalf("%s: %v", containerId, err)
1433         }
1434
1435         dockerClientProxy := ThinDockerClientProxy{Docker: docker}
1436
1437         cr := NewContainerRunner(api, kc, dockerClientProxy, containerId)
1438         cr.statInterval = *statInterval
1439         cr.cgroupRoot = *cgroupRoot
1440         cr.expectCgroupParent = *cgroupParent
1441         cr.enableNetwork = *enableNetwork
1442         cr.networkMode = *networkMode
1443         if *cgroupParentSubsystem != "" {
1444                 p := findCgroup(*cgroupParentSubsystem)
1445                 cr.setCgroupParent = p
1446                 cr.expectCgroupParent = p
1447         }
1448
1449         err = cr.Run()
1450         if err != nil {
1451                 log.Fatalf("%s: %v", containerId, err)
1452         }
1453
1454 }