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