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