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