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