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