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