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