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