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