17170: Use TLS for controller->crunch-run traffic.
[arvados.git] / lib / crunchrun / crunchrun.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package crunchrun
6
7 import (
8         "bytes"
9         "encoding/json"
10         "errors"
11         "flag"
12         "fmt"
13         "io"
14         "io/ioutil"
15         "log"
16         "os"
17         "os/exec"
18         "os/signal"
19         "path"
20         "path/filepath"
21         "regexp"
22         "runtime"
23         "runtime/pprof"
24         "sort"
25         "strings"
26         "sync"
27         "syscall"
28         "time"
29
30         "git.arvados.org/arvados.git/lib/cmd"
31         "git.arvados.org/arvados.git/lib/crunchstat"
32         "git.arvados.org/arvados.git/sdk/go/arvados"
33         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
34         "git.arvados.org/arvados.git/sdk/go/keepclient"
35         "git.arvados.org/arvados.git/sdk/go/manifest"
36         "golang.org/x/net/context"
37
38         dockertypes "github.com/docker/docker/api/types"
39         dockercontainer "github.com/docker/docker/api/types/container"
40         dockernetwork "github.com/docker/docker/api/types/network"
41         dockerclient "github.com/docker/docker/client"
42 )
43
44 type command struct{}
45
46 var Command = command{}
47
48 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
49 type IArvadosClient interface {
50         Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
51         Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
52         Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
53         Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
54         CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
55         Discovery(key string) (interface{}, error)
56 }
57
58 // ErrCancelled is the error returned when the container is cancelled.
59 var ErrCancelled = errors.New("Cancelled")
60
61 // IKeepClient is the minimal Keep API methods used by crunch-run.
62 type IKeepClient interface {
63         PutB(buf []byte) (string, int, error)
64         ReadAt(locator string, p []byte, off int) (int, error)
65         ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error)
66         LocalLocator(locator string) (string, error)
67         ClearBlockCache()
68 }
69
70 // NewLogWriter is a factory function to create a new log writer.
71 type NewLogWriter func(name string) (io.WriteCloser, error)
72
73 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
74
75 type MkTempDir func(string, string) (string, error)
76
77 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
78 type ThinDockerClient interface {
79         ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error)
80         ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
81                 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error)
82         ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error
83         ContainerRemove(ctx context.Context, container string, options dockertypes.ContainerRemoveOptions) error
84         ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error)
85         ContainerInspect(ctx context.Context, id string) (dockertypes.ContainerJSON, error)
86         ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error)
87         ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error)
88         ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error)
89 }
90
91 type PsProcess interface {
92         CmdlineSlice() ([]string, error)
93 }
94
95 // ContainerRunner is the main stateful struct used for a single execution of a
96 // container.
97 type ContainerRunner struct {
98         Docker ThinDockerClient
99
100         // Dispatcher client is initialized with the Dispatcher token.
101         // This is a privileged token used to manage container status
102         // and logs.
103         //
104         // We have both dispatcherClient and DispatcherArvClient
105         // because there are two different incompatible Arvados Go
106         // SDKs and we have to use both (hopefully this gets fixed in
107         // #14467)
108         dispatcherClient     *arvados.Client
109         DispatcherArvClient  IArvadosClient
110         DispatcherKeepClient IKeepClient
111
112         // Container client is initialized with the Container token
113         // This token controls the permissions of the container, and
114         // must be used for operations such as reading collections.
115         //
116         // Same comment as above applies to
117         // containerClient/ContainerArvClient.
118         containerClient     *arvados.Client
119         ContainerArvClient  IArvadosClient
120         ContainerKeepClient IKeepClient
121
122         Container       arvados.Container
123         ContainerConfig dockercontainer.Config
124         HostConfig      dockercontainer.HostConfig
125         token           string
126         ContainerID     string
127         ExitCode        *int
128         NewLogWriter    NewLogWriter
129         loggingDone     chan bool
130         CrunchLog       *ThrottledLogger
131         Stdout          io.WriteCloser
132         Stderr          io.WriteCloser
133         logUUID         string
134         logMtx          sync.Mutex
135         LogCollection   arvados.CollectionFileSystem
136         LogsPDH         *string
137         RunArvMount     RunArvMount
138         MkTempDir       MkTempDir
139         ArvMount        *exec.Cmd
140         ArvMountPoint   string
141         HostOutputDir   string
142         Binds           []string
143         Volumes         map[string]struct{}
144         OutputPDH       *string
145         SigChan         chan os.Signal
146         ArvMountExit    chan error
147         SecretMounts    map[string]arvados.Mount
148         MkArvClient     func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error)
149         finalState      string
150         parentTemp      string
151
152         statLogger       io.WriteCloser
153         statReporter     *crunchstat.Reporter
154         hoststatLogger   io.WriteCloser
155         hoststatReporter *crunchstat.Reporter
156         statInterval     time.Duration
157         cgroupRoot       string
158         // What we expect the container's cgroup parent to be.
159         expectCgroupParent string
160         // What we tell docker to use as the container's cgroup
161         // parent. Note: Ideally we would use the same field for both
162         // expectCgroupParent and setCgroupParent, and just make it
163         // default to "docker". However, when using docker < 1.10 with
164         // systemd, specifying a non-empty cgroup parent (even the
165         // default value "docker") hits a docker bug
166         // (https://github.com/docker/docker/issues/17126). Using two
167         // separate fields makes it possible to use the "expect cgroup
168         // parent to be X" feature even on sites where the "specify
169         // cgroup parent" feature breaks.
170         setCgroupParent string
171
172         cStateLock sync.Mutex
173         cCancelled bool // StopContainer() invoked
174         cRemoved   bool // docker confirmed the container no longer exists
175
176         enableNetwork string // one of "default" or "always"
177         networkMode   string // passed through to HostConfig.NetworkMode
178         arvMountLog   *ThrottledLogger
179
180         containerWatchdogInterval time.Duration
181
182         gateway Gateway
183 }
184
185 // setupSignals sets up signal handling to gracefully terminate the underlying
186 // Docker container and update state when receiving a TERM, INT or QUIT signal.
187 func (runner *ContainerRunner) setupSignals() {
188         runner.SigChan = make(chan os.Signal, 1)
189         signal.Notify(runner.SigChan, syscall.SIGTERM)
190         signal.Notify(runner.SigChan, syscall.SIGINT)
191         signal.Notify(runner.SigChan, syscall.SIGQUIT)
192
193         go func(sig chan os.Signal) {
194                 for s := range sig {
195                         runner.stop(s)
196                 }
197         }(runner.SigChan)
198 }
199
200 // stop the underlying Docker container.
201 func (runner *ContainerRunner) stop(sig os.Signal) {
202         runner.cStateLock.Lock()
203         defer runner.cStateLock.Unlock()
204         if sig != nil {
205                 runner.CrunchLog.Printf("caught signal: %v", sig)
206         }
207         if runner.ContainerID == "" {
208                 return
209         }
210         runner.cCancelled = true
211         runner.CrunchLog.Printf("removing container")
212         err := runner.Docker.ContainerRemove(context.TODO(), runner.ContainerID, dockertypes.ContainerRemoveOptions{Force: true})
213         if err != nil {
214                 runner.CrunchLog.Printf("error removing container: %s", err)
215         }
216         if err == nil || strings.Contains(err.Error(), "No such container: "+runner.ContainerID) {
217                 runner.cRemoved = true
218         }
219 }
220
221 var errorBlacklist = []string{
222         "(?ms).*[Cc]annot connect to the Docker daemon.*",
223         "(?ms).*oci runtime error.*starting container process.*container init.*mounting.*to rootfs.*no such file or directory.*",
224         "(?ms).*grpc: the connection is unavailable.*",
225 }
226 var brokenNodeHook *string = flag.String("broken-node-hook", "", "Script to run if node is detected to be broken (for example, Docker daemon is not running)")
227
228 func (runner *ContainerRunner) runBrokenNodeHook() {
229         if *brokenNodeHook == "" {
230                 path := filepath.Join(lockdir, brokenfile)
231                 runner.CrunchLog.Printf("Writing %s to mark node as broken", path)
232                 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0700)
233                 if err != nil {
234                         runner.CrunchLog.Printf("Error writing %s: %s", path, err)
235                         return
236                 }
237                 f.Close()
238         } else {
239                 runner.CrunchLog.Printf("Running broken node hook %q", *brokenNodeHook)
240                 // run killme script
241                 c := exec.Command(*brokenNodeHook)
242                 c.Stdout = runner.CrunchLog
243                 c.Stderr = runner.CrunchLog
244                 err := c.Run()
245                 if err != nil {
246                         runner.CrunchLog.Printf("Error running broken node hook: %v", err)
247                 }
248         }
249 }
250
251 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
252         for _, d := range errorBlacklist {
253                 if m, e := regexp.MatchString(d, goterr.Error()); m && e == nil {
254                         runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
255                         runner.runBrokenNodeHook()
256                         return true
257                 }
258         }
259         return false
260 }
261
262 // LoadImage determines the docker image id from the container record and
263 // checks if it is available in the local Docker image store.  If not, it loads
264 // the image from Keep.
265 func (runner *ContainerRunner) LoadImage() (err error) {
266
267         runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
268
269         var collection arvados.Collection
270         err = runner.ContainerArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
271         if err != nil {
272                 return fmt.Errorf("While getting container image collection: %v", err)
273         }
274         manifest := manifest.Manifest{Text: collection.ManifestText}
275         var img, imageID string
276         for ms := range manifest.StreamIter() {
277                 img = ms.FileStreamSegments[0].Name
278                 if !strings.HasSuffix(img, ".tar") {
279                         return fmt.Errorf("First file in the container image collection does not end in .tar")
280                 }
281                 imageID = img[:len(img)-4]
282         }
283
284         runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
285
286         _, _, err = runner.Docker.ImageInspectWithRaw(context.TODO(), imageID)
287         if err != nil {
288                 runner.CrunchLog.Print("Loading Docker image from keep")
289
290                 var readCloser io.ReadCloser
291                 readCloser, err = runner.ContainerKeepClient.ManifestFileReader(manifest, img)
292                 if err != nil {
293                         return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
294                 }
295
296                 response, err := runner.Docker.ImageLoad(context.TODO(), readCloser, true)
297                 if err != nil {
298                         return fmt.Errorf("While loading container image into Docker: %v", err)
299                 }
300
301                 defer response.Body.Close()
302                 rbody, err := ioutil.ReadAll(response.Body)
303                 if err != nil {
304                         return fmt.Errorf("Reading response to image load: %v", err)
305                 }
306                 runner.CrunchLog.Printf("Docker response: %s", rbody)
307         } else {
308                 runner.CrunchLog.Print("Docker image is available")
309         }
310
311         runner.ContainerConfig.Image = imageID
312
313         runner.ContainerKeepClient.ClearBlockCache()
314
315         return nil
316 }
317
318 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
319         c = exec.Command("arv-mount", arvMountCmd...)
320
321         // Copy our environment, but override ARVADOS_API_TOKEN with
322         // the container auth token.
323         c.Env = nil
324         for _, s := range os.Environ() {
325                 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
326                         c.Env = append(c.Env, s)
327                 }
328         }
329         c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
330
331         w, err := runner.NewLogWriter("arv-mount")
332         if err != nil {
333                 return nil, err
334         }
335         runner.arvMountLog = NewThrottledLogger(w)
336         c.Stdout = runner.arvMountLog
337         c.Stderr = runner.arvMountLog
338
339         runner.CrunchLog.Printf("Running %v", c.Args)
340
341         err = c.Start()
342         if err != nil {
343                 return nil, err
344         }
345
346         statReadme := make(chan bool)
347         runner.ArvMountExit = make(chan error)
348
349         keepStatting := true
350         go func() {
351                 for keepStatting {
352                         time.Sleep(100 * time.Millisecond)
353                         _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
354                         if err == nil {
355                                 keepStatting = false
356                                 statReadme <- true
357                         }
358                 }
359                 close(statReadme)
360         }()
361
362         go func() {
363                 mnterr := c.Wait()
364                 if mnterr != nil {
365                         runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
366                 }
367                 runner.ArvMountExit <- mnterr
368                 close(runner.ArvMountExit)
369         }()
370
371         select {
372         case <-statReadme:
373                 break
374         case err := <-runner.ArvMountExit:
375                 runner.ArvMount = nil
376                 keepStatting = false
377                 return nil, err
378         }
379
380         return c, nil
381 }
382
383 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
384         if runner.ArvMountPoint == "" {
385                 runner.ArvMountPoint, err = runner.MkTempDir(runner.parentTemp, prefix)
386         }
387         return
388 }
389
390 func copyfile(src string, dst string) (err error) {
391         srcfile, err := os.Open(src)
392         if err != nil {
393                 return
394         }
395
396         os.MkdirAll(path.Dir(dst), 0777)
397
398         dstfile, err := os.Create(dst)
399         if err != nil {
400                 return
401         }
402         _, err = io.Copy(dstfile, srcfile)
403         if err != nil {
404                 return
405         }
406
407         err = srcfile.Close()
408         err2 := dstfile.Close()
409
410         if err != nil {
411                 return
412         }
413
414         if err2 != nil {
415                 return err2
416         }
417
418         return nil
419 }
420
421 func (runner *ContainerRunner) SetupMounts() (err error) {
422         err = runner.SetupArvMountPoint("keep")
423         if err != nil {
424                 return fmt.Errorf("While creating keep mount temp dir: %v", err)
425         }
426
427         token, err := runner.ContainerToken()
428         if err != nil {
429                 return fmt.Errorf("could not get container token: %s", err)
430         }
431
432         pdhOnly := true
433         tmpcount := 0
434         arvMountCmd := []string{
435                 "--foreground",
436                 "--allow-other",
437                 "--read-write",
438                 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
439
440         if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
441                 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
442         }
443
444         collectionPaths := []string{}
445         runner.Binds = nil
446         runner.Volumes = make(map[string]struct{})
447         needCertMount := true
448         type copyFile struct {
449                 src  string
450                 bind string
451         }
452         var copyFiles []copyFile
453
454         var binds []string
455         for bind := range runner.Container.Mounts {
456                 binds = append(binds, bind)
457         }
458         for bind := range runner.SecretMounts {
459                 if _, ok := runner.Container.Mounts[bind]; ok {
460                         return fmt.Errorf("secret mount %q conflicts with regular mount", bind)
461                 }
462                 if runner.SecretMounts[bind].Kind != "json" &&
463                         runner.SecretMounts[bind].Kind != "text" {
464                         return fmt.Errorf("secret mount %q type is %q but only 'json' and 'text' are permitted",
465                                 bind, runner.SecretMounts[bind].Kind)
466                 }
467                 binds = append(binds, bind)
468         }
469         sort.Strings(binds)
470
471         for _, bind := range binds {
472                 mnt, ok := runner.Container.Mounts[bind]
473                 if !ok {
474                         mnt = runner.SecretMounts[bind]
475                 }
476                 if bind == "stdout" || bind == "stderr" {
477                         // Is it a "file" mount kind?
478                         if mnt.Kind != "file" {
479                                 return fmt.Errorf("unsupported mount kind '%s' for %s: only 'file' is supported", mnt.Kind, bind)
480                         }
481
482                         // Does path start with OutputPath?
483                         prefix := runner.Container.OutputPath
484                         if !strings.HasSuffix(prefix, "/") {
485                                 prefix += "/"
486                         }
487                         if !strings.HasPrefix(mnt.Path, prefix) {
488                                 return fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
489                         }
490                 }
491
492                 if bind == "stdin" {
493                         // Is it a "collection" mount kind?
494                         if mnt.Kind != "collection" && mnt.Kind != "json" {
495                                 return fmt.Errorf("unsupported mount kind '%s' for stdin: only 'collection' and 'json' are supported", mnt.Kind)
496                         }
497                 }
498
499                 if bind == "/etc/arvados/ca-certificates.crt" {
500                         needCertMount = false
501                 }
502
503                 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
504                         if mnt.Kind != "collection" && mnt.Kind != "text" && mnt.Kind != "json" {
505                                 return fmt.Errorf("only mount points of kind 'collection', 'text' or 'json' are supported underneath the output_path for %q, was %q", bind, mnt.Kind)
506                         }
507                 }
508
509                 switch {
510                 case mnt.Kind == "collection" && bind != "stdin":
511                         var src string
512                         if mnt.UUID != "" && mnt.PortableDataHash != "" {
513                                 return fmt.Errorf("cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
514                         }
515                         if mnt.UUID != "" {
516                                 if mnt.Writable {
517                                         return fmt.Errorf("writing to existing collections currently not permitted")
518                                 }
519                                 pdhOnly = false
520                                 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
521                         } else if mnt.PortableDataHash != "" {
522                                 if mnt.Writable && !strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
523                                         return fmt.Errorf("can never write to a collection specified by portable data hash")
524                                 }
525                                 idx := strings.Index(mnt.PortableDataHash, "/")
526                                 if idx > 0 {
527                                         mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
528                                         mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
529                                         runner.Container.Mounts[bind] = mnt
530                                 }
531                                 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
532                                 if mnt.Path != "" && mnt.Path != "." {
533                                         if strings.HasPrefix(mnt.Path, "./") {
534                                                 mnt.Path = mnt.Path[2:]
535                                         } else if strings.HasPrefix(mnt.Path, "/") {
536                                                 mnt.Path = mnt.Path[1:]
537                                         }
538                                         src += "/" + mnt.Path
539                                 }
540                         } else {
541                                 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
542                                 arvMountCmd = append(arvMountCmd, "--mount-tmp")
543                                 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
544                                 tmpcount++
545                         }
546                         if mnt.Writable {
547                                 if bind == runner.Container.OutputPath {
548                                         runner.HostOutputDir = src
549                                         runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
550                                 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
551                                         copyFiles = append(copyFiles, copyFile{src, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
552                                 } else {
553                                         runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
554                                 }
555                         } else {
556                                 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
557                         }
558                         collectionPaths = append(collectionPaths, src)
559
560                 case mnt.Kind == "tmp":
561                         var tmpdir string
562                         tmpdir, err = runner.MkTempDir(runner.parentTemp, "tmp")
563                         if err != nil {
564                                 return fmt.Errorf("while creating mount temp dir: %v", err)
565                         }
566                         st, staterr := os.Stat(tmpdir)
567                         if staterr != nil {
568                                 return fmt.Errorf("while Stat on temp dir: %v", staterr)
569                         }
570                         err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
571                         if staterr != nil {
572                                 return fmt.Errorf("while Chmod temp dir: %v", err)
573                         }
574                         runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", tmpdir, bind))
575                         if bind == runner.Container.OutputPath {
576                                 runner.HostOutputDir = tmpdir
577                         }
578
579                 case mnt.Kind == "json" || mnt.Kind == "text":
580                         var filedata []byte
581                         if mnt.Kind == "json" {
582                                 filedata, err = json.Marshal(mnt.Content)
583                                 if err != nil {
584                                         return fmt.Errorf("encoding json data: %v", err)
585                                 }
586                         } else {
587                                 text, ok := mnt.Content.(string)
588                                 if !ok {
589                                         return fmt.Errorf("content for mount %q must be a string", bind)
590                                 }
591                                 filedata = []byte(text)
592                         }
593
594                         tmpdir, err := runner.MkTempDir(runner.parentTemp, mnt.Kind)
595                         if err != nil {
596                                 return fmt.Errorf("creating temp dir: %v", err)
597                         }
598                         tmpfn := filepath.Join(tmpdir, "mountdata."+mnt.Kind)
599                         err = ioutil.WriteFile(tmpfn, filedata, 0444)
600                         if err != nil {
601                                 return fmt.Errorf("writing temp file: %v", err)
602                         }
603                         if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
604                                 copyFiles = append(copyFiles, copyFile{tmpfn, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
605                         } else {
606                                 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
607                         }
608
609                 case mnt.Kind == "git_tree":
610                         tmpdir, err := runner.MkTempDir(runner.parentTemp, "git_tree")
611                         if err != nil {
612                                 return fmt.Errorf("creating temp dir: %v", err)
613                         }
614                         err = gitMount(mnt).extractTree(runner.ContainerArvClient, tmpdir, token)
615                         if err != nil {
616                                 return err
617                         }
618                         runner.Binds = append(runner.Binds, tmpdir+":"+bind+":ro")
619                 }
620         }
621
622         if runner.HostOutputDir == "" {
623                 return fmt.Errorf("output path does not correspond to a writable mount point")
624         }
625
626         if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
627                 for _, certfile := range arvadosclient.CertFiles {
628                         _, err := os.Stat(certfile)
629                         if err == nil {
630                                 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
631                                 break
632                         }
633                 }
634         }
635
636         if pdhOnly {
637                 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
638         } else {
639                 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
640         }
641         arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
642
643         runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
644         if err != nil {
645                 return fmt.Errorf("while trying to start arv-mount: %v", err)
646         }
647
648         for _, p := range collectionPaths {
649                 _, err = os.Stat(p)
650                 if err != nil {
651                         return fmt.Errorf("while checking that input files exist: %v", err)
652                 }
653         }
654
655         for _, cp := range copyFiles {
656                 st, err := os.Stat(cp.src)
657                 if err != nil {
658                         return fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
659                 }
660                 if st.IsDir() {
661                         err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
662                                 if walkerr != nil {
663                                         return walkerr
664                                 }
665                                 target := path.Join(cp.bind, walkpath[len(cp.src):])
666                                 if walkinfo.Mode().IsRegular() {
667                                         copyerr := copyfile(walkpath, target)
668                                         if copyerr != nil {
669                                                 return copyerr
670                                         }
671                                         return os.Chmod(target, walkinfo.Mode()|0777)
672                                 } else if walkinfo.Mode().IsDir() {
673                                         mkerr := os.MkdirAll(target, 0777)
674                                         if mkerr != nil {
675                                                 return mkerr
676                                         }
677                                         return os.Chmod(target, walkinfo.Mode()|os.ModeSetgid|0777)
678                                 } else {
679                                         return fmt.Errorf("source %q is not a regular file or directory", cp.src)
680                                 }
681                         })
682                 } else if st.Mode().IsRegular() {
683                         err = copyfile(cp.src, cp.bind)
684                         if err == nil {
685                                 err = os.Chmod(cp.bind, st.Mode()|0777)
686                         }
687                 }
688                 if err != nil {
689                         return fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
690                 }
691         }
692
693         return nil
694 }
695
696 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
697         // Handle docker log protocol
698         // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
699         defer close(runner.loggingDone)
700
701         header := make([]byte, 8)
702         var err error
703         for err == nil {
704                 _, err = io.ReadAtLeast(containerReader, header, 8)
705                 if err != nil {
706                         if err == io.EOF {
707                                 err = nil
708                         }
709                         break
710                 }
711                 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
712                 if header[0] == 1 {
713                         // stdout
714                         _, err = io.CopyN(runner.Stdout, containerReader, readsize)
715                 } else {
716                         // stderr
717                         _, err = io.CopyN(runner.Stderr, containerReader, readsize)
718                 }
719         }
720
721         if err != nil {
722                 runner.CrunchLog.Printf("error reading docker logs: %v", err)
723         }
724
725         err = runner.Stdout.Close()
726         if err != nil {
727                 runner.CrunchLog.Printf("error closing stdout logs: %v", err)
728         }
729
730         err = runner.Stderr.Close()
731         if err != nil {
732                 runner.CrunchLog.Printf("error closing stderr logs: %v", err)
733         }
734
735         if runner.statReporter != nil {
736                 runner.statReporter.Stop()
737                 err = runner.statLogger.Close()
738                 if err != nil {
739                         runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
740                 }
741         }
742 }
743
744 func (runner *ContainerRunner) stopHoststat() error {
745         if runner.hoststatReporter == nil {
746                 return nil
747         }
748         runner.hoststatReporter.Stop()
749         err := runner.hoststatLogger.Close()
750         if err != nil {
751                 return fmt.Errorf("error closing hoststat logs: %v", err)
752         }
753         return nil
754 }
755
756 func (runner *ContainerRunner) startHoststat() error {
757         w, err := runner.NewLogWriter("hoststat")
758         if err != nil {
759                 return err
760         }
761         runner.hoststatLogger = NewThrottledLogger(w)
762         runner.hoststatReporter = &crunchstat.Reporter{
763                 Logger:     log.New(runner.hoststatLogger, "", 0),
764                 CgroupRoot: runner.cgroupRoot,
765                 PollPeriod: runner.statInterval,
766         }
767         runner.hoststatReporter.Start()
768         return nil
769 }
770
771 func (runner *ContainerRunner) startCrunchstat() error {
772         w, err := runner.NewLogWriter("crunchstat")
773         if err != nil {
774                 return err
775         }
776         runner.statLogger = NewThrottledLogger(w)
777         runner.statReporter = &crunchstat.Reporter{
778                 CID:          runner.ContainerID,
779                 Logger:       log.New(runner.statLogger, "", 0),
780                 CgroupParent: runner.expectCgroupParent,
781                 CgroupRoot:   runner.cgroupRoot,
782                 PollPeriod:   runner.statInterval,
783                 TempDir:      runner.parentTemp,
784         }
785         runner.statReporter.Start()
786         return nil
787 }
788
789 type infoCommand struct {
790         label string
791         cmd   []string
792 }
793
794 // LogHostInfo logs info about the current host, for debugging and
795 // accounting purposes. Although it's logged as "node-info", this is
796 // about the environment where crunch-run is actually running, which
797 // might differ from what's described in the node record (see
798 // LogNodeRecord).
799 func (runner *ContainerRunner) LogHostInfo() (err error) {
800         w, err := runner.NewLogWriter("node-info")
801         if err != nil {
802                 return
803         }
804
805         commands := []infoCommand{
806                 {
807                         label: "Host Information",
808                         cmd:   []string{"uname", "-a"},
809                 },
810                 {
811                         label: "CPU Information",
812                         cmd:   []string{"cat", "/proc/cpuinfo"},
813                 },
814                 {
815                         label: "Memory Information",
816                         cmd:   []string{"cat", "/proc/meminfo"},
817                 },
818                 {
819                         label: "Disk Space",
820                         cmd:   []string{"df", "-m", "/", os.TempDir()},
821                 },
822                 {
823                         label: "Disk INodes",
824                         cmd:   []string{"df", "-i", "/", os.TempDir()},
825                 },
826         }
827
828         // Run commands with informational output to be logged.
829         for _, command := range commands {
830                 fmt.Fprintln(w, command.label)
831                 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
832                 cmd.Stdout = w
833                 cmd.Stderr = w
834                 if err := cmd.Run(); err != nil {
835                         err = fmt.Errorf("While running command %q: %v", command.cmd, err)
836                         fmt.Fprintln(w, err)
837                         return err
838                 }
839                 fmt.Fprintln(w, "")
840         }
841
842         err = w.Close()
843         if err != nil {
844                 return fmt.Errorf("While closing node-info logs: %v", err)
845         }
846         return nil
847 }
848
849 // LogContainerRecord gets and saves the raw JSON container record from the API server
850 func (runner *ContainerRunner) LogContainerRecord() error {
851         logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
852         if !logged && err == nil {
853                 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
854         }
855         return err
856 }
857
858 // LogNodeRecord logs the current host's InstanceType config entry (or
859 // the arvados#node record, if running via crunch-dispatch-slurm).
860 func (runner *ContainerRunner) LogNodeRecord() error {
861         if it := os.Getenv("InstanceType"); it != "" {
862                 // Dispatched via arvados-dispatch-cloud. Save
863                 // InstanceType config fragment received from
864                 // dispatcher on stdin.
865                 w, err := runner.LogCollection.OpenFile("node.json", os.O_CREATE|os.O_WRONLY, 0666)
866                 if err != nil {
867                         return err
868                 }
869                 defer w.Close()
870                 _, err = io.WriteString(w, it)
871                 if err != nil {
872                         return err
873                 }
874                 return w.Close()
875         }
876         // Dispatched via crunch-dispatch-slurm. Look up
877         // apiserver's node record corresponding to
878         // $SLURMD_NODENAME.
879         hostname := os.Getenv("SLURMD_NODENAME")
880         if hostname == "" {
881                 hostname, _ = os.Hostname()
882         }
883         _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
884                 // The "info" field has admin-only info when
885                 // obtained with a privileged token, and
886                 // should not be logged.
887                 node, ok := resp.(map[string]interface{})
888                 if ok {
889                         delete(node, "info")
890                 }
891         })
892         return err
893 }
894
895 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
896         writer, err := runner.LogCollection.OpenFile(label+".json", os.O_CREATE|os.O_WRONLY, 0666)
897         if err != nil {
898                 return false, err
899         }
900         w := &ArvLogWriter{
901                 ArvClient:     runner.DispatcherArvClient,
902                 UUID:          runner.Container.UUID,
903                 loggingStream: label,
904                 writeCloser:   writer,
905         }
906
907         reader, err := runner.DispatcherArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
908         if err != nil {
909                 return false, fmt.Errorf("error getting %s record: %v", label, err)
910         }
911         defer reader.Close()
912
913         dec := json.NewDecoder(reader)
914         dec.UseNumber()
915         var resp map[string]interface{}
916         if err = dec.Decode(&resp); err != nil {
917                 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
918         }
919         items, ok := resp["items"].([]interface{})
920         if !ok {
921                 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
922         } else if len(items) < 1 {
923                 return false, nil
924         }
925         if munge != nil {
926                 munge(items[0])
927         }
928         // Re-encode it using indentation to improve readability
929         enc := json.NewEncoder(w)
930         enc.SetIndent("", "    ")
931         if err = enc.Encode(items[0]); err != nil {
932                 return false, fmt.Errorf("error logging %s record: %v", label, err)
933         }
934         err = w.Close()
935         if err != nil {
936                 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
937         }
938         return true, nil
939 }
940
941 // AttachStreams connects the docker container stdin, stdout and stderr logs
942 // to the Arvados logger which logs to Keep and the API server logs table.
943 func (runner *ContainerRunner) AttachStreams() (err error) {
944
945         runner.CrunchLog.Print("Attaching container streams")
946
947         // If stdin mount is provided, attach it to the docker container
948         var stdinRdr arvados.File
949         var stdinJSON []byte
950         if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
951                 if stdinMnt.Kind == "collection" {
952                         var stdinColl arvados.Collection
953                         collID := stdinMnt.UUID
954                         if collID == "" {
955                                 collID = stdinMnt.PortableDataHash
956                         }
957                         err = runner.ContainerArvClient.Get("collections", collID, nil, &stdinColl)
958                         if err != nil {
959                                 return fmt.Errorf("While getting stdin collection: %v", err)
960                         }
961
962                         stdinRdr, err = runner.ContainerKeepClient.ManifestFileReader(
963                                 manifest.Manifest{Text: stdinColl.ManifestText},
964                                 stdinMnt.Path)
965                         if os.IsNotExist(err) {
966                                 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
967                         } else if err != nil {
968                                 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
969                         }
970                 } else if stdinMnt.Kind == "json" {
971                         stdinJSON, err = json.Marshal(stdinMnt.Content)
972                         if err != nil {
973                                 return fmt.Errorf("While encoding stdin json data: %v", err)
974                         }
975                 }
976         }
977
978         stdinUsed := stdinRdr != nil || len(stdinJSON) != 0
979         response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
980                 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
981         if err != nil {
982                 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
983         }
984
985         runner.loggingDone = make(chan bool)
986
987         if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
988                 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
989                 if err != nil {
990                         return err
991                 }
992                 runner.Stdout = stdoutFile
993         } else if w, err := runner.NewLogWriter("stdout"); err != nil {
994                 return err
995         } else {
996                 runner.Stdout = NewThrottledLogger(w)
997         }
998
999         if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
1000                 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
1001                 if err != nil {
1002                         return err
1003                 }
1004                 runner.Stderr = stderrFile
1005         } else if w, err := runner.NewLogWriter("stderr"); err != nil {
1006                 return err
1007         } else {
1008                 runner.Stderr = NewThrottledLogger(w)
1009         }
1010
1011         if stdinRdr != nil {
1012                 go func() {
1013                         _, err := io.Copy(response.Conn, stdinRdr)
1014                         if err != nil {
1015                                 runner.CrunchLog.Printf("While writing stdin collection to docker container: %v", err)
1016                                 runner.stop(nil)
1017                         }
1018                         stdinRdr.Close()
1019                         response.CloseWrite()
1020                 }()
1021         } else if len(stdinJSON) != 0 {
1022                 go func() {
1023                         _, err := io.Copy(response.Conn, bytes.NewReader(stdinJSON))
1024                         if err != nil {
1025                                 runner.CrunchLog.Printf("While writing stdin json to docker container: %v", err)
1026                                 runner.stop(nil)
1027                         }
1028                         response.CloseWrite()
1029                 }()
1030         }
1031
1032         go runner.ProcessDockerAttach(response.Reader)
1033
1034         return nil
1035 }
1036
1037 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
1038         stdoutPath := mntPath[len(runner.Container.OutputPath):]
1039         index := strings.LastIndex(stdoutPath, "/")
1040         if index > 0 {
1041                 subdirs := stdoutPath[:index]
1042                 if subdirs != "" {
1043                         st, err := os.Stat(runner.HostOutputDir)
1044                         if err != nil {
1045                                 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
1046                         }
1047                         stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
1048                         err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
1049                         if err != nil {
1050                                 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
1051                         }
1052                 }
1053         }
1054         stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
1055         if err != nil {
1056                 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
1057         }
1058
1059         return stdoutFile, nil
1060 }
1061
1062 // CreateContainer creates the docker container.
1063 func (runner *ContainerRunner) CreateContainer() error {
1064         runner.CrunchLog.Print("Creating Docker container")
1065
1066         runner.ContainerConfig.Cmd = runner.Container.Command
1067         if runner.Container.Cwd != "." {
1068                 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
1069         }
1070
1071         for k, v := range runner.Container.Environment {
1072                 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
1073         }
1074
1075         runner.ContainerConfig.Volumes = runner.Volumes
1076
1077         maxRAM := int64(runner.Container.RuntimeConstraints.RAM)
1078         minDockerRAM := int64(16)
1079         if maxRAM < minDockerRAM*1024*1024 {
1080                 // Docker daemon won't let you set a limit less than ~10 MiB
1081                 maxRAM = minDockerRAM * 1024 * 1024
1082         }
1083         runner.HostConfig = dockercontainer.HostConfig{
1084                 Binds: runner.Binds,
1085                 LogConfig: dockercontainer.LogConfig{
1086                         Type: "none",
1087                 },
1088                 Resources: dockercontainer.Resources{
1089                         CgroupParent: runner.setCgroupParent,
1090                         NanoCPUs:     int64(runner.Container.RuntimeConstraints.VCPUs) * 1000000000,
1091                         Memory:       maxRAM, // RAM
1092                         MemorySwap:   maxRAM, // RAM+swap
1093                         KernelMemory: maxRAM, // kernel portion
1094                 },
1095         }
1096
1097         if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
1098                 tok, err := runner.ContainerToken()
1099                 if err != nil {
1100                         return err
1101                 }
1102                 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
1103                         "ARVADOS_API_TOKEN="+tok,
1104                         "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
1105                         "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
1106                 )
1107                 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
1108         } else {
1109                 if runner.enableNetwork == "always" {
1110                         runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
1111                 } else {
1112                         runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
1113                 }
1114         }
1115
1116         _, stdinUsed := runner.Container.Mounts["stdin"]
1117         runner.ContainerConfig.OpenStdin = stdinUsed
1118         runner.ContainerConfig.StdinOnce = stdinUsed
1119         runner.ContainerConfig.AttachStdin = stdinUsed
1120         runner.ContainerConfig.AttachStdout = true
1121         runner.ContainerConfig.AttachStderr = true
1122
1123         createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
1124         if err != nil {
1125                 return fmt.Errorf("While creating container: %v", err)
1126         }
1127
1128         runner.ContainerID = createdBody.ID
1129
1130         return runner.AttachStreams()
1131 }
1132
1133 // StartContainer starts the docker container created by CreateContainer.
1134 func (runner *ContainerRunner) StartContainer() error {
1135         runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
1136         runner.cStateLock.Lock()
1137         defer runner.cStateLock.Unlock()
1138         if runner.cCancelled {
1139                 return ErrCancelled
1140         }
1141         err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
1142                 dockertypes.ContainerStartOptions{})
1143         if err != nil {
1144                 var advice string
1145                 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
1146                         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])
1147                 }
1148                 return fmt.Errorf("could not start container: %v%s", err, advice)
1149         }
1150         return nil
1151 }
1152
1153 // WaitFinish waits for the container to terminate, capture the exit code, and
1154 // close the stdout/stderr logging.
1155 func (runner *ContainerRunner) WaitFinish() error {
1156         var runTimeExceeded <-chan time.Time
1157         runner.CrunchLog.Print("Waiting for container to finish")
1158
1159         waitOk, waitErr := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID, dockercontainer.WaitConditionNotRunning)
1160         arvMountExit := runner.ArvMountExit
1161         if timeout := runner.Container.SchedulingParameters.MaxRunTime; timeout > 0 {
1162                 runTimeExceeded = time.After(time.Duration(timeout) * time.Second)
1163         }
1164
1165         containerGone := make(chan struct{})
1166         go func() {
1167                 defer close(containerGone)
1168                 if runner.containerWatchdogInterval < 1 {
1169                         runner.containerWatchdogInterval = time.Minute
1170                 }
1171                 for range time.NewTicker(runner.containerWatchdogInterval).C {
1172                         ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(runner.containerWatchdogInterval))
1173                         ctr, err := runner.Docker.ContainerInspect(ctx, runner.ContainerID)
1174                         cancel()
1175                         runner.cStateLock.Lock()
1176                         done := runner.cRemoved || runner.ExitCode != nil
1177                         runner.cStateLock.Unlock()
1178                         if done {
1179                                 return
1180                         } else if err != nil {
1181                                 runner.CrunchLog.Printf("Error inspecting container: %s", err)
1182                                 runner.checkBrokenNode(err)
1183                                 return
1184                         } else if ctr.State == nil || !(ctr.State.Running || ctr.State.Status == "created") {
1185                                 runner.CrunchLog.Printf("Container is not running: State=%v", ctr.State)
1186                                 return
1187                         }
1188                 }
1189         }()
1190
1191         for {
1192                 select {
1193                 case waitBody := <-waitOk:
1194                         runner.CrunchLog.Printf("Container exited with code: %v", waitBody.StatusCode)
1195                         code := int(waitBody.StatusCode)
1196                         runner.ExitCode = &code
1197
1198                         // wait for stdout/stderr to complete
1199                         <-runner.loggingDone
1200                         return nil
1201
1202                 case err := <-waitErr:
1203                         return fmt.Errorf("container wait: %v", err)
1204
1205                 case <-arvMountExit:
1206                         runner.CrunchLog.Printf("arv-mount exited while container is still running.  Stopping container.")
1207                         runner.stop(nil)
1208                         // arvMountExit will always be ready now that
1209                         // it's closed, but that doesn't interest us.
1210                         arvMountExit = nil
1211
1212                 case <-runTimeExceeded:
1213                         runner.CrunchLog.Printf("maximum run time exceeded. Stopping container.")
1214                         runner.stop(nil)
1215                         runTimeExceeded = nil
1216
1217                 case <-containerGone:
1218                         return errors.New("docker client never returned status")
1219                 }
1220         }
1221 }
1222
1223 func (runner *ContainerRunner) updateLogs() {
1224         ticker := time.NewTicker(crunchLogUpdatePeriod / 360)
1225         defer ticker.Stop()
1226
1227         sigusr1 := make(chan os.Signal, 1)
1228         signal.Notify(sigusr1, syscall.SIGUSR1)
1229         defer signal.Stop(sigusr1)
1230
1231         saveAtTime := time.Now().Add(crunchLogUpdatePeriod)
1232         saveAtSize := crunchLogUpdateSize
1233         var savedSize int64
1234         for {
1235                 select {
1236                 case <-ticker.C:
1237                 case <-sigusr1:
1238                         saveAtTime = time.Now()
1239                 }
1240                 runner.logMtx.Lock()
1241                 done := runner.LogsPDH != nil
1242                 runner.logMtx.Unlock()
1243                 if done {
1244                         return
1245                 }
1246                 size := runner.LogCollection.Size()
1247                 if size == savedSize || (time.Now().Before(saveAtTime) && size < saveAtSize) {
1248                         continue
1249                 }
1250                 saveAtTime = time.Now().Add(crunchLogUpdatePeriod)
1251                 saveAtSize = runner.LogCollection.Size() + crunchLogUpdateSize
1252                 saved, err := runner.saveLogCollection(false)
1253                 if err != nil {
1254                         runner.CrunchLog.Printf("error updating log collection: %s", err)
1255                         continue
1256                 }
1257
1258                 var updated arvados.Container
1259                 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1260                         "container": arvadosclient.Dict{"log": saved.PortableDataHash},
1261                 }, &updated)
1262                 if err != nil {
1263                         runner.CrunchLog.Printf("error updating container log to %s: %s", saved.PortableDataHash, err)
1264                         continue
1265                 }
1266
1267                 savedSize = size
1268         }
1269 }
1270
1271 // CaptureOutput saves data from the container's output directory if
1272 // needed, and updates the container output accordingly.
1273 func (runner *ContainerRunner) CaptureOutput() error {
1274         if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
1275                 // Output may have been set directly by the container, so
1276                 // refresh the container record to check.
1277                 err := runner.DispatcherArvClient.Get("containers", runner.Container.UUID,
1278                         nil, &runner.Container)
1279                 if err != nil {
1280                         return err
1281                 }
1282                 if runner.Container.Output != "" {
1283                         // Container output is already set.
1284                         runner.OutputPDH = &runner.Container.Output
1285                         return nil
1286                 }
1287         }
1288
1289         txt, err := (&copier{
1290                 client:        runner.containerClient,
1291                 arvClient:     runner.ContainerArvClient,
1292                 keepClient:    runner.ContainerKeepClient,
1293                 hostOutputDir: runner.HostOutputDir,
1294                 ctrOutputDir:  runner.Container.OutputPath,
1295                 binds:         runner.Binds,
1296                 mounts:        runner.Container.Mounts,
1297                 secretMounts:  runner.SecretMounts,
1298                 logger:        runner.CrunchLog,
1299         }).Copy()
1300         if err != nil {
1301                 return err
1302         }
1303         if n := len(regexp.MustCompile(` [0-9a-f]+\+\S*\+R`).FindAllStringIndex(txt, -1)); n > 0 {
1304                 runner.CrunchLog.Printf("Copying %d data blocks from remote input collections...", n)
1305                 fs, err := (&arvados.Collection{ManifestText: txt}).FileSystem(runner.containerClient, runner.ContainerKeepClient)
1306                 if err != nil {
1307                         return err
1308                 }
1309                 txt, err = fs.MarshalManifest(".")
1310                 if err != nil {
1311                         return err
1312                 }
1313         }
1314         var resp arvados.Collection
1315         err = runner.ContainerArvClient.Create("collections", arvadosclient.Dict{
1316                 "ensure_unique_name": true,
1317                 "collection": arvadosclient.Dict{
1318                         "is_trashed":    true,
1319                         "name":          "output for " + runner.Container.UUID,
1320                         "manifest_text": txt,
1321                 },
1322         }, &resp)
1323         if err != nil {
1324                 return fmt.Errorf("error creating output collection: %v", err)
1325         }
1326         runner.OutputPDH = &resp.PortableDataHash
1327         return nil
1328 }
1329
1330 func (runner *ContainerRunner) CleanupDirs() {
1331         if runner.ArvMount != nil {
1332                 var delay int64 = 8
1333                 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1334                 umount.Stdout = runner.CrunchLog
1335                 umount.Stderr = runner.CrunchLog
1336                 runner.CrunchLog.Printf("Running %v", umount.Args)
1337                 umnterr := umount.Start()
1338
1339                 if umnterr != nil {
1340                         runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1341                 } else {
1342                         // If arv-mount --unmount gets stuck for any reason, we
1343                         // don't want to wait for it forever.  Do Wait() in a goroutine
1344                         // so it doesn't block crunch-run.
1345                         umountExit := make(chan error)
1346                         go func() {
1347                                 mnterr := umount.Wait()
1348                                 if mnterr != nil {
1349                                         runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1350                                 }
1351                                 umountExit <- mnterr
1352                         }()
1353
1354                         for again := true; again; {
1355                                 again = false
1356                                 select {
1357                                 case <-umountExit:
1358                                         umount = nil
1359                                         again = true
1360                                 case <-runner.ArvMountExit:
1361                                         break
1362                                 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1363                                         runner.CrunchLog.Printf("Timed out waiting for unmount")
1364                                         if umount != nil {
1365                                                 umount.Process.Kill()
1366                                         }
1367                                         runner.ArvMount.Process.Kill()
1368                                 }
1369                         }
1370                 }
1371         }
1372
1373         if runner.ArvMountPoint != "" {
1374                 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1375                         runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1376                 }
1377         }
1378
1379         if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1380                 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1381         }
1382 }
1383
1384 // CommitLogs posts the collection containing the final container logs.
1385 func (runner *ContainerRunner) CommitLogs() error {
1386         func() {
1387                 // Hold cStateLock to prevent races on CrunchLog (e.g., stop()).
1388                 runner.cStateLock.Lock()
1389                 defer runner.cStateLock.Unlock()
1390
1391                 runner.CrunchLog.Print(runner.finalState)
1392
1393                 if runner.arvMountLog != nil {
1394                         runner.arvMountLog.Close()
1395                 }
1396                 runner.CrunchLog.Close()
1397
1398                 // Closing CrunchLog above allows them to be committed to Keep at this
1399                 // point, but re-open crunch log with ArvClient in case there are any
1400                 // other further errors (such as failing to write the log to Keep!)
1401                 // while shutting down
1402                 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{
1403                         ArvClient:     runner.DispatcherArvClient,
1404                         UUID:          runner.Container.UUID,
1405                         loggingStream: "crunch-run",
1406                         writeCloser:   nil,
1407                 })
1408                 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1409         }()
1410
1411         if runner.LogsPDH != nil {
1412                 // If we have already assigned something to LogsPDH,
1413                 // we must be closing the re-opened log, which won't
1414                 // end up getting attached to the container record and
1415                 // therefore doesn't need to be saved as a collection
1416                 // -- it exists only to send logs to other channels.
1417                 return nil
1418         }
1419         saved, err := runner.saveLogCollection(true)
1420         if err != nil {
1421                 return fmt.Errorf("error saving log collection: %s", err)
1422         }
1423         runner.logMtx.Lock()
1424         defer runner.logMtx.Unlock()
1425         runner.LogsPDH = &saved.PortableDataHash
1426         return nil
1427 }
1428
1429 func (runner *ContainerRunner) saveLogCollection(final bool) (response arvados.Collection, err error) {
1430         runner.logMtx.Lock()
1431         defer runner.logMtx.Unlock()
1432         if runner.LogsPDH != nil {
1433                 // Already finalized.
1434                 return
1435         }
1436         mt, err := runner.LogCollection.MarshalManifest(".")
1437         if err != nil {
1438                 err = fmt.Errorf("error creating log manifest: %v", err)
1439                 return
1440         }
1441         updates := arvadosclient.Dict{
1442                 "name":          "logs for " + runner.Container.UUID,
1443                 "manifest_text": mt,
1444         }
1445         if final {
1446                 updates["is_trashed"] = true
1447         } else {
1448                 exp := time.Now().Add(crunchLogUpdatePeriod * 24)
1449                 updates["trash_at"] = exp
1450                 updates["delete_at"] = exp
1451         }
1452         reqBody := arvadosclient.Dict{"collection": updates}
1453         if runner.logUUID == "" {
1454                 reqBody["ensure_unique_name"] = true
1455                 err = runner.DispatcherArvClient.Create("collections", reqBody, &response)
1456         } else {
1457                 err = runner.DispatcherArvClient.Update("collections", runner.logUUID, reqBody, &response)
1458         }
1459         if err != nil {
1460                 return
1461         }
1462         runner.logUUID = response.UUID
1463         return
1464 }
1465
1466 // UpdateContainerRunning updates the container state to "Running"
1467 func (runner *ContainerRunner) UpdateContainerRunning() error {
1468         runner.cStateLock.Lock()
1469         defer runner.cStateLock.Unlock()
1470         if runner.cCancelled {
1471                 return ErrCancelled
1472         }
1473         return runner.DispatcherArvClient.Update("containers", runner.Container.UUID,
1474                 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running", "gateway_address": runner.gateway.Address}}, nil)
1475 }
1476
1477 // ContainerToken returns the api_token the container (and any
1478 // arv-mount processes) are allowed to use.
1479 func (runner *ContainerRunner) ContainerToken() (string, error) {
1480         if runner.token != "" {
1481                 return runner.token, nil
1482         }
1483
1484         var auth arvados.APIClientAuthorization
1485         err := runner.DispatcherArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1486         if err != nil {
1487                 return "", err
1488         }
1489         runner.token = fmt.Sprintf("v2/%s/%s/%s", auth.UUID, auth.APIToken, runner.Container.UUID)
1490         return runner.token, nil
1491 }
1492
1493 // UpdateContainerFinal updates the container record state on API
1494 // server to "Complete" or "Cancelled"
1495 func (runner *ContainerRunner) UpdateContainerFinal() error {
1496         update := arvadosclient.Dict{}
1497         update["state"] = runner.finalState
1498         if runner.LogsPDH != nil {
1499                 update["log"] = *runner.LogsPDH
1500         }
1501         if runner.finalState == "Complete" {
1502                 if runner.ExitCode != nil {
1503                         update["exit_code"] = *runner.ExitCode
1504                 }
1505                 if runner.OutputPDH != nil {
1506                         update["output"] = *runner.OutputPDH
1507                 }
1508         }
1509         return runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1510 }
1511
1512 // IsCancelled returns the value of Cancelled, with goroutine safety.
1513 func (runner *ContainerRunner) IsCancelled() bool {
1514         runner.cStateLock.Lock()
1515         defer runner.cStateLock.Unlock()
1516         return runner.cCancelled
1517 }
1518
1519 // NewArvLogWriter creates an ArvLogWriter
1520 func (runner *ContainerRunner) NewArvLogWriter(name string) (io.WriteCloser, error) {
1521         writer, err := runner.LogCollection.OpenFile(name+".txt", os.O_CREATE|os.O_WRONLY, 0666)
1522         if err != nil {
1523                 return nil, err
1524         }
1525         return &ArvLogWriter{
1526                 ArvClient:     runner.DispatcherArvClient,
1527                 UUID:          runner.Container.UUID,
1528                 loggingStream: name,
1529                 writeCloser:   writer,
1530         }, nil
1531 }
1532
1533 // Run the full container lifecycle.
1534 func (runner *ContainerRunner) Run() (err error) {
1535         runner.CrunchLog.Printf("crunch-run %s started", cmd.Version.String())
1536         runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1537
1538         hostname, hosterr := os.Hostname()
1539         if hosterr != nil {
1540                 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1541         } else {
1542                 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1543         }
1544
1545         runner.finalState = "Queued"
1546
1547         defer func() {
1548                 runner.CleanupDirs()
1549
1550                 runner.CrunchLog.Printf("crunch-run finished")
1551                 runner.CrunchLog.Close()
1552         }()
1553
1554         err = runner.fetchContainerRecord()
1555         if err != nil {
1556                 return
1557         }
1558         if runner.Container.State != "Locked" {
1559                 return fmt.Errorf("dispatch error detected: container %q has state %q", runner.Container.UUID, runner.Container.State)
1560         }
1561
1562         defer func() {
1563                 // checkErr prints e (unless it's nil) and sets err to
1564                 // e (unless err is already non-nil). Thus, if err
1565                 // hasn't already been assigned when Run() returns,
1566                 // this cleanup func will cause Run() to return the
1567                 // first non-nil error that is passed to checkErr().
1568                 checkErr := func(errorIn string, e error) {
1569                         if e == nil {
1570                                 return
1571                         }
1572                         runner.CrunchLog.Printf("error in %s: %v", errorIn, e)
1573                         if err == nil {
1574                                 err = e
1575                         }
1576                         if runner.finalState == "Complete" {
1577                                 // There was an error in the finalization.
1578                                 runner.finalState = "Cancelled"
1579                         }
1580                 }
1581
1582                 // Log the error encountered in Run(), if any
1583                 checkErr("Run", err)
1584
1585                 if runner.finalState == "Queued" {
1586                         runner.UpdateContainerFinal()
1587                         return
1588                 }
1589
1590                 if runner.IsCancelled() {
1591                         runner.finalState = "Cancelled"
1592                         // but don't return yet -- we still want to
1593                         // capture partial output and write logs
1594                 }
1595
1596                 checkErr("CaptureOutput", runner.CaptureOutput())
1597                 checkErr("stopHoststat", runner.stopHoststat())
1598                 checkErr("CommitLogs", runner.CommitLogs())
1599                 checkErr("UpdateContainerFinal", runner.UpdateContainerFinal())
1600         }()
1601
1602         runner.setupSignals()
1603         err = runner.startHoststat()
1604         if err != nil {
1605                 return
1606         }
1607
1608         // check for and/or load image
1609         err = runner.LoadImage()
1610         if err != nil {
1611                 if !runner.checkBrokenNode(err) {
1612                         // Failed to load image but not due to a "broken node"
1613                         // condition, probably user error.
1614                         runner.finalState = "Cancelled"
1615                 }
1616                 err = fmt.Errorf("While loading container image: %v", err)
1617                 return
1618         }
1619
1620         // set up FUSE mount and binds
1621         err = runner.SetupMounts()
1622         if err != nil {
1623                 runner.finalState = "Cancelled"
1624                 err = fmt.Errorf("While setting up mounts: %v", err)
1625                 return
1626         }
1627
1628         err = runner.CreateContainer()
1629         if err != nil {
1630                 return
1631         }
1632         err = runner.LogHostInfo()
1633         if err != nil {
1634                 return
1635         }
1636         err = runner.LogNodeRecord()
1637         if err != nil {
1638                 return
1639         }
1640         err = runner.LogContainerRecord()
1641         if err != nil {
1642                 return
1643         }
1644
1645         if runner.IsCancelled() {
1646                 return
1647         }
1648
1649         err = runner.UpdateContainerRunning()
1650         if err != nil {
1651                 return
1652         }
1653         runner.finalState = "Cancelled"
1654
1655         err = runner.startCrunchstat()
1656         if err != nil {
1657                 return
1658         }
1659
1660         err = runner.StartContainer()
1661         if err != nil {
1662                 runner.checkBrokenNode(err)
1663                 return
1664         }
1665
1666         err = runner.WaitFinish()
1667         if err == nil && !runner.IsCancelled() {
1668                 runner.finalState = "Complete"
1669         }
1670         return
1671 }
1672
1673 // Fetch the current container record (uuid = runner.Container.UUID)
1674 // into runner.Container.
1675 func (runner *ContainerRunner) fetchContainerRecord() error {
1676         reader, err := runner.DispatcherArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1677         if err != nil {
1678                 return fmt.Errorf("error fetching container record: %v", err)
1679         }
1680         defer reader.Close()
1681
1682         dec := json.NewDecoder(reader)
1683         dec.UseNumber()
1684         err = dec.Decode(&runner.Container)
1685         if err != nil {
1686                 return fmt.Errorf("error decoding container record: %v", err)
1687         }
1688
1689         var sm struct {
1690                 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
1691         }
1692
1693         containerToken, err := runner.ContainerToken()
1694         if err != nil {
1695                 return fmt.Errorf("error getting container token: %v", err)
1696         }
1697
1698         runner.ContainerArvClient, runner.ContainerKeepClient,
1699                 runner.containerClient, err = runner.MkArvClient(containerToken)
1700         if err != nil {
1701                 return fmt.Errorf("error creating container API client: %v", err)
1702         }
1703
1704         err = runner.ContainerArvClient.Call("GET", "containers", runner.Container.UUID, "secret_mounts", nil, &sm)
1705         if err != nil {
1706                 if apierr, ok := err.(arvadosclient.APIServerError); !ok || apierr.HttpStatusCode != 404 {
1707                         return fmt.Errorf("error fetching secret_mounts: %v", err)
1708                 }
1709                 // ok && apierr.HttpStatusCode == 404, which means
1710                 // secret_mounts isn't supported by this API server.
1711         }
1712         runner.SecretMounts = sm.SecretMounts
1713
1714         return nil
1715 }
1716
1717 // NewContainerRunner creates a new container runner.
1718 func NewContainerRunner(dispatcherClient *arvados.Client,
1719         dispatcherArvClient IArvadosClient,
1720         dispatcherKeepClient IKeepClient,
1721         docker ThinDockerClient,
1722         containerUUID string) (*ContainerRunner, error) {
1723
1724         cr := &ContainerRunner{
1725                 dispatcherClient:     dispatcherClient,
1726                 DispatcherArvClient:  dispatcherArvClient,
1727                 DispatcherKeepClient: dispatcherKeepClient,
1728                 Docker:               docker,
1729         }
1730         cr.NewLogWriter = cr.NewArvLogWriter
1731         cr.RunArvMount = cr.ArvMountCmd
1732         cr.MkTempDir = ioutil.TempDir
1733         cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1734                 cl, err := arvadosclient.MakeArvadosClient()
1735                 if err != nil {
1736                         return nil, nil, nil, err
1737                 }
1738                 cl.ApiToken = token
1739                 kc, err := keepclient.MakeKeepClient(cl)
1740                 if err != nil {
1741                         return nil, nil, nil, err
1742                 }
1743                 c2 := arvados.NewClientFromEnv()
1744                 c2.AuthToken = token
1745                 return cl, kc, c2, nil
1746         }
1747         var err error
1748         cr.LogCollection, err = (&arvados.Collection{}).FileSystem(cr.dispatcherClient, cr.DispatcherKeepClient)
1749         if err != nil {
1750                 return nil, err
1751         }
1752         cr.Container.UUID = containerUUID
1753         w, err := cr.NewLogWriter("crunch-run")
1754         if err != nil {
1755                 return nil, err
1756         }
1757         cr.CrunchLog = NewThrottledLogger(w)
1758         cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1759
1760         loadLogThrottleParams(dispatcherArvClient)
1761         go cr.updateLogs()
1762
1763         return cr, nil
1764 }
1765
1766 func (command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
1767         flags := flag.NewFlagSet(prog, flag.ContinueOnError)
1768         statInterval := flags.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1769         cgroupRoot := flags.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1770         cgroupParent := flags.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1771         cgroupParentSubsystem := flags.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1772         caCertsPath := flags.String("ca-certs", "", "Path to TLS root certificates")
1773         detach := flags.Bool("detach", false, "Detach from parent process and run in the background")
1774         stdinEnv := flags.Bool("stdin-env", false, "Load environment variables from JSON message on stdin")
1775         sleep := flags.Duration("sleep", 0, "Delay before starting (testing use only)")
1776         kill := flags.Int("kill", -1, "Send signal to an existing crunch-run process for given UUID")
1777         list := flags.Bool("list", false, "List UUIDs of existing crunch-run processes")
1778         enableNetwork := flags.String("container-enable-networking", "default",
1779                 `Specify if networking should be enabled for container.  One of 'default', 'always':
1780         default: only enable networking if container requests it.
1781         always:  containers always have networking enabled
1782         `)
1783         networkMode := flags.String("container-network-mode", "default",
1784                 `Set networking mode for container.  Corresponds to Docker network mode (--net).
1785         `)
1786         memprofile := flags.String("memprofile", "", "write memory profile to `file` after running container")
1787         flags.Duration("check-containerd", 0, "Ignored. Exists for compatibility with older versions.")
1788
1789         ignoreDetachFlag := false
1790         if len(args) > 0 && args[0] == "-no-detach" {
1791                 // This process was invoked by a parent process, which
1792                 // has passed along its own arguments, including
1793                 // -detach, after the leading -no-detach flag.  Strip
1794                 // the leading -no-detach flag (it's not recognized by
1795                 // flags.Parse()) and ignore the -detach flag that
1796                 // comes later.
1797                 args = args[1:]
1798                 ignoreDetachFlag = true
1799         }
1800
1801         if err := flags.Parse(args); err == flag.ErrHelp {
1802                 return 0
1803         } else if err != nil {
1804                 log.Print(err)
1805                 return 1
1806         }
1807
1808         if *stdinEnv && !ignoreDetachFlag {
1809                 // Load env vars on stdin if asked (but not in a
1810                 // detached child process, in which case stdin is
1811                 // /dev/null).
1812                 err := loadEnv(os.Stdin)
1813                 if err != nil {
1814                         log.Print(err)
1815                         return 1
1816                 }
1817         }
1818
1819         containerID := flags.Arg(0)
1820
1821         switch {
1822         case *detach && !ignoreDetachFlag:
1823                 return Detach(containerID, prog, args, os.Stdout, os.Stderr)
1824         case *kill >= 0:
1825                 return KillProcess(containerID, syscall.Signal(*kill), os.Stdout, os.Stderr)
1826         case *list:
1827                 return ListProcesses(os.Stdout, os.Stderr)
1828         }
1829
1830         if containerID == "" {
1831                 log.Printf("usage: %s [options] UUID", prog)
1832                 return 1
1833         }
1834
1835         log.Printf("crunch-run %s started", cmd.Version.String())
1836         time.Sleep(*sleep)
1837
1838         if *caCertsPath != "" {
1839                 arvadosclient.CertFiles = []string{*caCertsPath}
1840         }
1841
1842         api, err := arvadosclient.MakeArvadosClient()
1843         if err != nil {
1844                 log.Printf("%s: %v", containerID, err)
1845                 return 1
1846         }
1847         api.Retries = 8
1848
1849         kc, kcerr := keepclient.MakeKeepClient(api)
1850         if kcerr != nil {
1851                 log.Printf("%s: %v", containerID, kcerr)
1852                 return 1
1853         }
1854         kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1855         kc.Retries = 4
1856
1857         // API version 1.21 corresponds to Docker 1.9, which is currently the
1858         // minimum version we want to support.
1859         docker, dockererr := dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1860
1861         cr, err := NewContainerRunner(arvados.NewClientFromEnv(), api, kc, docker, containerID)
1862         if err != nil {
1863                 log.Print(err)
1864                 return 1
1865         }
1866         if dockererr != nil {
1867                 cr.CrunchLog.Printf("%s: %v", containerID, dockererr)
1868                 cr.checkBrokenNode(dockererr)
1869                 cr.CrunchLog.Close()
1870                 return 1
1871         }
1872
1873         cr.gateway = Gateway{
1874                 Address:           os.Getenv("GatewayAddress"),
1875                 AuthSecret:        os.Getenv("GatewayAuthSecret"),
1876                 ContainerUUID:     containerID,
1877                 DockerContainerID: &cr.ContainerID,
1878                 Log:               cr.CrunchLog,
1879         }
1880         os.Unsetenv("GatewayAuthSecret")
1881         err = cr.gateway.Start()
1882         if err != nil {
1883                 log.Printf("error starting gateway server: %s", err)
1884                 return 1
1885         }
1886
1887         parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerID+".")
1888         if tmperr != nil {
1889                 log.Printf("%s: %v", containerID, tmperr)
1890                 return 1
1891         }
1892
1893         cr.parentTemp = parentTemp
1894         cr.statInterval = *statInterval
1895         cr.cgroupRoot = *cgroupRoot
1896         cr.expectCgroupParent = *cgroupParent
1897         cr.enableNetwork = *enableNetwork
1898         cr.networkMode = *networkMode
1899         if *cgroupParentSubsystem != "" {
1900                 p := findCgroup(*cgroupParentSubsystem)
1901                 cr.setCgroupParent = p
1902                 cr.expectCgroupParent = p
1903         }
1904
1905         runerr := cr.Run()
1906
1907         if *memprofile != "" {
1908                 f, err := os.Create(*memprofile)
1909                 if err != nil {
1910                         log.Printf("could not create memory profile: %s", err)
1911                 }
1912                 runtime.GC() // get up-to-date statistics
1913                 if err := pprof.WriteHeapProfile(f); err != nil {
1914                         log.Printf("could not write memory profile: %s", err)
1915                 }
1916                 closeerr := f.Close()
1917                 if closeerr != nil {
1918                         log.Printf("closing memprofile file: %s", err)
1919                 }
1920         }
1921
1922         if runerr != nil {
1923                 log.Printf("%s: %v", containerID, runerr)
1924                 return 1
1925         }
1926         return 0
1927 }
1928
1929 func loadEnv(rdr io.Reader) error {
1930         buf, err := ioutil.ReadAll(rdr)
1931         if err != nil {
1932                 return fmt.Errorf("read stdin: %s", err)
1933         }
1934         var env map[string]string
1935         err = json.Unmarshal(buf, &env)
1936         if err != nil {
1937                 return fmt.Errorf("decode stdin: %s", err)
1938         }
1939         for k, v := range env {
1940                 err = os.Setenv(k, v)
1941                 if err != nil {
1942                         return fmt.Errorf("setenv(%q): %s", k, err)
1943                 }
1944         }
1945         return nil
1946 }