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