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