Merge branch '8567-docker-migrator' refs #8567
[arvados.git] / services / crunch-run / crunchrun.go
1 package main
2
3 import (
4         "encoding/json"
5         "errors"
6         "flag"
7         "fmt"
8         "io"
9         "io/ioutil"
10         "log"
11         "os"
12         "os/exec"
13         "os/signal"
14         "path"
15         "path/filepath"
16         "sort"
17         "strings"
18         "sync"
19         "syscall"
20         "time"
21
22         "git.curoverse.com/arvados.git/lib/crunchstat"
23         "git.curoverse.com/arvados.git/sdk/go/arvados"
24         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
25         "git.curoverse.com/arvados.git/sdk/go/keepclient"
26         "git.curoverse.com/arvados.git/sdk/go/manifest"
27         "github.com/curoverse/dockerclient"
28 )
29
30 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
31 type IArvadosClient interface {
32         Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
33         Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
34         Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
35         Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
36         CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
37         Discovery(key string) (interface{}, error)
38 }
39
40 // ErrCancelled is the error returned when the container is cancelled.
41 var ErrCancelled = errors.New("Cancelled")
42
43 // IKeepClient is the minimal Keep API methods used by crunch-run.
44 type IKeepClient interface {
45         PutHB(hash string, buf []byte) (string, int, error)
46         ManifestFileReader(m manifest.Manifest, filename string) (keepclient.Reader, error)
47 }
48
49 // NewLogWriter is a factory function to create a new log writer.
50 type NewLogWriter func(name string) io.WriteCloser
51
52 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
53
54 type MkTempDir func(string, string) (string, error)
55
56 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
57 type ThinDockerClient interface {
58         StopContainer(id string, timeout int) error
59         InspectImage(id string) (*dockerclient.ImageInfo, error)
60         LoadImage(reader io.Reader) error
61         CreateContainer(config *dockerclient.ContainerConfig, name string, authConfig *dockerclient.AuthConfig) (string, error)
62         StartContainer(id string, config *dockerclient.HostConfig) error
63         AttachContainer(id string, options *dockerclient.AttachOptions) (io.ReadCloser, error)
64         Wait(id string) <-chan dockerclient.WaitResult
65         RemoveImage(name string, force bool) ([]*dockerclient.ImageDelete, error)
66 }
67
68 // ContainerRunner is the main stateful struct used for a single execution of a
69 // container.
70 type ContainerRunner struct {
71         Docker    ThinDockerClient
72         ArvClient IArvadosClient
73         Kc        IKeepClient
74         arvados.Container
75         dockerclient.ContainerConfig
76         dockerclient.HostConfig
77         token       string
78         ContainerID string
79         ExitCode    *int
80         NewLogWriter
81         loggingDone   chan bool
82         CrunchLog     *ThrottledLogger
83         Stdout        io.WriteCloser
84         Stderr        *ThrottledLogger
85         LogCollection *CollectionWriter
86         LogsPDH       *string
87         RunArvMount
88         MkTempDir
89         ArvMount       *exec.Cmd
90         ArvMountPoint  string
91         HostOutputDir  string
92         CleanupTempDir []string
93         Binds          []string
94         OutputPDH      *string
95         SigChan        chan os.Signal
96         ArvMountExit   chan error
97         finalState     string
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         cStateLock sync.Mutex
118         cStarted   bool // StartContainer() succeeded
119         cCancelled bool // StopContainer() invoked
120
121         enableNetwork string // one of "default" or "always"
122         networkMode   string // passed through to HostConfig.NetworkMode
123 }
124
125 // SetupSignals sets up signal handling to gracefully terminate the underlying
126 // Docker container and update state when receiving a TERM, INT or QUIT signal.
127 func (runner *ContainerRunner) SetupSignals() {
128         runner.SigChan = make(chan os.Signal, 1)
129         signal.Notify(runner.SigChan, syscall.SIGTERM)
130         signal.Notify(runner.SigChan, syscall.SIGINT)
131         signal.Notify(runner.SigChan, syscall.SIGQUIT)
132
133         go func(sig chan os.Signal) {
134                 <-sig
135                 runner.stop()
136                 signal.Stop(sig)
137         }(runner.SigChan)
138 }
139
140 // stop the underlying Docker container.
141 func (runner *ContainerRunner) stop() {
142         runner.cStateLock.Lock()
143         defer runner.cStateLock.Unlock()
144         if runner.cCancelled {
145                 return
146         }
147         runner.cCancelled = true
148         if runner.cStarted {
149                 err := runner.Docker.StopContainer(runner.ContainerID, 10)
150                 if err != nil {
151                         log.Printf("StopContainer failed: %s", err)
152                 }
153         }
154 }
155
156 // LoadImage determines the docker image id from the container record and
157 // checks if it is available in the local Docker image store.  If not, it loads
158 // the image from Keep.
159 func (runner *ContainerRunner) LoadImage() (err error) {
160
161         runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
162
163         var collection arvados.Collection
164         err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
165         if err != nil {
166                 return fmt.Errorf("While getting container image collection: %v", err)
167         }
168         manifest := manifest.Manifest{Text: collection.ManifestText}
169         var img, imageID string
170         for ms := range manifest.StreamIter() {
171                 img = ms.FileStreamSegments[0].Name
172                 if !strings.HasSuffix(img, ".tar") {
173                         return fmt.Errorf("First file in the container image collection does not end in .tar")
174                 }
175                 imageID = img[:len(img)-4]
176         }
177
178         runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
179
180         _, err = runner.Docker.InspectImage(imageID)
181         if err != nil {
182                 runner.CrunchLog.Print("Loading Docker image from keep")
183
184                 var readCloser io.ReadCloser
185                 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
186                 if err != nil {
187                         return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
188                 }
189
190                 err = runner.Docker.LoadImage(readCloser)
191                 if err != nil {
192                         return fmt.Errorf("While loading container image into Docker: %v", err)
193                 }
194         } else {
195                 runner.CrunchLog.Print("Docker image is available")
196         }
197
198         runner.ContainerConfig.Image = imageID
199
200         return nil
201 }
202
203 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
204         c = exec.Command("arv-mount", arvMountCmd...)
205
206         // Copy our environment, but override ARVADOS_API_TOKEN with
207         // the container auth token.
208         c.Env = nil
209         for _, s := range os.Environ() {
210                 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
211                         c.Env = append(c.Env, s)
212                 }
213         }
214         c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
215
216         nt := NewThrottledLogger(runner.NewLogWriter("arv-mount"))
217         c.Stdout = nt
218         c.Stderr = nt
219
220         err = c.Start()
221         if err != nil {
222                 return nil, err
223         }
224
225         statReadme := make(chan bool)
226         runner.ArvMountExit = make(chan error)
227
228         keepStatting := true
229         go func() {
230                 for keepStatting {
231                         time.Sleep(100 * time.Millisecond)
232                         _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
233                         if err == nil {
234                                 keepStatting = false
235                                 statReadme <- true
236                         }
237                 }
238                 close(statReadme)
239         }()
240
241         go func() {
242                 runner.ArvMountExit <- c.Wait()
243                 close(runner.ArvMountExit)
244         }()
245
246         select {
247         case <-statReadme:
248                 break
249         case err := <-runner.ArvMountExit:
250                 runner.ArvMount = nil
251                 keepStatting = false
252                 return nil, err
253         }
254
255         return c, nil
256 }
257
258 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
259         if runner.ArvMountPoint == "" {
260                 runner.ArvMountPoint, err = runner.MkTempDir("", prefix)
261         }
262         return
263 }
264
265 func (runner *ContainerRunner) SetupMounts() (err error) {
266         err = runner.SetupArvMountPoint("keep")
267         if err != nil {
268                 return fmt.Errorf("While creating keep mount temp dir: %v", err)
269         }
270
271         runner.CleanupTempDir = append(runner.CleanupTempDir, runner.ArvMountPoint)
272
273         pdhOnly := true
274         tmpcount := 0
275         arvMountCmd := []string{"--foreground", "--allow-other", "--read-write"}
276
277         if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
278                 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
279         }
280
281         collectionPaths := []string{}
282         runner.Binds = nil
283         needCertMount := true
284
285         var binds []string
286         for bind, _ := range runner.Container.Mounts {
287                 binds = append(binds, bind)
288         }
289         sort.Strings(binds)
290
291         for _, bind := range binds {
292                 mnt := runner.Container.Mounts[bind]
293                 if bind == "stdout" {
294                         // Is it a "file" mount kind?
295                         if mnt.Kind != "file" {
296                                 return fmt.Errorf("Unsupported mount kind '%s' for stdout. Only 'file' is supported.", mnt.Kind)
297                         }
298
299                         // Does path start with OutputPath?
300                         prefix := runner.Container.OutputPath
301                         if !strings.HasSuffix(prefix, "/") {
302                                 prefix += "/"
303                         }
304                         if !strings.HasPrefix(mnt.Path, prefix) {
305                                 return fmt.Errorf("Stdout path does not start with OutputPath: %s, %s", mnt.Path, prefix)
306                         }
307                 }
308
309                 if bind == "/etc/arvados/ca-certificates.crt" {
310                         needCertMount = false
311                 }
312
313                 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
314                         if mnt.Kind != "collection" {
315                                 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
316                         }
317                 }
318
319                 switch {
320                 case mnt.Kind == "collection":
321                         var src string
322                         if mnt.UUID != "" && mnt.PortableDataHash != "" {
323                                 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
324                         }
325                         if mnt.UUID != "" {
326                                 if mnt.Writable {
327                                         return fmt.Errorf("Writing to existing collections currently not permitted.")
328                                 }
329                                 pdhOnly = false
330                                 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
331                         } else if mnt.PortableDataHash != "" {
332                                 if mnt.Writable {
333                                         return fmt.Errorf("Can never write to a collection specified by portable data hash")
334                                 }
335                                 idx := strings.Index(mnt.PortableDataHash, "/")
336                                 if idx > 0 {
337                                         mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
338                                         mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
339                                         runner.Container.Mounts[bind] = mnt
340                                 }
341                                 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
342                                 if mnt.Path != "" && mnt.Path != "." {
343                                         if strings.HasPrefix(mnt.Path, "./") {
344                                                 mnt.Path = mnt.Path[2:]
345                                         } else if strings.HasPrefix(mnt.Path, "/") {
346                                                 mnt.Path = mnt.Path[1:]
347                                         }
348                                         src += "/" + mnt.Path
349                                 }
350                         } else {
351                                 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
352                                 arvMountCmd = append(arvMountCmd, "--mount-tmp")
353                                 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
354                                 tmpcount += 1
355                         }
356                         if mnt.Writable {
357                                 if bind == runner.Container.OutputPath {
358                                         runner.HostOutputDir = src
359                                 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
360                                         return fmt.Errorf("Writable mount points are not permitted underneath the output_path: %v", bind)
361                                 }
362                                 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
363                         } else {
364                                 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
365                         }
366                         collectionPaths = append(collectionPaths, src)
367
368                 case mnt.Kind == "tmp" && bind == runner.Container.OutputPath:
369                         runner.HostOutputDir, err = runner.MkTempDir("", "")
370                         if err != nil {
371                                 return fmt.Errorf("While creating mount temp dir: %v", err)
372                         }
373                         st, staterr := os.Stat(runner.HostOutputDir)
374                         if staterr != nil {
375                                 return fmt.Errorf("While Stat on temp dir: %v", staterr)
376                         }
377                         err = os.Chmod(runner.HostOutputDir, st.Mode()|os.ModeSetgid|0777)
378                         if staterr != nil {
379                                 return fmt.Errorf("While Chmod temp dir: %v", err)
380                         }
381                         runner.CleanupTempDir = append(runner.CleanupTempDir, runner.HostOutputDir)
382                         runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", runner.HostOutputDir, bind))
383
384                 case mnt.Kind == "tmp":
385                         runner.Binds = append(runner.Binds, bind)
386
387                 case mnt.Kind == "json":
388                         jsondata, err := json.Marshal(mnt.Content)
389                         if err != nil {
390                                 return fmt.Errorf("encoding json data: %v", err)
391                         }
392                         // Create a tempdir with a single file
393                         // (instead of just a tempfile): this way we
394                         // can ensure the file is world-readable
395                         // inside the container, without having to
396                         // make it world-readable on the docker host.
397                         tmpdir, err := runner.MkTempDir("", "")
398                         if err != nil {
399                                 return fmt.Errorf("creating temp dir: %v", err)
400                         }
401                         runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
402                         tmpfn := filepath.Join(tmpdir, "mountdata.json")
403                         err = ioutil.WriteFile(tmpfn, jsondata, 0644)
404                         if err != nil {
405                                 return fmt.Errorf("writing temp file: %v", err)
406                         }
407                         runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
408                 }
409         }
410
411         if runner.HostOutputDir == "" {
412                 return fmt.Errorf("Output path does not correspond to a writable mount point")
413         }
414
415         if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
416                 for _, certfile := range arvadosclient.CertFiles {
417                         _, err := os.Stat(certfile)
418                         if err == nil {
419                                 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
420                                 break
421                         }
422                 }
423         }
424
425         if pdhOnly {
426                 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
427         } else {
428                 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
429         }
430         arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
431
432         token, err := runner.ContainerToken()
433         if err != nil {
434                 return fmt.Errorf("could not get container token: %s", err)
435         }
436
437         runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
438         if err != nil {
439                 return fmt.Errorf("While trying to start arv-mount: %v", err)
440         }
441
442         for _, p := range collectionPaths {
443                 _, err = os.Stat(p)
444                 if err != nil {
445                         return fmt.Errorf("While checking that input files exist: %v", err)
446                 }
447         }
448
449         return nil
450 }
451
452 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
453         // Handle docker log protocol
454         // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
455
456         header := make([]byte, 8)
457         for {
458                 _, readerr := io.ReadAtLeast(containerReader, header, 8)
459
460                 if readerr == nil {
461                         readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
462                         if header[0] == 1 {
463                                 // stdout
464                                 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
465                         } else {
466                                 // stderr
467                                 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
468                         }
469                 }
470
471                 if readerr != nil {
472                         if readerr != io.EOF {
473                                 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
474                         }
475
476                         closeerr := runner.Stdout.Close()
477                         if closeerr != nil {
478                                 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
479                         }
480
481                         closeerr = runner.Stderr.Close()
482                         if closeerr != nil {
483                                 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
484                         }
485
486                         if runner.statReporter != nil {
487                                 runner.statReporter.Stop()
488                                 closeerr = runner.statLogger.Close()
489                                 if closeerr != nil {
490                                         runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
491                                 }
492                         }
493
494                         runner.loggingDone <- true
495                         close(runner.loggingDone)
496                         return
497                 }
498         }
499 }
500
501 func (runner *ContainerRunner) StartCrunchstat() {
502         runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
503         runner.statReporter = &crunchstat.Reporter{
504                 CID:          runner.ContainerID,
505                 Logger:       log.New(runner.statLogger, "", 0),
506                 CgroupParent: runner.expectCgroupParent,
507                 CgroupRoot:   runner.cgroupRoot,
508                 PollPeriod:   runner.statInterval,
509         }
510         runner.statReporter.Start()
511 }
512
513 type infoCommand struct {
514         label string
515         cmd   []string
516 }
517
518 // Gather node information and store it on the log for debugging
519 // purposes.
520 func (runner *ContainerRunner) LogNodeInfo() (err error) {
521         w := runner.NewLogWriter("node-info")
522         logger := log.New(w, "node-info", 0)
523
524         commands := []infoCommand{
525                 infoCommand{
526                         label: "Host Information",
527                         cmd:   []string{"uname", "-a"},
528                 },
529                 infoCommand{
530                         label: "CPU Information",
531                         cmd:   []string{"cat", "/proc/cpuinfo"},
532                 },
533                 infoCommand{
534                         label: "Memory Information",
535                         cmd:   []string{"cat", "/proc/meminfo"},
536                 },
537                 infoCommand{
538                         label: "Disk Space",
539                         cmd:   []string{"df", "-m", "/", os.TempDir()},
540                 },
541                 infoCommand{
542                         label: "Disk INodes",
543                         cmd:   []string{"df", "-i", "/", os.TempDir()},
544                 },
545         }
546
547         // Run commands with informational output to be logged.
548         var out []byte
549         for _, command := range commands {
550                 out, err = exec.Command(command.cmd[0], command.cmd[1:]...).CombinedOutput()
551                 if err != nil {
552                         return fmt.Errorf("While running command %q: %v",
553                                 command.cmd, err)
554                 }
555                 logger.Println(command.label)
556                 for _, line := range strings.Split(string(out), "\n") {
557                         logger.Println(" ", line)
558                 }
559         }
560
561         err = w.Close()
562         if err != nil {
563                 return fmt.Errorf("While closing node-info logs: %v", err)
564         }
565         return nil
566 }
567
568 // Get and save the raw JSON container record from the API server
569 func (runner *ContainerRunner) LogContainerRecord() (err error) {
570         w := &ArvLogWriter{
571                 runner.ArvClient,
572                 runner.Container.UUID,
573                 "container",
574                 runner.LogCollection.Open("container.json"),
575         }
576         // Get Container record JSON from the API Server
577         reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
578         if err != nil {
579                 return fmt.Errorf("While retrieving container record from the API server: %v", err)
580         }
581         defer reader.Close()
582         // Read the API server response as []byte
583         json_bytes, err := ioutil.ReadAll(reader)
584         if err != nil {
585                 return fmt.Errorf("While reading container record API server response: %v", err)
586         }
587         // Decode the JSON []byte
588         var cr map[string]interface{}
589         if err = json.Unmarshal(json_bytes, &cr); err != nil {
590                 return fmt.Errorf("While decoding the container record JSON response: %v", err)
591         }
592         // Re-encode it using indentation to improve readability
593         enc := json.NewEncoder(w)
594         enc.SetIndent("", "    ")
595         if err = enc.Encode(cr); err != nil {
596                 return fmt.Errorf("While logging the JSON container record: %v", err)
597         }
598         err = w.Close()
599         if err != nil {
600                 return fmt.Errorf("While closing container.json log: %v", err)
601         }
602         return nil
603 }
604
605 // AttachLogs connects the docker container stdout and stderr logs to the
606 // Arvados logger which logs to Keep and the API server logs table.
607 func (runner *ContainerRunner) AttachStreams() (err error) {
608
609         runner.CrunchLog.Print("Attaching container streams")
610
611         var containerReader io.Reader
612         containerReader, err = runner.Docker.AttachContainer(runner.ContainerID,
613                 &dockerclient.AttachOptions{Stream: true, Stdout: true, Stderr: true})
614         if err != nil {
615                 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
616         }
617
618         runner.loggingDone = make(chan bool)
619
620         if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
621                 stdoutPath := stdoutMnt.Path[len(runner.Container.OutputPath):]
622                 index := strings.LastIndex(stdoutPath, "/")
623                 if index > 0 {
624                         subdirs := stdoutPath[:index]
625                         if subdirs != "" {
626                                 st, err := os.Stat(runner.HostOutputDir)
627                                 if err != nil {
628                                         return fmt.Errorf("While Stat on temp dir: %v", err)
629                                 }
630                                 stdoutPath := path.Join(runner.HostOutputDir, subdirs)
631                                 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
632                                 if err != nil {
633                                         return fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
634                                 }
635                         }
636                 }
637                 stdoutFile, err := os.Create(path.Join(runner.HostOutputDir, stdoutPath))
638                 if err != nil {
639                         return fmt.Errorf("While creating stdout file: %v", err)
640                 }
641                 runner.Stdout = stdoutFile
642         } else {
643                 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
644         }
645         runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
646
647         go runner.ProcessDockerAttach(containerReader)
648
649         return nil
650 }
651
652 // CreateContainer creates the docker container.
653 func (runner *ContainerRunner) CreateContainer() error {
654         runner.CrunchLog.Print("Creating Docker container")
655
656         runner.ContainerConfig.Cmd = runner.Container.Command
657         if runner.Container.Cwd != "." {
658                 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
659         }
660
661         for k, v := range runner.Container.Environment {
662                 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
663         }
664
665         runner.HostConfig = dockerclient.HostConfig{
666                 Binds:        runner.Binds,
667                 CgroupParent: runner.setCgroupParent,
668                 LogConfig: dockerclient.LogConfig{
669                         Type: "none",
670                 },
671         }
672
673         if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
674                 tok, err := runner.ContainerToken()
675                 if err != nil {
676                         return err
677                 }
678                 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
679                         "ARVADOS_API_TOKEN="+tok,
680                         "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
681                         "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
682                 )
683                 runner.HostConfig.NetworkMode = runner.networkMode
684         } else {
685                 if runner.enableNetwork == "always" {
686                         runner.HostConfig.NetworkMode = runner.networkMode
687                 } else {
688                         runner.HostConfig.NetworkMode = "none"
689                 }
690         }
691
692         var err error
693         runner.ContainerID, err = runner.Docker.CreateContainer(&runner.ContainerConfig, "", nil)
694         if err != nil {
695                 return fmt.Errorf("While creating container: %v", err)
696         }
697
698         return runner.AttachStreams()
699 }
700
701 // StartContainer starts the docker container created by CreateContainer.
702 func (runner *ContainerRunner) StartContainer() error {
703         runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
704         runner.cStateLock.Lock()
705         defer runner.cStateLock.Unlock()
706         if runner.cCancelled {
707                 return ErrCancelled
708         }
709         err := runner.Docker.StartContainer(runner.ContainerID, &runner.HostConfig)
710         if err != nil {
711                 return fmt.Errorf("could not start container: %v", err)
712         }
713         runner.cStarted = true
714         return nil
715 }
716
717 // WaitFinish waits for the container to terminate, capture the exit code, and
718 // close the stdout/stderr logging.
719 func (runner *ContainerRunner) WaitFinish() error {
720         runner.CrunchLog.Print("Waiting for container to finish")
721
722         waitDocker := runner.Docker.Wait(runner.ContainerID)
723         waitMount := runner.ArvMountExit
724         for waitDocker != nil {
725                 select {
726                 case err := <-waitMount:
727                         runner.CrunchLog.Printf("arv-mount exited before container finished: %v", err)
728                         waitMount = nil
729                         runner.stop()
730                 case wr := <-waitDocker:
731                         if wr.Error != nil {
732                                 return fmt.Errorf("While waiting for container to finish: %v", wr.Error)
733                         }
734                         runner.ExitCode = &wr.ExitCode
735                         waitDocker = nil
736                 }
737         }
738
739         // wait for stdout/stderr to complete
740         <-runner.loggingDone
741
742         return nil
743 }
744
745 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
746 func (runner *ContainerRunner) CaptureOutput() error {
747         if runner.finalState != "Complete" {
748                 return nil
749         }
750
751         if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
752                 // Output may have been set directly by the container, so
753                 // refresh the container record to check.
754                 err := runner.ArvClient.Get("containers", runner.Container.UUID,
755                         nil, &runner.Container)
756                 if err != nil {
757                         return err
758                 }
759                 if runner.Container.Output != "" {
760                         // Container output is already set.
761                         runner.OutputPDH = &runner.Container.Output
762                         return nil
763                 }
764         }
765
766         if runner.HostOutputDir == "" {
767                 return nil
768         }
769
770         _, err := os.Stat(runner.HostOutputDir)
771         if err != nil {
772                 return fmt.Errorf("While checking host output path: %v", err)
773         }
774
775         var manifestText string
776
777         collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
778         _, err = os.Stat(collectionMetafile)
779         if err != nil {
780                 // Regular directory
781                 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
782                 manifestText, err = cw.WriteTree(runner.HostOutputDir, runner.CrunchLog.Logger)
783                 if err != nil {
784                         return fmt.Errorf("While uploading output files: %v", err)
785                 }
786         } else {
787                 // FUSE mount directory
788                 file, openerr := os.Open(collectionMetafile)
789                 if openerr != nil {
790                         return fmt.Errorf("While opening FUSE metafile: %v", err)
791                 }
792                 defer file.Close()
793
794                 var rec arvados.Collection
795                 err = json.NewDecoder(file).Decode(&rec)
796                 if err != nil {
797                         return fmt.Errorf("While reading FUSE metafile: %v", err)
798                 }
799                 manifestText = rec.ManifestText
800         }
801
802         // Pre-populate output from the configured mount points
803         var binds []string
804         for bind, _ := range runner.Container.Mounts {
805                 binds = append(binds, bind)
806         }
807         sort.Strings(binds)
808
809         for _, bind := range binds {
810                 mnt := runner.Container.Mounts[bind]
811
812                 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
813
814                 if bindSuffix == bind || len(bindSuffix) <= 0 {
815                         // either does not start with OutputPath or is OutputPath itself
816                         continue
817                 }
818
819                 if mnt.ExcludeFromOutput == true {
820                         continue
821                 }
822
823                 // append to manifest_text
824                 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
825                 if err != nil {
826                         return err
827                 }
828
829                 manifestText = manifestText + m
830         }
831
832         // Save output
833         var response arvados.Collection
834         manifest := manifest.Manifest{Text: manifestText}
835         manifestText = manifest.Extract(".", ".").Text
836         err = runner.ArvClient.Create("collections",
837                 arvadosclient.Dict{
838                         "ensure_unique_name": true,
839                         "collection": arvadosclient.Dict{
840                                 "is_trashed":    true,
841                                 "name":          "output for " + runner.Container.UUID,
842                                 "manifest_text": manifestText}},
843                 &response)
844         if err != nil {
845                 return fmt.Errorf("While creating output collection: %v", err)
846         }
847         runner.OutputPDH = &response.PortableDataHash
848         return nil
849 }
850
851 var outputCollections = make(map[string]arvados.Collection)
852
853 // Fetch the collection for the mnt.PortableDataHash
854 // Return the manifest_text fragment corresponding to the specified mnt.Path
855 //  after making any required updates.
856 //  Ex:
857 //    If mnt.Path is not specified,
858 //      return the entire manifest_text after replacing any "." with bindSuffix
859 //    If mnt.Path corresponds to one stream,
860 //      return the manifest_text for that stream after replacing that stream name with bindSuffix
861 //    Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
862 //      for that stream after replacing stream name with bindSuffix minus the last word
863 //      and the file name with last word of the bindSuffix
864 //  Allowed path examples:
865 //    "path":"/"
866 //    "path":"/subdir1"
867 //    "path":"/subdir1/subdir2"
868 //    "path":"/subdir/filename" etc
869 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
870         collection := outputCollections[mnt.PortableDataHash]
871         if collection.PortableDataHash == "" {
872                 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
873                 if err != nil {
874                         return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
875                 }
876                 outputCollections[mnt.PortableDataHash] = collection
877         }
878
879         if collection.ManifestText == "" {
880                 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
881                 return "", nil
882         }
883
884         mft := manifest.Manifest{Text: collection.ManifestText}
885         extracted := mft.Extract(mnt.Path, bindSuffix)
886         if extracted.Err != nil {
887                 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
888         }
889         return extracted.Text, nil
890 }
891
892 func (runner *ContainerRunner) CleanupDirs() {
893         if runner.ArvMount != nil {
894                 umount := exec.Command("fusermount", "-z", "-u", runner.ArvMountPoint)
895                 umnterr := umount.Run()
896                 if umnterr != nil {
897                         runner.CrunchLog.Printf("While running fusermount: %v", umnterr)
898                 }
899
900                 mnterr := <-runner.ArvMountExit
901                 if mnterr != nil {
902                         runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
903                 }
904         }
905
906         for _, tmpdir := range runner.CleanupTempDir {
907                 rmerr := os.RemoveAll(tmpdir)
908                 if rmerr != nil {
909                         runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
910                 }
911         }
912 }
913
914 // CommitLogs posts the collection containing the final container logs.
915 func (runner *ContainerRunner) CommitLogs() error {
916         runner.CrunchLog.Print(runner.finalState)
917         runner.CrunchLog.Close()
918
919         // Closing CrunchLog above allows it to be committed to Keep at this
920         // point, but re-open crunch log with ArvClient in case there are any
921         // other further (such as failing to write the log to Keep!) while
922         // shutting down
923         runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{runner.ArvClient, runner.Container.UUID,
924                 "crunch-run", nil})
925
926         if runner.LogsPDH != nil {
927                 // If we have already assigned something to LogsPDH,
928                 // we must be closing the re-opened log, which won't
929                 // end up getting attached to the container record and
930                 // therefore doesn't need to be saved as a collection
931                 // -- it exists only to send logs to other channels.
932                 return nil
933         }
934
935         mt, err := runner.LogCollection.ManifestText()
936         if err != nil {
937                 return fmt.Errorf("While creating log manifest: %v", err)
938         }
939
940         var response arvados.Collection
941         err = runner.ArvClient.Create("collections",
942                 arvadosclient.Dict{
943                         "ensure_unique_name": true,
944                         "collection": arvadosclient.Dict{
945                                 "is_trashed":    true,
946                                 "name":          "logs for " + runner.Container.UUID,
947                                 "manifest_text": mt}},
948                 &response)
949         if err != nil {
950                 return fmt.Errorf("While creating log collection: %v", err)
951         }
952         runner.LogsPDH = &response.PortableDataHash
953         return nil
954 }
955
956 // UpdateContainerRunning updates the container state to "Running"
957 func (runner *ContainerRunner) UpdateContainerRunning() error {
958         runner.cStateLock.Lock()
959         defer runner.cStateLock.Unlock()
960         if runner.cCancelled {
961                 return ErrCancelled
962         }
963         return runner.ArvClient.Update("containers", runner.Container.UUID,
964                 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
965 }
966
967 // ContainerToken returns the api_token the container (and any
968 // arv-mount processes) are allowed to use.
969 func (runner *ContainerRunner) ContainerToken() (string, error) {
970         if runner.token != "" {
971                 return runner.token, nil
972         }
973
974         var auth arvados.APIClientAuthorization
975         err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
976         if err != nil {
977                 return "", err
978         }
979         runner.token = auth.APIToken
980         return runner.token, nil
981 }
982
983 // UpdateContainerComplete updates the container record state on API
984 // server to "Complete" or "Cancelled"
985 func (runner *ContainerRunner) UpdateContainerFinal() error {
986         update := arvadosclient.Dict{}
987         update["state"] = runner.finalState
988         if runner.LogsPDH != nil {
989                 update["log"] = *runner.LogsPDH
990         }
991         if runner.finalState == "Complete" {
992                 if runner.ExitCode != nil {
993                         update["exit_code"] = *runner.ExitCode
994                 }
995                 if runner.OutputPDH != nil {
996                         update["output"] = *runner.OutputPDH
997                 }
998         }
999         return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1000 }
1001
1002 // IsCancelled returns the value of Cancelled, with goroutine safety.
1003 func (runner *ContainerRunner) IsCancelled() bool {
1004         runner.cStateLock.Lock()
1005         defer runner.cStateLock.Unlock()
1006         return runner.cCancelled
1007 }
1008
1009 // NewArvLogWriter creates an ArvLogWriter
1010 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1011         return &ArvLogWriter{runner.ArvClient, runner.Container.UUID, name, runner.LogCollection.Open(name + ".txt")}
1012 }
1013
1014 // Run the full container lifecycle.
1015 func (runner *ContainerRunner) Run() (err error) {
1016         runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1017
1018         hostname, hosterr := os.Hostname()
1019         if hosterr != nil {
1020                 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1021         } else {
1022                 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1023         }
1024
1025         // Clean up temporary directories _after_ finalizing
1026         // everything (if we've made any by then)
1027         defer runner.CleanupDirs()
1028
1029         runner.finalState = "Queued"
1030
1031         defer func() {
1032                 // checkErr prints e (unless it's nil) and sets err to
1033                 // e (unless err is already non-nil). Thus, if err
1034                 // hasn't already been assigned when Run() returns,
1035                 // this cleanup func will cause Run() to return the
1036                 // first non-nil error that is passed to checkErr().
1037                 checkErr := func(e error) {
1038                         if e == nil {
1039                                 return
1040                         }
1041                         runner.CrunchLog.Print(e)
1042                         if err == nil {
1043                                 err = e
1044                         }
1045                 }
1046
1047                 // Log the error encountered in Run(), if any
1048                 checkErr(err)
1049
1050                 if runner.finalState == "Queued" {
1051                         runner.CrunchLog.Close()
1052                         runner.UpdateContainerFinal()
1053                         return
1054                 }
1055
1056                 if runner.IsCancelled() {
1057                         runner.finalState = "Cancelled"
1058                         // but don't return yet -- we still want to
1059                         // capture partial output and write logs
1060                 }
1061
1062                 checkErr(runner.CaptureOutput())
1063                 checkErr(runner.CommitLogs())
1064                 checkErr(runner.UpdateContainerFinal())
1065
1066                 // The real log is already closed, but then we opened
1067                 // a new one in case we needed to log anything while
1068                 // finalizing.
1069                 runner.CrunchLog.Close()
1070         }()
1071
1072         err = runner.ArvClient.Get("containers", runner.Container.UUID, nil, &runner.Container)
1073         if err != nil {
1074                 err = fmt.Errorf("While getting container record: %v", err)
1075                 return
1076         }
1077
1078         // setup signal handling
1079         runner.SetupSignals()
1080
1081         // check for and/or load image
1082         err = runner.LoadImage()
1083         if err != nil {
1084                 runner.finalState = "Cancelled"
1085                 err = fmt.Errorf("While loading container image: %v", err)
1086                 return
1087         }
1088
1089         // set up FUSE mount and binds
1090         err = runner.SetupMounts()
1091         if err != nil {
1092                 runner.finalState = "Cancelled"
1093                 err = fmt.Errorf("While setting up mounts: %v", err)
1094                 return
1095         }
1096
1097         err = runner.CreateContainer()
1098         if err != nil {
1099                 return
1100         }
1101
1102         // Gather and record node information
1103         err = runner.LogNodeInfo()
1104         if err != nil {
1105                 return
1106         }
1107         // Save container.json record on log collection
1108         err = runner.LogContainerRecord()
1109         if err != nil {
1110                 return
1111         }
1112
1113         runner.StartCrunchstat()
1114
1115         if runner.IsCancelled() {
1116                 return
1117         }
1118
1119         err = runner.UpdateContainerRunning()
1120         if err != nil {
1121                 return
1122         }
1123         runner.finalState = "Cancelled"
1124
1125         err = runner.StartContainer()
1126         if err != nil {
1127                 return
1128         }
1129
1130         err = runner.WaitFinish()
1131         if err == nil {
1132                 runner.finalState = "Complete"
1133         }
1134         return
1135 }
1136
1137 // NewContainerRunner creates a new container runner.
1138 func NewContainerRunner(api IArvadosClient,
1139         kc IKeepClient,
1140         docker ThinDockerClient,
1141         containerUUID string) *ContainerRunner {
1142
1143         cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1144         cr.NewLogWriter = cr.NewArvLogWriter
1145         cr.RunArvMount = cr.ArvMountCmd
1146         cr.MkTempDir = ioutil.TempDir
1147         cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1148         cr.Container.UUID = containerUUID
1149         cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1150         cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1151         return cr
1152 }
1153
1154 func main() {
1155         statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1156         cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1157         cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1158         cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1159         caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1160         enableNetwork := flag.String("container-enable-networking", "default",
1161                 `Specify if networking should be enabled for container.  One of 'default', 'always':
1162         default: only enable networking if container requests it.
1163         always:  containers always have networking enabled
1164         `)
1165         networkMode := flag.String("container-network-mode", "default",
1166                 `Set networking mode for container.  Corresponds to Docker network mode (--net).
1167         `)
1168         flag.Parse()
1169
1170         containerId := flag.Arg(0)
1171
1172         if *caCertsPath != "" {
1173                 arvadosclient.CertFiles = []string{*caCertsPath}
1174         }
1175
1176         api, err := arvadosclient.MakeArvadosClient()
1177         if err != nil {
1178                 log.Fatalf("%s: %v", containerId, err)
1179         }
1180         api.Retries = 8
1181
1182         var kc *keepclient.KeepClient
1183         kc, err = keepclient.MakeKeepClient(api)
1184         if err != nil {
1185                 log.Fatalf("%s: %v", containerId, err)
1186         }
1187         kc.Retries = 4
1188
1189         var docker *dockerclient.DockerClient
1190         docker, err = dockerclient.NewDockerClient("unix:///var/run/docker.sock", nil)
1191         if err != nil {
1192                 log.Fatalf("%s: %v", containerId, err)
1193         }
1194
1195         cr := NewContainerRunner(api, kc, docker, containerId)
1196         cr.statInterval = *statInterval
1197         cr.cgroupRoot = *cgroupRoot
1198         cr.expectCgroupParent = *cgroupParent
1199         cr.enableNetwork = *enableNetwork
1200         cr.networkMode = *networkMode
1201         if *cgroupParentSubsystem != "" {
1202                 p := findCgroup(*cgroupParentSubsystem)
1203                 cr.setCgroupParent = p
1204                 cr.expectCgroupParent = p
1205         }
1206
1207         err = cr.Run()
1208         if err != nil {
1209                 log.Fatalf("%s: %v", containerId, err)
1210         }
1211
1212 }