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