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