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