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