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