10467: Update var names in parameterized test func.
[arvados.git] / services / crunch-run / crunchrun.go
1 package main
2
3 import (
4         "encoding/json"
5         "errors"
6         "flag"
7         "fmt"
8         "git.curoverse.com/arvados.git/lib/crunchstat"
9         "git.curoverse.com/arvados.git/sdk/go/arvados"
10         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
11         "git.curoverse.com/arvados.git/sdk/go/keepclient"
12         "git.curoverse.com/arvados.git/sdk/go/manifest"
13         "github.com/curoverse/dockerclient"
14         "io"
15         "io/ioutil"
16         "log"
17         "os"
18         "os/exec"
19         "os/signal"
20         "path"
21         "path/filepath"
22         "strings"
23         "sync"
24         "syscall"
25         "time"
26 )
27
28 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
29 type IArvadosClient interface {
30         Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
31         Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
32         Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
33         Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
34         Discovery(key string) (interface{}, error)
35 }
36
37 // ErrCancelled is the error returned when the container is cancelled.
38 var ErrCancelled = errors.New("Cancelled")
39
40 // IKeepClient is the minimal Keep API methods used by crunch-run.
41 type IKeepClient interface {
42         PutHB(hash string, buf []byte) (string, int, error)
43         ManifestFileReader(m manifest.Manifest, filename string) (keepclient.ReadCloserWithLen, error)
44 }
45
46 // NewLogWriter is a factory function to create a new log writer.
47 type NewLogWriter func(name string) io.WriteCloser
48
49 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
50
51 type MkTempDir func(string, string) (string, error)
52
53 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
54 type ThinDockerClient interface {
55         StopContainer(id string, timeout int) error
56         InspectImage(id string) (*dockerclient.ImageInfo, error)
57         LoadImage(reader io.Reader) error
58         CreateContainer(config *dockerclient.ContainerConfig, name string, authConfig *dockerclient.AuthConfig) (string, error)
59         StartContainer(id string, config *dockerclient.HostConfig) error
60         AttachContainer(id string, options *dockerclient.AttachOptions) (io.ReadCloser, error)
61         Wait(id string) <-chan dockerclient.WaitResult
62         RemoveImage(name string, force bool) ([]*dockerclient.ImageDelete, error)
63 }
64
65 // ContainerRunner is the main stateful struct used for a single execution of a
66 // container.
67 type ContainerRunner struct {
68         Docker    ThinDockerClient
69         ArvClient IArvadosClient
70         Kc        IKeepClient
71         arvados.Container
72         dockerclient.ContainerConfig
73         dockerclient.HostConfig
74         token       string
75         ContainerID string
76         ExitCode    *int
77         NewLogWriter
78         loggingDone   chan bool
79         CrunchLog     *ThrottledLogger
80         Stdout        io.WriteCloser
81         Stderr        *ThrottledLogger
82         LogCollection *CollectionWriter
83         LogsPDH       *string
84         RunArvMount
85         MkTempDir
86         ArvMount       *exec.Cmd
87         ArvMountPoint  string
88         HostOutputDir  string
89         CleanupTempDir []string
90         Binds          []string
91         OutputPDH      *string
92         CancelLock     sync.Mutex
93         Cancelled      bool
94         SigChan        chan os.Signal
95         ArvMountExit   chan error
96         finalState     string
97         trashLifetime  time.Duration
98
99         statLogger   io.WriteCloser
100         statReporter *crunchstat.Reporter
101         statInterval time.Duration
102         cgroupRoot   string
103         // What we expect the container's cgroup parent to be.
104         expectCgroupParent string
105         // What we tell docker to use as the container's cgroup
106         // parent. Note: Ideally we would use the same field for both
107         // expectCgroupParent and setCgroupParent, and just make it
108         // default to "docker". However, when using docker < 1.10 with
109         // systemd, specifying a non-empty cgroup parent (even the
110         // default value "docker") hits a docker bug
111         // (https://github.com/docker/docker/issues/17126). Using two
112         // separate fields makes it possible to use the "expect cgroup
113         // parent to be X" feature even on sites where the "specify
114         // cgroup parent" feature breaks.
115         setCgroupParent string
116 }
117
118 // SetupSignals sets up signal handling to gracefully terminate the underlying
119 // Docker container and update state when receiving a TERM, INT or QUIT signal.
120 func (runner *ContainerRunner) SetupSignals() {
121         runner.SigChan = make(chan os.Signal, 1)
122         signal.Notify(runner.SigChan, syscall.SIGTERM)
123         signal.Notify(runner.SigChan, syscall.SIGINT)
124         signal.Notify(runner.SigChan, syscall.SIGQUIT)
125
126         go func(sig <-chan os.Signal) {
127                 for range sig {
128                         if !runner.Cancelled {
129                                 runner.CancelLock.Lock()
130                                 runner.Cancelled = true
131                                 if runner.ContainerID != "" {
132                                         runner.Docker.StopContainer(runner.ContainerID, 10)
133                                 }
134                                 runner.CancelLock.Unlock()
135                         }
136                 }
137         }(runner.SigChan)
138 }
139
140 // LoadImage determines the docker image id from the container record and
141 // checks if it is available in the local Docker image store.  If not, it loads
142 // the image from Keep.
143 func (runner *ContainerRunner) LoadImage() (err error) {
144
145         runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
146
147         var collection arvados.Collection
148         err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
149         if err != nil {
150                 return fmt.Errorf("While getting container image collection: %v", err)
151         }
152         manifest := manifest.Manifest{Text: collection.ManifestText}
153         var img, imageID string
154         for ms := range manifest.StreamIter() {
155                 img = ms.FileStreamSegments[0].Name
156                 if !strings.HasSuffix(img, ".tar") {
157                         return fmt.Errorf("First file in the container image collection does not end in .tar")
158                 }
159                 imageID = img[:len(img)-4]
160         }
161
162         runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
163
164         _, err = runner.Docker.InspectImage(imageID)
165         if err != nil {
166                 runner.CrunchLog.Print("Loading Docker image from keep")
167
168                 var readCloser io.ReadCloser
169                 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
170                 if err != nil {
171                         return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
172                 }
173
174                 err = runner.Docker.LoadImage(readCloser)
175                 if err != nil {
176                         return fmt.Errorf("While loading container image into Docker: %v", err)
177                 }
178         } else {
179                 runner.CrunchLog.Print("Docker image is available")
180         }
181
182         runner.ContainerConfig.Image = imageID
183
184         return nil
185 }
186
187 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
188         c = exec.Command("arv-mount", arvMountCmd...)
189
190         // Copy our environment, but override ARVADOS_API_TOKEN with
191         // the container auth token.
192         c.Env = nil
193         for _, s := range os.Environ() {
194                 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
195                         c.Env = append(c.Env, s)
196                 }
197         }
198         c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
199
200         nt := NewThrottledLogger(runner.NewLogWriter("arv-mount"))
201         c.Stdout = nt
202         c.Stderr = nt
203
204         err = c.Start()
205         if err != nil {
206                 return nil, err
207         }
208
209         statReadme := make(chan bool)
210         runner.ArvMountExit = make(chan error)
211
212         keepStatting := true
213         go func() {
214                 for keepStatting {
215                         time.Sleep(100 * time.Millisecond)
216                         _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
217                         if err == nil {
218                                 keepStatting = false
219                                 statReadme <- true
220                         }
221                 }
222                 close(statReadme)
223         }()
224
225         go func() {
226                 runner.ArvMountExit <- c.Wait()
227                 close(runner.ArvMountExit)
228         }()
229
230         select {
231         case <-statReadme:
232                 break
233         case err := <-runner.ArvMountExit:
234                 runner.ArvMount = nil
235                 keepStatting = false
236                 return nil, err
237         }
238
239         return c, nil
240 }
241
242 func (runner *ContainerRunner) SetupMounts() (err error) {
243         runner.ArvMountPoint, err = runner.MkTempDir("", "keep")
244         if err != nil {
245                 return fmt.Errorf("While creating keep mount temp dir: %v", err)
246         }
247
248         runner.CleanupTempDir = append(runner.CleanupTempDir, runner.ArvMountPoint)
249
250         pdhOnly := true
251         tmpcount := 0
252         arvMountCmd := []string{"--foreground", "--allow-other", "--read-write"}
253
254         if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
255                 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
256         }
257
258         collectionPaths := []string{}
259         runner.Binds = nil
260
261         for bind, mnt := range runner.Container.Mounts {
262                 if bind == "stdout" {
263                         // Is it a "file" mount kind?
264                         if mnt.Kind != "file" {
265                                 return fmt.Errorf("Unsupported mount kind '%s' for stdout. Only 'file' is supported.", mnt.Kind)
266                         }
267
268                         // Does path start with OutputPath?
269                         prefix := runner.Container.OutputPath
270                         if !strings.HasSuffix(prefix, "/") {
271                                 prefix += "/"
272                         }
273                         if !strings.HasPrefix(mnt.Path, prefix) {
274                                 return fmt.Errorf("Stdout path does not start with OutputPath: %s, %s", mnt.Path, prefix)
275                         }
276                 }
277
278                 switch {
279                 case mnt.Kind == "collection":
280                         var src string
281                         if mnt.UUID != "" && mnt.PortableDataHash != "" {
282                                 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
283                         }
284                         if mnt.UUID != "" {
285                                 if mnt.Writable {
286                                         return fmt.Errorf("Writing to existing collections currently not permitted.")
287                                 }
288                                 pdhOnly = false
289                                 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
290                         } else if mnt.PortableDataHash != "" {
291                                 if mnt.Writable {
292                                         return fmt.Errorf("Can never write to a collection specified by portable data hash")
293                                 }
294                                 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
295                         } else {
296                                 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
297                                 arvMountCmd = append(arvMountCmd, "--mount-tmp")
298                                 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
299                                 tmpcount += 1
300                         }
301                         if mnt.Writable {
302                                 if bind == runner.Container.OutputPath {
303                                         runner.HostOutputDir = src
304                                 }
305                                 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
306                         } else {
307                                 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
308                         }
309                         collectionPaths = append(collectionPaths, src)
310
311                 case mnt.Kind == "tmp" && bind == runner.Container.OutputPath:
312                         runner.HostOutputDir, err = runner.MkTempDir("", "")
313                         if err != nil {
314                                 return fmt.Errorf("While creating mount temp dir: %v", err)
315                         }
316                         st, staterr := os.Stat(runner.HostOutputDir)
317                         if staterr != nil {
318                                 return fmt.Errorf("While Stat on temp dir: %v", staterr)
319                         }
320                         err = os.Chmod(runner.HostOutputDir, st.Mode()|os.ModeSetgid|0777)
321                         if staterr != nil {
322                                 return fmt.Errorf("While Chmod temp dir: %v", err)
323                         }
324                         runner.CleanupTempDir = append(runner.CleanupTempDir, runner.HostOutputDir)
325                         runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", runner.HostOutputDir, bind))
326
327                 case mnt.Kind == "tmp":
328                         runner.Binds = append(runner.Binds, bind)
329
330                 case mnt.Kind == "json":
331                         jsondata, err := json.Marshal(mnt.Content)
332                         if err != nil {
333                                 return fmt.Errorf("encoding json data: %v", err)
334                         }
335                         // Create a tempdir with a single file
336                         // (instead of just a tempfile): this way we
337                         // can ensure the file is world-readable
338                         // inside the container, without having to
339                         // make it world-readable on the docker host.
340                         tmpdir, err := runner.MkTempDir("", "")
341                         if err != nil {
342                                 return fmt.Errorf("creating temp dir: %v", err)
343                         }
344                         runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
345                         tmpfn := filepath.Join(tmpdir, "mountdata.json")
346                         err = ioutil.WriteFile(tmpfn, jsondata, 0644)
347                         if err != nil {
348                                 return fmt.Errorf("writing temp file: %v", err)
349                         }
350                         runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
351                 }
352         }
353
354         if runner.HostOutputDir == "" {
355                 return fmt.Errorf("Output path does not correspond to a writable mount point")
356         }
357
358         if pdhOnly {
359                 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
360         } else {
361                 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
362         }
363         arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
364
365         token, err := runner.ContainerToken()
366         if err != nil {
367                 return fmt.Errorf("could not get container token: %s", err)
368         }
369
370         runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
371         if err != nil {
372                 return fmt.Errorf("While trying to start arv-mount: %v", err)
373         }
374
375         for _, p := range collectionPaths {
376                 _, err = os.Stat(p)
377                 if err != nil {
378                         return fmt.Errorf("While checking that input files exist: %v", err)
379                 }
380         }
381
382         return nil
383 }
384
385 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
386         // Handle docker log protocol
387         // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
388
389         header := make([]byte, 8)
390         for {
391                 _, readerr := io.ReadAtLeast(containerReader, header, 8)
392
393                 if readerr == nil {
394                         readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
395                         if header[0] == 1 {
396                                 // stdout
397                                 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
398                         } else {
399                                 // stderr
400                                 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
401                         }
402                 }
403
404                 if readerr != nil {
405                         if readerr != io.EOF {
406                                 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
407                         }
408
409                         closeerr := runner.Stdout.Close()
410                         if closeerr != nil {
411                                 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
412                         }
413
414                         closeerr = runner.Stderr.Close()
415                         if closeerr != nil {
416                                 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
417                         }
418
419                         if runner.statReporter != nil {
420                                 runner.statReporter.Stop()
421                                 closeerr = runner.statLogger.Close()
422                                 if closeerr != nil {
423                                         runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
424                                 }
425                         }
426
427                         runner.loggingDone <- true
428                         close(runner.loggingDone)
429                         return
430                 }
431         }
432 }
433
434 func (runner *ContainerRunner) StartCrunchstat() {
435         runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
436         runner.statReporter = &crunchstat.Reporter{
437                 CID:          runner.ContainerID,
438                 Logger:       log.New(runner.statLogger, "", 0),
439                 CgroupParent: runner.expectCgroupParent,
440                 CgroupRoot:   runner.cgroupRoot,
441                 PollPeriod:   runner.statInterval,
442         }
443         runner.statReporter.Start()
444 }
445
446 // AttachLogs connects the docker container stdout and stderr logs to the
447 // Arvados logger which logs to Keep and the API server logs table.
448 func (runner *ContainerRunner) AttachStreams() (err error) {
449
450         runner.CrunchLog.Print("Attaching container streams")
451
452         var containerReader io.Reader
453         containerReader, err = runner.Docker.AttachContainer(runner.ContainerID,
454                 &dockerclient.AttachOptions{Stream: true, Stdout: true, Stderr: true})
455         if err != nil {
456                 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
457         }
458
459         runner.loggingDone = make(chan bool)
460
461         if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
462                 stdoutPath := stdoutMnt.Path[len(runner.Container.OutputPath):]
463                 index := strings.LastIndex(stdoutPath, "/")
464                 if index > 0 {
465                         subdirs := stdoutPath[:index]
466                         if subdirs != "" {
467                                 st, err := os.Stat(runner.HostOutputDir)
468                                 if err != nil {
469                                         return fmt.Errorf("While Stat on temp dir: %v", err)
470                                 }
471                                 stdoutPath := path.Join(runner.HostOutputDir, subdirs)
472                                 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
473                                 if err != nil {
474                                         return fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
475                                 }
476                         }
477                 }
478                 stdoutFile, err := os.Create(path.Join(runner.HostOutputDir, stdoutPath))
479                 if err != nil {
480                         return fmt.Errorf("While creating stdout file: %v", err)
481                 }
482                 runner.Stdout = stdoutFile
483         } else {
484                 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
485         }
486         runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
487
488         go runner.ProcessDockerAttach(containerReader)
489
490         return nil
491 }
492
493 // CreateContainer creates the docker container.
494 func (runner *ContainerRunner) CreateContainer() error {
495         runner.CrunchLog.Print("Creating Docker container")
496
497         runner.ContainerConfig.Cmd = runner.Container.Command
498         if runner.Container.Cwd != "." {
499                 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
500         }
501
502         for k, v := range runner.Container.Environment {
503                 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
504         }
505         if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
506                 tok, err := runner.ContainerToken()
507                 if err != nil {
508                         return err
509                 }
510                 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
511                         "ARVADOS_API_TOKEN="+tok,
512                         "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
513                         "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
514                 )
515                 runner.ContainerConfig.NetworkDisabled = false
516         } else {
517                 runner.ContainerConfig.NetworkDisabled = true
518         }
519
520         var err error
521         runner.ContainerID, err = runner.Docker.CreateContainer(&runner.ContainerConfig, "", nil)
522         if err != nil {
523                 return fmt.Errorf("While creating container: %v", err)
524         }
525
526         runner.HostConfig = dockerclient.HostConfig{
527                 Binds:        runner.Binds,
528                 CgroupParent: runner.setCgroupParent,
529                 LogConfig: dockerclient.LogConfig{
530                         Type: "none",
531                 },
532         }
533
534         return runner.AttachStreams()
535 }
536
537 // StartContainer starts the docker container created by CreateContainer.
538 func (runner *ContainerRunner) StartContainer() error {
539         runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
540         err := runner.Docker.StartContainer(runner.ContainerID, &runner.HostConfig)
541         if err != nil {
542                 return fmt.Errorf("could not start container: %v", err)
543         }
544         return nil
545 }
546
547 // WaitFinish waits for the container to terminate, capture the exit code, and
548 // close the stdout/stderr logging.
549 func (runner *ContainerRunner) WaitFinish() error {
550         runner.CrunchLog.Print("Waiting for container to finish")
551
552         result := runner.Docker.Wait(runner.ContainerID)
553         wr := <-result
554         if wr.Error != nil {
555                 return fmt.Errorf("While waiting for container to finish: %v", wr.Error)
556         }
557         runner.ExitCode = &wr.ExitCode
558
559         // wait for stdout/stderr to complete
560         <-runner.loggingDone
561
562         return nil
563 }
564
565 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
566 func (runner *ContainerRunner) CaptureOutput() error {
567         if runner.finalState != "Complete" {
568                 return nil
569         }
570
571         if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
572                 // Output may have been set directly by the container, so
573                 // refresh the container record to check.
574                 err := runner.ArvClient.Get("containers", runner.Container.UUID,
575                         nil, &runner.Container)
576                 if err != nil {
577                         return err
578                 }
579                 if runner.Container.Output != "" {
580                         // Container output is already set.
581                         runner.OutputPDH = &runner.Container.Output
582                         return nil
583                 }
584         }
585
586         if runner.HostOutputDir == "" {
587                 return nil
588         }
589
590         _, err := os.Stat(runner.HostOutputDir)
591         if err != nil {
592                 return fmt.Errorf("While checking host output path: %v", err)
593         }
594
595         var manifestText string
596
597         collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
598         _, err = os.Stat(collectionMetafile)
599         if err != nil {
600                 // Regular directory
601                 cw := CollectionWriter{runner.Kc, nil, sync.Mutex{}}
602                 manifestText, err = cw.WriteTree(runner.HostOutputDir, runner.CrunchLog.Logger)
603                 if err != nil {
604                         return fmt.Errorf("While uploading output files: %v", err)
605                 }
606         } else {
607                 // FUSE mount directory
608                 file, openerr := os.Open(collectionMetafile)
609                 if openerr != nil {
610                         return fmt.Errorf("While opening FUSE metafile: %v", err)
611                 }
612                 defer file.Close()
613
614                 var rec arvados.Collection
615                 err = json.NewDecoder(file).Decode(&rec)
616                 if err != nil {
617                         return fmt.Errorf("While reading FUSE metafile: %v", err)
618                 }
619                 manifestText = rec.ManifestText
620         }
621
622         var response arvados.Collection
623         err = runner.ArvClient.Create("collections",
624                 arvadosclient.Dict{
625                         "collection": arvadosclient.Dict{
626                                 "expires_at":    time.Now().Add(runner.trashLifetime).Format(time.RFC3339),
627                                 "name":          "output for " + runner.Container.UUID,
628                                 "manifest_text": manifestText}},
629                 &response)
630         if err != nil {
631                 return fmt.Errorf("While creating output collection: %v", err)
632         }
633         runner.OutputPDH = &response.PortableDataHash
634         return nil
635 }
636
637 func (runner *ContainerRunner) loadDiscoveryVars() {
638         tl, err := runner.ArvClient.Discovery("defaultTrashLifetime")
639         if err != nil {
640                 log.Fatalf("getting defaultTrashLifetime from discovery document: %s", err)
641         }
642         runner.trashLifetime = time.Duration(tl.(float64)) * time.Second
643 }
644
645 func (runner *ContainerRunner) CleanupDirs() {
646         if runner.ArvMount != nil {
647                 umount := exec.Command("fusermount", "-z", "-u", runner.ArvMountPoint)
648                 umnterr := umount.Run()
649                 if umnterr != nil {
650                         runner.CrunchLog.Printf("While running fusermount: %v", umnterr)
651                 }
652
653                 mnterr := <-runner.ArvMountExit
654                 if mnterr != nil {
655                         runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
656                 }
657         }
658
659         for _, tmpdir := range runner.CleanupTempDir {
660                 rmerr := os.RemoveAll(tmpdir)
661                 if rmerr != nil {
662                         runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
663                 }
664         }
665 }
666
667 // CommitLogs posts the collection containing the final container logs.
668 func (runner *ContainerRunner) CommitLogs() error {
669         runner.CrunchLog.Print(runner.finalState)
670         runner.CrunchLog.Close()
671
672         // Closing CrunchLog above allows it to be committed to Keep at this
673         // point, but re-open crunch log with ArvClient in case there are any
674         // other further (such as failing to write the log to Keep!) while
675         // shutting down
676         runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{runner.ArvClient, runner.Container.UUID,
677                 "crunch-run", nil})
678
679         if runner.LogsPDH != nil {
680                 // If we have already assigned something to LogsPDH,
681                 // we must be closing the re-opened log, which won't
682                 // end up getting attached to the container record and
683                 // therefore doesn't need to be saved as a collection
684                 // -- it exists only to send logs to other channels.
685                 return nil
686         }
687
688         mt, err := runner.LogCollection.ManifestText()
689         if err != nil {
690                 return fmt.Errorf("While creating log manifest: %v", err)
691         }
692
693         var response arvados.Collection
694         err = runner.ArvClient.Create("collections",
695                 arvadosclient.Dict{
696                         "collection": arvadosclient.Dict{
697                                 "expires_at":    time.Now().Add(runner.trashLifetime).Format(time.RFC3339),
698                                 "name":          "logs for " + runner.Container.UUID,
699                                 "manifest_text": mt}},
700                 &response)
701         if err != nil {
702                 return fmt.Errorf("While creating log collection: %v", err)
703         }
704         runner.LogsPDH = &response.PortableDataHash
705         return nil
706 }
707
708 // UpdateContainerRunning updates the container state to "Running"
709 func (runner *ContainerRunner) UpdateContainerRunning() error {
710         runner.CancelLock.Lock()
711         defer runner.CancelLock.Unlock()
712         if runner.Cancelled {
713                 return ErrCancelled
714         }
715         return runner.ArvClient.Update("containers", runner.Container.UUID,
716                 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
717 }
718
719 // ContainerToken returns the api_token the container (and any
720 // arv-mount processes) are allowed to use.
721 func (runner *ContainerRunner) ContainerToken() (string, error) {
722         if runner.token != "" {
723                 return runner.token, nil
724         }
725
726         var auth arvados.APIClientAuthorization
727         err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
728         if err != nil {
729                 return "", err
730         }
731         runner.token = auth.APIToken
732         return runner.token, nil
733 }
734
735 // UpdateContainerComplete updates the container record state on API
736 // server to "Complete" or "Cancelled"
737 func (runner *ContainerRunner) UpdateContainerFinal() error {
738         update := arvadosclient.Dict{}
739         update["state"] = runner.finalState
740         if runner.finalState == "Complete" {
741                 if runner.LogsPDH != nil {
742                         update["log"] = *runner.LogsPDH
743                 }
744                 if runner.ExitCode != nil {
745                         update["exit_code"] = *runner.ExitCode
746                 }
747                 if runner.OutputPDH != nil {
748                         update["output"] = *runner.OutputPDH
749                 }
750         }
751         return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
752 }
753
754 // IsCancelled returns the value of Cancelled, with goroutine safety.
755 func (runner *ContainerRunner) IsCancelled() bool {
756         runner.CancelLock.Lock()
757         defer runner.CancelLock.Unlock()
758         return runner.Cancelled
759 }
760
761 // NewArvLogWriter creates an ArvLogWriter
762 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
763         return &ArvLogWriter{runner.ArvClient, runner.Container.UUID, name, runner.LogCollection.Open(name + ".txt")}
764 }
765
766 // Run the full container lifecycle.
767 func (runner *ContainerRunner) Run() (err error) {
768         runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
769
770         hostname, hosterr := os.Hostname()
771         if hosterr != nil {
772                 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
773         } else {
774                 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
775         }
776
777         // Clean up temporary directories _after_ finalizing
778         // everything (if we've made any by then)
779         defer runner.CleanupDirs()
780
781         runner.finalState = "Queued"
782
783         defer func() {
784                 // checkErr prints e (unless it's nil) and sets err to
785                 // e (unless err is already non-nil). Thus, if err
786                 // hasn't already been assigned when Run() returns,
787                 // this cleanup func will cause Run() to return the
788                 // first non-nil error that is passed to checkErr().
789                 checkErr := func(e error) {
790                         if e == nil {
791                                 return
792                         }
793                         runner.CrunchLog.Print(e)
794                         if err == nil {
795                                 err = e
796                         }
797                 }
798
799                 // Log the error encountered in Run(), if any
800                 checkErr(err)
801
802                 if runner.finalState == "Queued" {
803                         runner.UpdateContainerFinal()
804                         return
805                 }
806
807                 if runner.IsCancelled() {
808                         runner.finalState = "Cancelled"
809                         // but don't return yet -- we still want to
810                         // capture partial output and write logs
811                 }
812
813                 checkErr(runner.CaptureOutput())
814                 checkErr(runner.CommitLogs())
815                 checkErr(runner.UpdateContainerFinal())
816
817                 // The real log is already closed, but then we opened
818                 // a new one in case we needed to log anything while
819                 // finalizing.
820                 runner.CrunchLog.Close()
821         }()
822
823         err = runner.ArvClient.Get("containers", runner.Container.UUID, nil, &runner.Container)
824         if err != nil {
825                 err = fmt.Errorf("While getting container record: %v", err)
826                 return
827         }
828
829         // setup signal handling
830         runner.SetupSignals()
831
832         // check for and/or load image
833         err = runner.LoadImage()
834         if err != nil {
835                 err = fmt.Errorf("While loading container image: %v", err)
836                 return
837         }
838
839         // set up FUSE mount and binds
840         err = runner.SetupMounts()
841         if err != nil {
842                 err = fmt.Errorf("While setting up mounts: %v", err)
843                 return
844         }
845
846         err = runner.CreateContainer()
847         if err != nil {
848                 return
849         }
850
851         runner.StartCrunchstat()
852
853         if runner.IsCancelled() {
854                 return
855         }
856
857         err = runner.UpdateContainerRunning()
858         if err != nil {
859                 return
860         }
861         runner.finalState = "Cancelled"
862
863         err = runner.StartContainer()
864         if err != nil {
865                 return
866         }
867
868         err = runner.WaitFinish()
869         if err == nil {
870                 runner.finalState = "Complete"
871         }
872         return
873 }
874
875 // NewContainerRunner creates a new container runner.
876 func NewContainerRunner(api IArvadosClient,
877         kc IKeepClient,
878         docker ThinDockerClient,
879         containerUUID string) *ContainerRunner {
880
881         cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
882         cr.NewLogWriter = cr.NewArvLogWriter
883         cr.RunArvMount = cr.ArvMountCmd
884         cr.MkTempDir = ioutil.TempDir
885         cr.LogCollection = &CollectionWriter{kc, nil, sync.Mutex{}}
886         cr.Container.UUID = containerUUID
887         cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
888         cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
889         cr.loadDiscoveryVars()
890         return cr
891 }
892
893 func main() {
894         statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
895         cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
896         cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
897         cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
898         flag.Parse()
899
900         containerId := flag.Arg(0)
901
902         api, err := arvadosclient.MakeArvadosClient()
903         if err != nil {
904                 log.Fatalf("%s: %v", containerId, err)
905         }
906         api.Retries = 8
907
908         var kc *keepclient.KeepClient
909         kc, err = keepclient.MakeKeepClient(api)
910         if err != nil {
911                 log.Fatalf("%s: %v", containerId, err)
912         }
913         kc.Retries = 4
914
915         var docker *dockerclient.DockerClient
916         docker, err = dockerclient.NewDockerClient("unix:///var/run/docker.sock", nil)
917         if err != nil {
918                 log.Fatalf("%s: %v", containerId, err)
919         }
920
921         cr := NewContainerRunner(api, kc, docker, containerId)
922         cr.statInterval = *statInterval
923         cr.cgroupRoot = *cgroupRoot
924         cr.expectCgroupParent = *cgroupParent
925         if *cgroupParentSubsystem != "" {
926                 p := findCgroup(*cgroupParentSubsystem)
927                 cr.setCgroupParent = p
928                 cr.expectCgroupParent = p
929         }
930
931         err = cr.Run()
932         if err != nil {
933                 log.Fatalf("%s: %v", containerId, err)
934         }
935
936 }