11121: Merge branch 'master' into 11121-crunch-output-collection-owner
[arvados.git] / services / crunch-run / crunchrun_test.go
1 package main
2
3 import (
4         "bytes"
5         "crypto/md5"
6         "encoding/json"
7         "errors"
8         "fmt"
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         . "gopkg.in/check.v1"
15         "io"
16         "io/ioutil"
17         "os"
18         "os/exec"
19         "path/filepath"
20         "sort"
21         "strings"
22         "sync"
23         "syscall"
24         "testing"
25         "time"
26 )
27
28 // Gocheck boilerplate
29 func TestCrunchExec(t *testing.T) {
30         TestingT(t)
31 }
32
33 type TestSuite struct{}
34
35 // Gocheck boilerplate
36 var _ = Suite(&TestSuite{})
37
38 type ArvTestClient struct {
39         Total   int64
40         Calls   int
41         Content []arvadosclient.Dict
42         arvados.Container
43         Logs map[string]*bytes.Buffer
44         sync.Mutex
45         WasSetRunning bool
46 }
47
48 type KeepTestClient struct {
49         Called  bool
50         Content []byte
51 }
52
53 var hwManifest = ". 82ab40c24fc8df01798e57ba66795bb1+841216+Aa124ac75e5168396c73c0a18eda641a4f41791c0@569fa8c3 0:841216:9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7.tar\n"
54 var hwPDH = "a45557269dcb65a6b78f9ac061c0850b+120"
55 var hwImageId = "9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7"
56
57 var otherManifest = ". 68a84f561b1d1708c6baff5e019a9ab3+46+Ae5d0af96944a3690becb1decdf60cc1c937f556d@5693216f 0:46:md5sum.txt\n"
58 var otherPDH = "a3e8f74c6f101eae01fa08bfb4e49b3a+54"
59
60 var normalizedManifestWithSubdirs = ". 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 0:9:file1_in_main.txt 9:18:file2_in_main.txt 0:27:zzzzz-8i9sb-bcdefghijkdhvnk.log.txt\n./subdir1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt\n./subdir1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt\n"
61 var normalizedWithSubdirsPDH = "a0def87f80dd594d4675809e83bd4f15+367"
62
63 var denormalizedManifestWithSubdirs = ". 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 0:9:file1_in_main.txt 9:18:file2_in_main.txt 0:27:zzzzz-8i9sb-bcdefghijkdhvnk.log.txt 0:10:subdir1/file1_in_subdir1.txt 10:17:subdir1/file2_in_subdir1.txt\n"
64 var denormalizedWithSubdirsPDH = "b0def87f80dd594d4675809e83bd4f15+367"
65
66 var fakeAuthUUID = "zzzzz-gj3su-55pqoyepgi2glem"
67 var fakeAuthToken = "a3ltuwzqcu2u4sc0q7yhpc2w7s00fdcqecg5d6e0u3pfohmbjt"
68
69 type TestDockerClient struct {
70         imageLoaded string
71         logReader   io.ReadCloser
72         logWriter   io.WriteCloser
73         fn          func(t *TestDockerClient)
74         finish      chan dockerclient.WaitResult
75         stop        chan bool
76         cwd         string
77         env         []string
78         api         *ArvTestClient
79 }
80
81 func NewTestDockerClient() *TestDockerClient {
82         t := &TestDockerClient{}
83         t.logReader, t.logWriter = io.Pipe()
84         t.finish = make(chan dockerclient.WaitResult)
85         t.stop = make(chan bool)
86         t.cwd = "/"
87         return t
88 }
89
90 func (t *TestDockerClient) StopContainer(id string, timeout int) error {
91         t.stop <- true
92         return nil
93 }
94
95 func (t *TestDockerClient) InspectImage(id string) (*dockerclient.ImageInfo, error) {
96         if t.imageLoaded == id {
97                 return &dockerclient.ImageInfo{}, nil
98         } else {
99                 return nil, errors.New("")
100         }
101 }
102
103 func (t *TestDockerClient) LoadImage(reader io.Reader) error {
104         _, err := io.Copy(ioutil.Discard, reader)
105         if err != nil {
106                 return err
107         } else {
108                 t.imageLoaded = hwImageId
109                 return nil
110         }
111 }
112
113 func (t *TestDockerClient) CreateContainer(config *dockerclient.ContainerConfig, name string, authConfig *dockerclient.AuthConfig) (string, error) {
114         if config.WorkingDir != "" {
115                 t.cwd = config.WorkingDir
116         }
117         t.env = config.Env
118         return "abcde", nil
119 }
120
121 func (t *TestDockerClient) StartContainer(id string, config *dockerclient.HostConfig) error {
122         if id == "abcde" {
123                 go t.fn(t)
124                 return nil
125         } else {
126                 return errors.New("Invalid container id")
127         }
128 }
129
130 func (t *TestDockerClient) AttachContainer(id string, options *dockerclient.AttachOptions) (io.ReadCloser, error) {
131         return t.logReader, nil
132 }
133
134 func (t *TestDockerClient) Wait(id string) <-chan dockerclient.WaitResult {
135         return t.finish
136 }
137
138 func (*TestDockerClient) RemoveImage(name string, force bool) ([]*dockerclient.ImageDelete, error) {
139         return nil, nil
140 }
141
142 func (client *ArvTestClient) Create(resourceType string,
143         parameters arvadosclient.Dict,
144         output interface{}) error {
145
146         client.Mutex.Lock()
147         defer client.Mutex.Unlock()
148
149         client.Calls++
150         client.Content = append(client.Content, parameters)
151
152         if resourceType == "logs" {
153                 et := parameters["log"].(arvadosclient.Dict)["event_type"].(string)
154                 if client.Logs == nil {
155                         client.Logs = make(map[string]*bytes.Buffer)
156                 }
157                 if client.Logs[et] == nil {
158                         client.Logs[et] = &bytes.Buffer{}
159                 }
160                 client.Logs[et].Write([]byte(parameters["log"].(arvadosclient.Dict)["properties"].(map[string]string)["text"]))
161         }
162
163         if resourceType == "collections" && output != nil {
164                 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
165                 outmap := output.(*arvados.Collection)
166                 outmap.PortableDataHash = fmt.Sprintf("%x+%d", md5.Sum([]byte(mt)), len(mt))
167         }
168
169         return nil
170 }
171
172 func (client *ArvTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
173         switch {
174         case method == "GET" && resourceType == "containers" && action == "auth":
175                 return json.Unmarshal([]byte(`{
176                         "kind": "arvados#api_client_authorization",
177                         "uuid": "`+fakeAuthUUID+`",
178                         "api_token": "`+fakeAuthToken+`"
179                         }`), output)
180         default:
181                 return fmt.Errorf("Not found")
182         }
183 }
184
185 func (client *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
186         if resourceType == "collections" {
187                 if uuid == hwPDH {
188                         output.(*arvados.Collection).ManifestText = hwManifest
189                 } else if uuid == otherPDH {
190                         output.(*arvados.Collection).ManifestText = otherManifest
191                 } else if uuid == normalizedWithSubdirsPDH {
192                         output.(*arvados.Collection).ManifestText = normalizedManifestWithSubdirs
193                 } else if uuid == denormalizedWithSubdirsPDH {
194                         output.(*arvados.Collection).ManifestText = denormalizedManifestWithSubdirs
195                 }
196         }
197         if resourceType == "containers" {
198                 (*output.(*arvados.Container)) = client.Container
199         }
200         return nil
201 }
202
203 func (client *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
204         client.Mutex.Lock()
205         defer client.Mutex.Unlock()
206         client.Calls++
207         client.Content = append(client.Content, parameters)
208         if resourceType == "containers" {
209                 if parameters["container"].(arvadosclient.Dict)["state"] == "Running" {
210                         client.WasSetRunning = true
211                 }
212         }
213         return nil
214 }
215
216 var discoveryMap = map[string]interface{}{"defaultTrashLifetime": float64(1209600)}
217
218 func (client *ArvTestClient) Discovery(key string) (interface{}, error) {
219         return discoveryMap[key], nil
220 }
221
222 // CalledWith returns the parameters from the first API call whose
223 // parameters match jpath/string. E.g., CalledWith(c, "foo.bar",
224 // "baz") returns parameters with parameters["foo"]["bar"]=="baz". If
225 // no call matches, it returns nil.
226 func (client *ArvTestClient) CalledWith(jpath string, expect interface{}) arvadosclient.Dict {
227 call:
228         for _, content := range client.Content {
229                 var v interface{} = content
230                 for _, k := range strings.Split(jpath, ".") {
231                         if dict, ok := v.(arvadosclient.Dict); !ok {
232                                 continue call
233                         } else {
234                                 v = dict[k]
235                         }
236                 }
237                 if v == expect {
238                         return content
239                 }
240         }
241         return nil
242 }
243
244 func (client *KeepTestClient) PutHB(hash string, buf []byte) (string, int, error) {
245         client.Content = buf
246         return fmt.Sprintf("%s+%d", hash, len(buf)), len(buf), nil
247 }
248
249 type FileWrapper struct {
250         io.ReadCloser
251         len uint64
252 }
253
254 func (fw FileWrapper) Len() uint64 {
255         return fw.len
256 }
257
258 func (fw FileWrapper) Seek(int64, int) (int64, error) {
259         return 0, errors.New("not implemented")
260 }
261
262 func (client *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.Reader, error) {
263         if filename == hwImageId+".tar" {
264                 rdr := ioutil.NopCloser(&bytes.Buffer{})
265                 client.Called = true
266                 return FileWrapper{rdr, 1321984}, nil
267         }
268         return nil, nil
269 }
270
271 func (s *TestSuite) TestLoadImage(c *C) {
272         kc := &KeepTestClient{}
273         docker := NewTestDockerClient()
274         cr := NewContainerRunner(&ArvTestClient{}, kc, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
275
276         _, err := cr.Docker.RemoveImage(hwImageId, true)
277
278         _, err = cr.Docker.InspectImage(hwImageId)
279         c.Check(err, NotNil)
280
281         cr.Container.ContainerImage = hwPDH
282
283         // (1) Test loading image from keep
284         c.Check(kc.Called, Equals, false)
285         c.Check(cr.ContainerConfig.Image, Equals, "")
286
287         err = cr.LoadImage()
288
289         c.Check(err, IsNil)
290         defer func() {
291                 cr.Docker.RemoveImage(hwImageId, true)
292         }()
293
294         c.Check(kc.Called, Equals, true)
295         c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
296
297         _, err = cr.Docker.InspectImage(hwImageId)
298         c.Check(err, IsNil)
299
300         // (2) Test using image that's already loaded
301         kc.Called = false
302         cr.ContainerConfig.Image = ""
303
304         err = cr.LoadImage()
305         c.Check(err, IsNil)
306         c.Check(kc.Called, Equals, false)
307         c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
308
309 }
310
311 type ArvErrorTestClient struct{}
312
313 func (ArvErrorTestClient) Create(resourceType string,
314         parameters arvadosclient.Dict,
315         output interface{}) error {
316         return nil
317 }
318
319 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
320         return errors.New("ArvError")
321 }
322
323 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
324         return errors.New("ArvError")
325 }
326
327 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
328         return nil
329 }
330
331 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
332         return discoveryMap[key], nil
333 }
334
335 type KeepErrorTestClient struct{}
336
337 func (KeepErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
338         return "", 0, errors.New("KeepError")
339 }
340
341 func (KeepErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.Reader, error) {
342         return nil, errors.New("KeepError")
343 }
344
345 type KeepReadErrorTestClient struct{}
346
347 func (KeepReadErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
348         return "", 0, nil
349 }
350
351 type ErrorReader struct{}
352
353 func (ErrorReader) Read(p []byte) (n int, err error) {
354         return 0, errors.New("ErrorReader")
355 }
356
357 func (ErrorReader) Close() error {
358         return nil
359 }
360
361 func (ErrorReader) Len() uint64 {
362         return 0
363 }
364
365 func (ErrorReader) Seek(int64, int) (int64, error) {
366         return 0, errors.New("ErrorReader")
367 }
368
369 func (KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.Reader, error) {
370         return ErrorReader{}, nil
371 }
372
373 func (s *TestSuite) TestLoadImageArvError(c *C) {
374         // (1) Arvados error
375         cr := NewContainerRunner(ArvErrorTestClient{}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
376         cr.Container.ContainerImage = hwPDH
377
378         err := cr.LoadImage()
379         c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
380 }
381
382 func (s *TestSuite) TestLoadImageKeepError(c *C) {
383         // (2) Keep error
384         docker := NewTestDockerClient()
385         cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
386         cr.Container.ContainerImage = hwPDH
387
388         err := cr.LoadImage()
389         c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
390 }
391
392 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
393         // (3) Collection doesn't contain image
394         cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
395         cr.Container.ContainerImage = otherPDH
396
397         err := cr.LoadImage()
398         c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
399 }
400
401 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
402         // (4) Collection doesn't contain image
403         docker := NewTestDockerClient()
404         cr := NewContainerRunner(&ArvTestClient{}, KeepReadErrorTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
405         cr.Container.ContainerImage = hwPDH
406
407         err := cr.LoadImage()
408         c.Check(err, NotNil)
409 }
410
411 type ClosableBuffer struct {
412         bytes.Buffer
413 }
414
415 func (*ClosableBuffer) Close() error {
416         return nil
417 }
418
419 type TestLogs struct {
420         Stdout ClosableBuffer
421         Stderr ClosableBuffer
422 }
423
424 func (tl *TestLogs) NewTestLoggingWriter(logstr string) io.WriteCloser {
425         if logstr == "stdout" {
426                 return &tl.Stdout
427         }
428         if logstr == "stderr" {
429                 return &tl.Stderr
430         }
431         return nil
432 }
433
434 func dockerLog(fd byte, msg string) []byte {
435         by := []byte(msg)
436         header := make([]byte, 8+len(by))
437         header[0] = fd
438         header[7] = byte(len(by))
439         copy(header[8:], by)
440         return header
441 }
442
443 func (s *TestSuite) TestRunContainer(c *C) {
444         docker := NewTestDockerClient()
445         docker.fn = func(t *TestDockerClient) {
446                 t.logWriter.Write(dockerLog(1, "Hello world\n"))
447                 t.logWriter.Close()
448                 t.finish <- dockerclient.WaitResult{}
449         }
450         cr := NewContainerRunner(&ArvTestClient{}, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
451
452         var logs TestLogs
453         cr.NewLogWriter = logs.NewTestLoggingWriter
454         cr.Container.ContainerImage = hwPDH
455         cr.Container.Command = []string{"./hw"}
456         err := cr.LoadImage()
457         c.Check(err, IsNil)
458
459         err = cr.CreateContainer()
460         c.Check(err, IsNil)
461
462         err = cr.StartContainer()
463         c.Check(err, IsNil)
464
465         err = cr.WaitFinish()
466         c.Check(err, IsNil)
467
468         c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
469         c.Check(logs.Stderr.String(), Equals, "")
470 }
471
472 func (s *TestSuite) TestCommitLogs(c *C) {
473         api := &ArvTestClient{}
474         kc := &KeepTestClient{}
475         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
476         cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
477
478         cr.CrunchLog.Print("Hello world!")
479         cr.CrunchLog.Print("Goodbye")
480         cr.finalState = "Complete"
481
482         err := cr.CommitLogs()
483         c.Check(err, IsNil)
484
485         c.Check(api.Calls, Equals, 2)
486         c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
487         c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
488         c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
489 }
490
491 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
492         api := &ArvTestClient{}
493         kc := &KeepTestClient{}
494         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
495
496         err := cr.UpdateContainerRunning()
497         c.Check(err, IsNil)
498
499         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
500 }
501
502 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
503         api := &ArvTestClient{}
504         kc := &KeepTestClient{}
505         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
506
507         cr.LogsPDH = new(string)
508         *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
509
510         cr.ExitCode = new(int)
511         *cr.ExitCode = 42
512         cr.finalState = "Complete"
513
514         err := cr.UpdateContainerFinal()
515         c.Check(err, IsNil)
516
517         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
518         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
519         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
520 }
521
522 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
523         api := &ArvTestClient{}
524         kc := &KeepTestClient{}
525         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
526         cr.Cancelled = true
527         cr.finalState = "Cancelled"
528
529         err := cr.UpdateContainerFinal()
530         c.Check(err, IsNil)
531
532         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
533         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
534         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
535 }
536
537 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
538 // dress rehearsal of the Run() function, starting from a JSON container record.
539 func FullRunHelper(c *C, record string, extraMounts []string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, realTemp string) {
540         rec := arvados.Container{}
541         err := json.Unmarshal([]byte(record), &rec)
542         c.Check(err, IsNil)
543
544         docker := NewTestDockerClient()
545         docker.fn = fn
546         docker.RemoveImage(hwImageId, true)
547
548         api = &ArvTestClient{Container: rec}
549         docker.api = api
550         cr = NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
551         cr.statInterval = 100 * time.Millisecond
552         am := &ArvMountCmdLine{}
553         cr.RunArvMount = am.ArvMountTest
554
555         realTemp, err = ioutil.TempDir("", "crunchrun_test1-")
556         c.Assert(err, IsNil)
557         defer os.RemoveAll(realTemp)
558
559         tempcount := 0
560         cr.MkTempDir = func(_ string, prefix string) (string, error) {
561                 tempcount++
562                 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, tempcount)
563                 err := os.Mkdir(d, os.ModePerm)
564                 if err != nil && strings.Contains(err.Error(), ": file exists") {
565                         // Test case must have pre-populated the tempdir
566                         err = nil
567                 }
568                 return d, err
569         }
570
571         if extraMounts != nil && len(extraMounts) > 0 {
572                 err := cr.SetupArvMountPoint("keep")
573                 c.Check(err, IsNil)
574
575                 for _, m := range extraMounts {
576                         os.MkdirAll(cr.ArvMountPoint+"/by_id/"+m, os.ModePerm)
577                 }
578         }
579
580         err = cr.Run()
581         c.Check(err, IsNil)
582         c.Check(api.WasSetRunning, Equals, true)
583
584         c.Check(api.Content[api.Calls-1]["container"].(arvadosclient.Dict)["log"], NotNil)
585
586         if err != nil {
587                 for k, v := range api.Logs {
588                         c.Log(k)
589                         c.Log(v.String())
590                 }
591         }
592
593         return
594 }
595
596 func (s *TestSuite) TestFullRunHello(c *C) {
597         api, _, _ := FullRunHelper(c, `{
598     "command": ["echo", "hello world"],
599     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
600     "cwd": ".",
601     "environment": {},
602     "mounts": {"/tmp": {"kind": "tmp"} },
603     "output_path": "/tmp",
604     "priority": 1,
605     "runtime_constraints": {}
606 }`, nil, func(t *TestDockerClient) {
607                 t.logWriter.Write(dockerLog(1, "hello world\n"))
608                 t.logWriter.Close()
609                 t.finish <- dockerclient.WaitResult{}
610         })
611
612         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
613         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
614         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
615
616 }
617
618 func (s *TestSuite) TestCrunchstat(c *C) {
619         api, _, _ := FullRunHelper(c, `{
620                 "command": ["sleep", "1"],
621                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
622                 "cwd": ".",
623                 "environment": {},
624                 "mounts": {"/tmp": {"kind": "tmp"} },
625                 "output_path": "/tmp",
626                 "priority": 1,
627                 "runtime_constraints": {}
628         }`, nil, func(t *TestDockerClient) {
629                 time.Sleep(time.Second)
630                 t.logWriter.Close()
631                 t.finish <- dockerclient.WaitResult{}
632         })
633
634         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
635         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
636
637         // We didn't actually start a container, so crunchstat didn't
638         // find accounting files and therefore didn't log any stats.
639         // It should have logged a "can't find accounting files"
640         // message after one poll interval, though, so we can confirm
641         // it's alive:
642         c.Assert(api.Logs["crunchstat"], NotNil)
643         c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
644
645         // The "files never appeared" log assures us that we called
646         // (*crunchstat.Reporter)Stop(), and that we set it up with
647         // the correct container ID "abcde":
648         c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files never appeared for abcde\n`)
649 }
650
651 func (s *TestSuite) TestFullRunStderr(c *C) {
652         api, _, _ := FullRunHelper(c, `{
653     "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
654     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
655     "cwd": ".",
656     "environment": {},
657     "mounts": {"/tmp": {"kind": "tmp"} },
658     "output_path": "/tmp",
659     "priority": 1,
660     "runtime_constraints": {}
661 }`, nil, func(t *TestDockerClient) {
662                 t.logWriter.Write(dockerLog(1, "hello\n"))
663                 t.logWriter.Write(dockerLog(2, "world\n"))
664                 t.logWriter.Close()
665                 t.finish <- dockerclient.WaitResult{ExitCode: 1}
666         })
667
668         final := api.CalledWith("container.state", "Complete")
669         c.Assert(final, NotNil)
670         c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
671         c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
672
673         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
674         c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
675 }
676
677 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
678         api, _, _ := FullRunHelper(c, `{
679     "command": ["pwd"],
680     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
681     "cwd": ".",
682     "environment": {},
683     "mounts": {"/tmp": {"kind": "tmp"} },
684     "output_path": "/tmp",
685     "priority": 1,
686     "runtime_constraints": {}
687 }`, nil, func(t *TestDockerClient) {
688                 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
689                 t.logWriter.Close()
690                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
691         })
692
693         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
694         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
695         c.Log(api.Logs["stdout"])
696         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
697 }
698
699 func (s *TestSuite) TestFullRunSetCwd(c *C) {
700         api, _, _ := FullRunHelper(c, `{
701     "command": ["pwd"],
702     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
703     "cwd": "/bin",
704     "environment": {},
705     "mounts": {"/tmp": {"kind": "tmp"} },
706     "output_path": "/tmp",
707     "priority": 1,
708     "runtime_constraints": {}
709 }`, nil, func(t *TestDockerClient) {
710                 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
711                 t.logWriter.Close()
712                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
713         })
714
715         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
716         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
717         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
718 }
719
720 func (s *TestSuite) TestCancel(c *C) {
721         record := `{
722     "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
723     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
724     "cwd": ".",
725     "environment": {},
726     "mounts": {"/tmp": {"kind": "tmp"} },
727     "output_path": "/tmp",
728     "priority": 1,
729     "runtime_constraints": {}
730 }`
731
732         rec := arvados.Container{}
733         err := json.Unmarshal([]byte(record), &rec)
734         c.Check(err, IsNil)
735
736         docker := NewTestDockerClient()
737         docker.fn = func(t *TestDockerClient) {
738                 <-t.stop
739                 t.logWriter.Write(dockerLog(1, "foo\n"))
740                 t.logWriter.Close()
741                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
742         }
743         docker.RemoveImage(hwImageId, true)
744
745         api := &ArvTestClient{Container: rec}
746         cr := NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
747         am := &ArvMountCmdLine{}
748         cr.RunArvMount = am.ArvMountTest
749
750         go func() {
751                 for cr.ContainerID == "" {
752                         time.Sleep(time.Millisecond)
753                 }
754                 cr.SigChan <- syscall.SIGINT
755         }()
756
757         err = cr.Run()
758
759         c.Check(err, IsNil)
760         if err != nil {
761                 for k, v := range api.Logs {
762                         c.Log(k)
763                         c.Log(v.String())
764                 }
765         }
766
767         c.Check(api.CalledWith("container.log", nil), NotNil)
768         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
769         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "foo\n"), Equals, true)
770
771 }
772
773 func (s *TestSuite) TestFullRunSetEnv(c *C) {
774         api, _, _ := FullRunHelper(c, `{
775     "command": ["/bin/sh", "-c", "echo $FROBIZ"],
776     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
777     "cwd": "/bin",
778     "environment": {"FROBIZ": "bilbo"},
779     "mounts": {"/tmp": {"kind": "tmp"} },
780     "output_path": "/tmp",
781     "priority": 1,
782     "runtime_constraints": {}
783 }`, nil, func(t *TestDockerClient) {
784                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
785                 t.logWriter.Close()
786                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
787         })
788
789         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
790         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
791         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)
792 }
793
794 type ArvMountCmdLine struct {
795         Cmd   []string
796         token string
797 }
798
799 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
800         am.Cmd = c
801         am.token = token
802         return nil, nil
803 }
804
805 func stubCert(temp string) string {
806         path := temp + "/ca-certificates.crt"
807         crt, _ := os.Create(path)
808         crt.Close()
809         arvadosclient.CertFiles = []string{path}
810         return path
811 }
812
813 func (s *TestSuite) TestSetupMounts(c *C) {
814         api := &ArvTestClient{}
815         kc := &KeepTestClient{}
816         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
817         am := &ArvMountCmdLine{}
818         cr.RunArvMount = am.ArvMountTest
819
820         realTemp, err := ioutil.TempDir("", "crunchrun_test1-")
821         c.Assert(err, IsNil)
822         certTemp, err := ioutil.TempDir("", "crunchrun_test2-")
823         c.Assert(err, IsNil)
824         stubCertPath := stubCert(certTemp)
825
826         defer os.RemoveAll(realTemp)
827         defer os.RemoveAll(certTemp)
828
829         i := 0
830         cr.MkTempDir = func(_ string, prefix string) (string, error) {
831                 i++
832                 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
833                 err := os.Mkdir(d, os.ModePerm)
834                 if err != nil && strings.Contains(err.Error(), ": file exists") {
835                         // Test case must have pre-populated the tempdir
836                         err = nil
837                 }
838                 return d, err
839         }
840
841         checkEmpty := func() {
842                 filepath.Walk(realTemp, func(path string, _ os.FileInfo, err error) error {
843                         c.Check(path, Equals, realTemp)
844                         c.Check(err, IsNil)
845                         return nil
846                 })
847         }
848
849         {
850                 i = 0
851                 cr.ArvMountPoint = ""
852                 cr.Container.Mounts = make(map[string]arvados.Mount)
853                 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
854                 cr.OutputPath = "/tmp"
855
856                 err := cr.SetupMounts()
857                 c.Check(err, IsNil)
858                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
859                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/tmp"})
860                 cr.CleanupDirs()
861                 checkEmpty()
862         }
863
864         {
865                 i = 0
866                 cr.ArvMountPoint = ""
867                 cr.Container.Mounts = make(map[string]arvados.Mount)
868                 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
869                 cr.OutputPath = "/tmp"
870
871                 apiflag := true
872                 cr.Container.RuntimeConstraints.API = &apiflag
873
874                 err := cr.SetupMounts()
875                 c.Check(err, IsNil)
876                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
877                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/tmp", stubCertPath + ":/etc/arvados/ca-certificates.crt:ro"})
878                 cr.CleanupDirs()
879                 checkEmpty()
880
881                 apiflag = false
882         }
883
884         {
885                 i = 0
886                 cr.ArvMountPoint = ""
887                 cr.Container.Mounts = map[string]arvados.Mount{
888                         "/keeptmp": {Kind: "collection", Writable: true},
889                 }
890                 cr.OutputPath = "/keeptmp"
891
892                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
893
894                 err := cr.SetupMounts()
895                 c.Check(err, IsNil)
896                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
897                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/tmp0:/keeptmp"})
898                 cr.CleanupDirs()
899                 checkEmpty()
900         }
901
902         {
903                 i = 0
904                 cr.ArvMountPoint = ""
905                 cr.Container.Mounts = map[string]arvados.Mount{
906                         "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
907                         "/keepout": {Kind: "collection", Writable: true},
908                 }
909                 cr.OutputPath = "/keepout"
910
911                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
912                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
913
914                 err := cr.SetupMounts()
915                 c.Check(err, IsNil)
916                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
917                 sort.StringSlice(cr.Binds).Sort()
918                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
919                         realTemp + "/keep1/tmp0:/keepout"})
920                 cr.CleanupDirs()
921                 checkEmpty()
922         }
923
924         {
925                 i = 0
926                 cr.ArvMountPoint = ""
927                 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
928                 cr.Container.Mounts = map[string]arvados.Mount{
929                         "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
930                         "/keepout": {Kind: "collection", Writable: true},
931                 }
932                 cr.OutputPath = "/keepout"
933
934                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
935                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
936
937                 err := cr.SetupMounts()
938                 c.Check(err, IsNil)
939                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
940                 sort.StringSlice(cr.Binds).Sort()
941                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
942                         realTemp + "/keep1/tmp0:/keepout"})
943                 cr.CleanupDirs()
944                 checkEmpty()
945         }
946
947         for _, test := range []struct {
948                 in  interface{}
949                 out string
950         }{
951                 {in: "foo", out: `"foo"`},
952                 {in: nil, out: `null`},
953                 {in: map[string]int{"foo": 123}, out: `{"foo":123}`},
954         } {
955                 i = 0
956                 cr.ArvMountPoint = ""
957                 cr.Container.Mounts = map[string]arvados.Mount{
958                         "/mnt/test.json": {Kind: "json", Content: test.in},
959                 }
960                 err := cr.SetupMounts()
961                 c.Check(err, IsNil)
962                 sort.StringSlice(cr.Binds).Sort()
963                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2/mountdata.json:/mnt/test.json:ro"})
964                 content, err := ioutil.ReadFile(realTemp + "/2/mountdata.json")
965                 c.Check(err, IsNil)
966                 c.Check(content, DeepEquals, []byte(test.out))
967                 cr.CleanupDirs()
968                 checkEmpty()
969         }
970
971         // Read-only mount points are allowed underneath output_dir mount point
972         {
973                 i = 0
974                 cr.ArvMountPoint = ""
975                 cr.Container.Mounts = make(map[string]arvados.Mount)
976                 cr.Container.Mounts = map[string]arvados.Mount{
977                         "/tmp":     {Kind: "tmp"},
978                         "/tmp/foo": {Kind: "collection"},
979                 }
980                 cr.OutputPath = "/tmp"
981
982                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
983
984                 err := cr.SetupMounts()
985                 c.Check(err, IsNil)
986                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
987                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/tmp", realTemp + "/keep1/tmp0:/tmp/foo:ro"})
988                 cr.CleanupDirs()
989                 checkEmpty()
990         }
991
992         // Writable mount points are not allowed underneath output_dir mount point
993         {
994                 i = 0
995                 cr.ArvMountPoint = ""
996                 cr.Container.Mounts = make(map[string]arvados.Mount)
997                 cr.Container.Mounts = map[string]arvados.Mount{
998                         "/tmp":     {Kind: "tmp"},
999                         "/tmp/foo": {Kind: "collection", Writable: true},
1000                 }
1001                 cr.OutputPath = "/tmp"
1002
1003                 err := cr.SetupMounts()
1004                 c.Check(err, NotNil)
1005                 c.Check(err, ErrorMatches, `Writable mount points are not permitted underneath the output_path.*`)
1006                 cr.CleanupDirs()
1007                 checkEmpty()
1008         }
1009
1010         // Only mount points of kind 'collection' are allowed underneath output_dir mount point
1011         {
1012                 i = 0
1013                 cr.ArvMountPoint = ""
1014                 cr.Container.Mounts = make(map[string]arvados.Mount)
1015                 cr.Container.Mounts = map[string]arvados.Mount{
1016                         "/tmp":     {Kind: "tmp"},
1017                         "/tmp/foo": {Kind: "json"},
1018                 }
1019                 cr.OutputPath = "/tmp"
1020
1021                 err := cr.SetupMounts()
1022                 c.Check(err, NotNil)
1023                 c.Check(err, ErrorMatches, `Only mount points of kind 'collection' are supported underneath the output_path.*`)
1024                 cr.CleanupDirs()
1025                 checkEmpty()
1026         }
1027 }
1028
1029 func (s *TestSuite) TestStdout(c *C) {
1030         helperRecord := `{
1031                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1032                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1033                 "cwd": "/bin",
1034                 "environment": {"FROBIZ": "bilbo"},
1035                 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1036                 "output_path": "/tmp",
1037                 "priority": 1,
1038                 "runtime_constraints": {}
1039         }`
1040
1041         api, _, _ := FullRunHelper(c, helperRecord, nil, func(t *TestDockerClient) {
1042                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1043                 t.logWriter.Close()
1044                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1045         })
1046
1047         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1048         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1049         c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1050 }
1051
1052 // Used by the TestStdoutWithWrongPath*()
1053 func StdoutErrorRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, err error) {
1054         rec := arvados.Container{}
1055         err = json.Unmarshal([]byte(record), &rec)
1056         c.Check(err, IsNil)
1057
1058         docker := NewTestDockerClient()
1059         docker.fn = fn
1060         docker.RemoveImage(hwImageId, true)
1061
1062         api = &ArvTestClient{Container: rec}
1063         cr = NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1064         am := &ArvMountCmdLine{}
1065         cr.RunArvMount = am.ArvMountTest
1066
1067         err = cr.Run()
1068         return
1069 }
1070
1071 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1072         _, _, err := StdoutErrorRunHelper(c, `{
1073     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1074     "output_path": "/tmp"
1075 }`, func(t *TestDockerClient) {})
1076
1077         c.Check(err, NotNil)
1078         c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
1079 }
1080
1081 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1082         _, _, err := StdoutErrorRunHelper(c, `{
1083     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1084     "output_path": "/tmp"
1085 }`, func(t *TestDockerClient) {})
1086
1087         c.Check(err, NotNil)
1088         c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'tmp' for stdout"), Equals, true)
1089 }
1090
1091 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1092         _, _, err := StdoutErrorRunHelper(c, `{
1093     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1094     "output_path": "/tmp"
1095 }`, func(t *TestDockerClient) {})
1096
1097         c.Check(err, NotNil)
1098         c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'collection' for stdout"), Equals, true)
1099 }
1100
1101 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1102         os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1103         defer os.Unsetenv("ARVADOS_API_HOST")
1104         api, _, _ := FullRunHelper(c, `{
1105     "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1106     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1107     "cwd": "/bin",
1108     "environment": {},
1109     "mounts": {"/tmp": {"kind": "tmp"} },
1110     "output_path": "/tmp",
1111     "priority": 1,
1112     "runtime_constraints": {"API": true}
1113 }`, nil, func(t *TestDockerClient) {
1114                 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
1115                 t.logWriter.Close()
1116                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1117         })
1118
1119         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1120         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1121         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "test.arvados.org\n"), Equals, true)
1122         c.Check(api.CalledWith("container.output", "d41d8cd98f00b204e9800998ecf8427e+0"), NotNil)
1123 }
1124
1125 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1126         os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1127         defer os.Unsetenv("ARVADOS_API_HOST")
1128         api, _, _ := FullRunHelper(c, `{
1129     "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1130     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1131     "cwd": "/bin",
1132     "environment": {},
1133     "mounts": {"/tmp": {"kind": "tmp"} },
1134     "output_path": "/tmp",
1135     "priority": 1,
1136     "runtime_constraints": {"API": true}
1137 }`, nil, func(t *TestDockerClient) {
1138                 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
1139                 t.logWriter.Close()
1140                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1141         })
1142
1143         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1144         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1145         c.Check(api.CalledWith("container.output", "d4ab34d3d4f8a72f5c4973051ae69fab+122"), NotNil)
1146 }
1147
1148 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1149         helperRecord := `{
1150                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1151                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1152                 "cwd": "/bin",
1153                 "environment": {"FROBIZ": "bilbo"},
1154                 "mounts": {
1155         "/tmp": {"kind": "tmp"},
1156         "/tmp/foo": {"kind": "collection",
1157                      "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1158                      "exclude_from_output": true
1159         },
1160         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1161     },
1162                 "output_path": "/tmp",
1163                 "priority": 1,
1164                 "runtime_constraints": {}
1165         }`
1166
1167         extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1168
1169         api, _, _ := FullRunHelper(c, helperRecord, extraMounts, func(t *TestDockerClient) {
1170                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1171                 t.logWriter.Close()
1172                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1173         })
1174
1175         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1176         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1177         c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1178 }
1179
1180 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1181         helperRecord := `{
1182                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1183                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1184                 "cwd": "/bin",
1185                 "environment": {"FROBIZ": "bilbo"},
1186                 "mounts": {
1187         "/tmp": {"kind": "tmp"},
1188         "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1189         "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1190         "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1191         "/tmp/foo/baz/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1192         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1193     },
1194                 "output_path": "/tmp",
1195                 "priority": 1,
1196                 "runtime_constraints": {}
1197         }`
1198
1199         extraMounts := []string{
1200                 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1201                 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1202                 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1203         }
1204
1205         api, runner, realtemp := FullRunHelper(c, helperRecord, extraMounts, func(t *TestDockerClient) {
1206                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1207                 t.logWriter.Close()
1208                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1209         })
1210
1211         c.Check(runner.Binds, DeepEquals, []string{realtemp + "/2:/tmp",
1212                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt:/tmp/foo/bar:ro",
1213                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt:/tmp/foo/baz/sub2file2:ro",
1214                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1:/tmp/foo/sub1:ro",
1215                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt:/tmp/foo/sub1file2:ro",
1216         })
1217
1218         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1219         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1220         for _, v := range api.Content {
1221                 if v["collection"] != nil {
1222                         collection := v["collection"].(arvadosclient.Dict)
1223                         if strings.Index(collection["name"].(string), "output") == 0 {
1224                                 manifest := collection["manifest_text"].(string)
1225
1226                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1227 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 9:18:bar 9:18:sub1file2
1228 ./foo/baz 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2
1229 ./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1230 ./foo/sub1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1231 `)
1232                         }
1233                 }
1234         }
1235 }
1236
1237 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
1238         helperRecord := `{
1239                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1240                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1241                 "cwd": "/bin",
1242                 "environment": {"FROBIZ": "bilbo"},
1243                 "mounts": {
1244         "/tmp": {"kind": "tmp"},
1245         "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt"},
1246         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1247     },
1248                 "output_path": "/tmp",
1249                 "priority": 1,
1250                 "runtime_constraints": {}
1251         }`
1252
1253         extraMounts := []string{
1254                 "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1255         }
1256
1257         api, _, _ := FullRunHelper(c, helperRecord, extraMounts, func(t *TestDockerClient) {
1258                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1259                 t.logWriter.Close()
1260                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1261         })
1262
1263         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1264         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1265         for _, v := range api.Content {
1266                 if v["collection"] != nil {
1267                         collection := v["collection"].(arvadosclient.Dict)
1268                         if strings.Index(collection["name"].(string), "output") == 0 {
1269                                 manifest := collection["manifest_text"].(string)
1270
1271                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1272 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 10:17:bar
1273 `)
1274                         }
1275                 }
1276         }
1277 }