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