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