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