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