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