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