9397: Use ManifestTextForPath
[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 27:5649: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 27:5649:zzzzz-8i9sb-bcdefghijkdhvnk.log.txt 5676:10:subdir1/file1_in_subdir1.txt 5686:18: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) {
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         if extraMounts != nil && len(extraMounts) > 0 {
556                 err := cr.SetupArvMountPoint("keep")
557                 c.Check(err, IsNil)
558
559                 for _, m := range extraMounts {
560                         os.MkdirAll(cr.ArvMountPoint+"/by_id/"+m, os.ModePerm)
561                 }
562         }
563
564         err = cr.Run()
565         c.Check(err, IsNil)
566         c.Check(api.WasSetRunning, Equals, true)
567
568         c.Check(api.Content[api.Calls-1]["container"].(arvadosclient.Dict)["log"], NotNil)
569
570         if err != nil {
571                 for k, v := range api.Logs {
572                         c.Log(k)
573                         c.Log(v.String())
574                 }
575         }
576
577         return
578 }
579
580 func (s *TestSuite) TestFullRunHello(c *C) {
581         api, _ := FullRunHelper(c, `{
582     "command": ["echo", "hello world"],
583     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
584     "cwd": ".",
585     "environment": {},
586     "mounts": {"/tmp": {"kind": "tmp"} },
587     "output_path": "/tmp",
588     "priority": 1,
589     "runtime_constraints": {}
590 }`, nil, func(t *TestDockerClient) {
591                 t.logWriter.Write(dockerLog(1, "hello world\n"))
592                 t.logWriter.Close()
593                 t.finish <- dockerclient.WaitResult{}
594         })
595
596         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
597         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
598         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
599
600 }
601
602 func (s *TestSuite) TestCrunchstat(c *C) {
603         api, _ := FullRunHelper(c, `{
604                 "command": ["sleep", "1"],
605                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
606                 "cwd": ".",
607                 "environment": {},
608                 "mounts": {"/tmp": {"kind": "tmp"} },
609                 "output_path": "/tmp",
610                 "priority": 1,
611                 "runtime_constraints": {}
612         }`, nil, func(t *TestDockerClient) {
613                 time.Sleep(time.Second)
614                 t.logWriter.Close()
615                 t.finish <- dockerclient.WaitResult{}
616         })
617
618         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
619         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
620
621         // We didn't actually start a container, so crunchstat didn't
622         // find accounting files and therefore didn't log any stats.
623         // It should have logged a "can't find accounting files"
624         // message after one poll interval, though, so we can confirm
625         // it's alive:
626         c.Assert(api.Logs["crunchstat"], NotNil)
627         c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
628
629         // The "files never appeared" log assures us that we called
630         // (*crunchstat.Reporter)Stop(), and that we set it up with
631         // the correct container ID "abcde":
632         c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files never appeared for abcde\n`)
633 }
634
635 func (s *TestSuite) TestFullRunStderr(c *C) {
636         api, _ := FullRunHelper(c, `{
637     "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
638     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
639     "cwd": ".",
640     "environment": {},
641     "mounts": {"/tmp": {"kind": "tmp"} },
642     "output_path": "/tmp",
643     "priority": 1,
644     "runtime_constraints": {}
645 }`, nil, func(t *TestDockerClient) {
646                 t.logWriter.Write(dockerLog(1, "hello\n"))
647                 t.logWriter.Write(dockerLog(2, "world\n"))
648                 t.logWriter.Close()
649                 t.finish <- dockerclient.WaitResult{ExitCode: 1}
650         })
651
652         final := api.CalledWith("container.state", "Complete")
653         c.Assert(final, NotNil)
654         c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
655         c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
656
657         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
658         c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
659 }
660
661 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
662         api, _ := FullRunHelper(c, `{
663     "command": ["pwd"],
664     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
665     "cwd": ".",
666     "environment": {},
667     "mounts": {"/tmp": {"kind": "tmp"} },
668     "output_path": "/tmp",
669     "priority": 1,
670     "runtime_constraints": {}
671 }`, nil, func(t *TestDockerClient) {
672                 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
673                 t.logWriter.Close()
674                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
675         })
676
677         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
678         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
679         c.Log(api.Logs["stdout"])
680         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
681 }
682
683 func (s *TestSuite) TestFullRunSetCwd(c *C) {
684         api, _ := FullRunHelper(c, `{
685     "command": ["pwd"],
686     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
687     "cwd": "/bin",
688     "environment": {},
689     "mounts": {"/tmp": {"kind": "tmp"} },
690     "output_path": "/tmp",
691     "priority": 1,
692     "runtime_constraints": {}
693 }`, nil, func(t *TestDockerClient) {
694                 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
695                 t.logWriter.Close()
696                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
697         })
698
699         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
700         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
701         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
702 }
703
704 func (s *TestSuite) TestCancel(c *C) {
705         record := `{
706     "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
707     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
708     "cwd": ".",
709     "environment": {},
710     "mounts": {"/tmp": {"kind": "tmp"} },
711     "output_path": "/tmp",
712     "priority": 1,
713     "runtime_constraints": {}
714 }`
715
716         rec := arvados.Container{}
717         err := json.Unmarshal([]byte(record), &rec)
718         c.Check(err, IsNil)
719
720         docker := NewTestDockerClient()
721         docker.fn = func(t *TestDockerClient) {
722                 <-t.stop
723                 t.logWriter.Write(dockerLog(1, "foo\n"))
724                 t.logWriter.Close()
725                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
726         }
727         docker.RemoveImage(hwImageId, true)
728
729         api := &ArvTestClient{Container: rec}
730         cr := NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
731         am := &ArvMountCmdLine{}
732         cr.RunArvMount = am.ArvMountTest
733
734         go func() {
735                 for cr.ContainerID == "" {
736                         time.Sleep(time.Millisecond)
737                 }
738                 cr.SigChan <- syscall.SIGINT
739         }()
740
741         err = cr.Run()
742
743         c.Check(err, IsNil)
744         if err != nil {
745                 for k, v := range api.Logs {
746                         c.Log(k)
747                         c.Log(v.String())
748                 }
749         }
750
751         c.Check(api.CalledWith("container.log", nil), NotNil)
752         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
753         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "foo\n"), Equals, true)
754
755 }
756
757 func (s *TestSuite) TestFullRunSetEnv(c *C) {
758         api, _ := FullRunHelper(c, `{
759     "command": ["/bin/sh", "-c", "echo $FROBIZ"],
760     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
761     "cwd": "/bin",
762     "environment": {"FROBIZ": "bilbo"},
763     "mounts": {"/tmp": {"kind": "tmp"} },
764     "output_path": "/tmp",
765     "priority": 1,
766     "runtime_constraints": {}
767 }`, nil, func(t *TestDockerClient) {
768                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
769                 t.logWriter.Close()
770                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
771         })
772
773         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
774         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
775         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)
776 }
777
778 type ArvMountCmdLine struct {
779         Cmd   []string
780         token string
781 }
782
783 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
784         am.Cmd = c
785         am.token = token
786         return nil, nil
787 }
788
789 func stubCert(temp string) string {
790         path := temp + "/ca-certificates.crt"
791         crt, _ := os.Create(path)
792         crt.Close()
793         arvadosclient.CertFiles = []string{path}
794         return path
795 }
796
797 func (s *TestSuite) TestSetupMounts(c *C) {
798         api := &ArvTestClient{}
799         kc := &KeepTestClient{}
800         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
801         am := &ArvMountCmdLine{}
802         cr.RunArvMount = am.ArvMountTest
803
804         realTemp, err := ioutil.TempDir("", "crunchrun_test1-")
805         c.Assert(err, IsNil)
806         certTemp, err := ioutil.TempDir("", "crunchrun_test2-")
807         c.Assert(err, IsNil)
808         stubCertPath := stubCert(certTemp)
809
810         defer os.RemoveAll(realTemp)
811         defer os.RemoveAll(certTemp)
812
813         i := 0
814         cr.MkTempDir = func(_ string, prefix string) (string, error) {
815                 i++
816                 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
817                 err := os.Mkdir(d, os.ModePerm)
818                 if err != nil && strings.Contains(err.Error(), ": file exists") {
819                         // Test case must have pre-populated the tempdir
820                         err = nil
821                 }
822                 return d, err
823         }
824
825         checkEmpty := func() {
826                 filepath.Walk(realTemp, func(path string, _ os.FileInfo, err error) error {
827                         c.Check(path, Equals, realTemp)
828                         c.Check(err, IsNil)
829                         return nil
830                 })
831         }
832
833         {
834                 i = 0
835                 cr.ArvMountPoint = ""
836                 cr.Container.Mounts = make(map[string]arvados.Mount)
837                 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
838                 cr.OutputPath = "/tmp"
839
840                 err := cr.SetupMounts()
841                 c.Check(err, IsNil)
842                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
843                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/tmp"})
844                 cr.CleanupDirs()
845                 checkEmpty()
846         }
847
848         {
849                 i = 0
850                 cr.ArvMountPoint = ""
851                 cr.Container.Mounts = make(map[string]arvados.Mount)
852                 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
853                 cr.OutputPath = "/tmp"
854
855                 apiflag := true
856                 cr.Container.RuntimeConstraints.API = &apiflag
857
858                 err := cr.SetupMounts()
859                 c.Check(err, IsNil)
860                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
861                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/tmp", stubCertPath + ":/etc/arvados/ca-certificates.crt:ro"})
862                 cr.CleanupDirs()
863                 checkEmpty()
864
865                 apiflag = false
866         }
867
868         {
869                 i = 0
870                 cr.ArvMountPoint = ""
871                 cr.Container.Mounts = map[string]arvados.Mount{
872                         "/keeptmp": {Kind: "collection", Writable: true},
873                 }
874                 cr.OutputPath = "/keeptmp"
875
876                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
877
878                 err := cr.SetupMounts()
879                 c.Check(err, IsNil)
880                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
881                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/tmp0:/keeptmp"})
882                 cr.CleanupDirs()
883                 checkEmpty()
884         }
885
886         {
887                 i = 0
888                 cr.ArvMountPoint = ""
889                 cr.Container.Mounts = map[string]arvados.Mount{
890                         "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
891                         "/keepout": {Kind: "collection", Writable: true},
892                 }
893                 cr.OutputPath = "/keepout"
894
895                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
896                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
897
898                 err := cr.SetupMounts()
899                 c.Check(err, IsNil)
900                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
901                 sort.StringSlice(cr.Binds).Sort()
902                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
903                         realTemp + "/keep1/tmp0:/keepout"})
904                 cr.CleanupDirs()
905                 checkEmpty()
906         }
907
908         {
909                 i = 0
910                 cr.ArvMountPoint = ""
911                 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
912                 cr.Container.Mounts = map[string]arvados.Mount{
913                         "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
914                         "/keepout": {Kind: "collection", Writable: true},
915                 }
916                 cr.OutputPath = "/keepout"
917
918                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
919                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
920
921                 err := cr.SetupMounts()
922                 c.Check(err, IsNil)
923                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
924                 sort.StringSlice(cr.Binds).Sort()
925                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
926                         realTemp + "/keep1/tmp0:/keepout"})
927                 cr.CleanupDirs()
928                 checkEmpty()
929         }
930
931         for _, test := range []struct {
932                 in  interface{}
933                 out string
934         }{
935                 {in: "foo", out: `"foo"`},
936                 {in: nil, out: `null`},
937                 {in: map[string]int{"foo": 123}, out: `{"foo":123}`},
938         } {
939                 i = 0
940                 cr.ArvMountPoint = ""
941                 cr.Container.Mounts = map[string]arvados.Mount{
942                         "/mnt/test.json": {Kind: "json", Content: test.in},
943                 }
944                 err := cr.SetupMounts()
945                 c.Check(err, IsNil)
946                 sort.StringSlice(cr.Binds).Sort()
947                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2/mountdata.json:/mnt/test.json:ro"})
948                 content, err := ioutil.ReadFile(realTemp + "/2/mountdata.json")
949                 c.Check(err, IsNil)
950                 c.Check(content, DeepEquals, []byte(test.out))
951                 cr.CleanupDirs()
952                 checkEmpty()
953         }
954
955         // Read-only mount points are allowed underneath output_dir mount point
956         {
957                 i = 0
958                 cr.ArvMountPoint = ""
959                 cr.Container.Mounts = make(map[string]arvados.Mount)
960                 cr.Container.Mounts = map[string]arvados.Mount{
961                         "/tmp":     {Kind: "tmp"},
962                         "/tmp/foo": {Kind: "collection"},
963                 }
964                 cr.OutputPath = "/tmp"
965
966                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
967
968                 err := cr.SetupMounts()
969                 c.Check(err, IsNil)
970                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
971                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/tmp", realTemp + "/keep1/tmp0:/tmp/foo:ro"})
972                 cr.CleanupDirs()
973                 checkEmpty()
974         }
975
976         // Writable mount points are not allowed underneath output_dir mount point
977         {
978                 i = 0
979                 cr.ArvMountPoint = ""
980                 cr.Container.Mounts = make(map[string]arvados.Mount)
981                 cr.Container.Mounts = map[string]arvados.Mount{
982                         "/tmp":     {Kind: "tmp"},
983                         "/tmp/foo": {Kind: "collection", Writable: true},
984                 }
985                 cr.OutputPath = "/tmp"
986
987                 err := cr.SetupMounts()
988                 c.Check(err, NotNil)
989                 c.Check(err, ErrorMatches, `Writable mount points are not permitted underneath the output_path.*`)
990                 cr.CleanupDirs()
991                 checkEmpty()
992         }
993
994         // Only mount points of kind 'collection' are allowed underneath output_dir mount point
995         {
996                 i = 0
997                 cr.ArvMountPoint = ""
998                 cr.Container.Mounts = make(map[string]arvados.Mount)
999                 cr.Container.Mounts = map[string]arvados.Mount{
1000                         "/tmp":     {Kind: "tmp"},
1001                         "/tmp/foo": {Kind: "json"},
1002                 }
1003                 cr.OutputPath = "/tmp"
1004
1005                 err := cr.SetupMounts()
1006                 c.Check(err, NotNil)
1007                 c.Check(err, ErrorMatches, `Only mount points of kind 'collection' are supported underneath the output_path.*`)
1008                 cr.CleanupDirs()
1009                 checkEmpty()
1010         }
1011 }
1012
1013 func (s *TestSuite) TestStdout(c *C) {
1014         helperRecord := `{
1015                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1016                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1017                 "cwd": "/bin",
1018                 "environment": {"FROBIZ": "bilbo"},
1019                 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1020                 "output_path": "/tmp",
1021                 "priority": 1,
1022                 "runtime_constraints": {}
1023         }`
1024
1025         api, _ := FullRunHelper(c, helperRecord, nil, func(t *TestDockerClient) {
1026                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1027                 t.logWriter.Close()
1028                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1029         })
1030
1031         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1032         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1033         c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1034 }
1035
1036 // Used by the TestStdoutWithWrongPath*()
1037 func StdoutErrorRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, err error) {
1038         rec := arvados.Container{}
1039         err = json.Unmarshal([]byte(record), &rec)
1040         c.Check(err, IsNil)
1041
1042         docker := NewTestDockerClient()
1043         docker.fn = fn
1044         docker.RemoveImage(hwImageId, true)
1045
1046         api = &ArvTestClient{Container: rec}
1047         cr = NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1048         am := &ArvMountCmdLine{}
1049         cr.RunArvMount = am.ArvMountTest
1050
1051         err = cr.Run()
1052         return
1053 }
1054
1055 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1056         _, _, err := StdoutErrorRunHelper(c, `{
1057     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1058     "output_path": "/tmp"
1059 }`, func(t *TestDockerClient) {})
1060
1061         c.Check(err, NotNil)
1062         c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
1063 }
1064
1065 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1066         _, _, err := StdoutErrorRunHelper(c, `{
1067     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1068     "output_path": "/tmp"
1069 }`, func(t *TestDockerClient) {})
1070
1071         c.Check(err, NotNil)
1072         c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'tmp' for stdout"), Equals, true)
1073 }
1074
1075 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1076         _, _, err := StdoutErrorRunHelper(c, `{
1077     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1078     "output_path": "/tmp"
1079 }`, func(t *TestDockerClient) {})
1080
1081         c.Check(err, NotNil)
1082         c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'collection' for stdout"), Equals, true)
1083 }
1084
1085 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1086         os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1087         defer os.Unsetenv("ARVADOS_API_HOST")
1088         api, _ := FullRunHelper(c, `{
1089     "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1090     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1091     "cwd": "/bin",
1092     "environment": {},
1093     "mounts": {"/tmp": {"kind": "tmp"} },
1094     "output_path": "/tmp",
1095     "priority": 1,
1096     "runtime_constraints": {"API": true}
1097 }`, nil, func(t *TestDockerClient) {
1098                 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
1099                 t.logWriter.Close()
1100                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1101         })
1102
1103         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1104         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1105         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "test.arvados.org\n"), Equals, true)
1106         c.Check(api.CalledWith("container.output", "d41d8cd98f00b204e9800998ecf8427e+0"), NotNil)
1107 }
1108
1109 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1110         os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1111         defer os.Unsetenv("ARVADOS_API_HOST")
1112         api, _ := FullRunHelper(c, `{
1113     "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1114     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1115     "cwd": "/bin",
1116     "environment": {},
1117     "mounts": {"/tmp": {"kind": "tmp"} },
1118     "output_path": "/tmp",
1119     "priority": 1,
1120     "runtime_constraints": {"API": true}
1121 }`, nil, func(t *TestDockerClient) {
1122                 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
1123                 t.logWriter.Close()
1124                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1125         })
1126
1127         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1128         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1129         c.Check(api.CalledWith("container.output", "d4ab34d3d4f8a72f5c4973051ae69fab+122"), NotNil)
1130 }
1131
1132 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1133         helperRecord := `{
1134                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1135                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1136                 "cwd": "/bin",
1137                 "environment": {"FROBIZ": "bilbo"},
1138                 "mounts": {
1139         "/tmp": {"kind": "tmp"},
1140         "/tmp/foo": {"kind": "collection",
1141                      "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1142                      "exclude_from_output": true
1143         },
1144         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1145     },
1146                 "output_path": "/tmp",
1147                 "priority": 1,
1148                 "runtime_constraints": {}
1149         }`
1150
1151         extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1152
1153         api, _ := FullRunHelper(c, helperRecord, extraMounts, func(t *TestDockerClient) {
1154                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1155                 t.logWriter.Close()
1156                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1157         })
1158
1159         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1160         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1161         c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1162 }
1163
1164 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1165         helperRecord := `{
1166                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1167                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1168                 "cwd": "/bin",
1169                 "environment": {"FROBIZ": "bilbo"},
1170                 "mounts": {
1171         "/tmp": {"kind": "tmp"},
1172         "/tmp/foo": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/"},
1173         "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1174         "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1175         "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1176         "/tmp/foo/bar/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1177         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1178     },
1179                 "output_path": "/tmp",
1180                 "priority": 1,
1181                 "runtime_constraints": {}
1182         }`
1183
1184         extraMounts := []string{"a0def87f80dd594d4675809e83bd4f15+367"}
1185
1186         api, _ := FullRunHelper(c, helperRecord, extraMounts, func(t *TestDockerClient) {
1187                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1188                 t.logWriter.Close()
1189                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1190         })
1191
1192         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1193         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1194         for _, v := range api.Content {
1195                 if v["collection"] != nil {
1196                         collection := v["collection"].(arvadosclient.Dict)
1197                         if strings.Index(collection["name"].(string), "output") == 0 {
1198                                 manifest := collection["manifest_text"].(string)
1199
1200                                 c.Check(-1, Not(Equals), strings.Index(manifest, "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out"))
1201
1202                                 origManifestWithDotReplacedAsFoo := strings.Replace(normalizedManifestWithSubdirs, "./", "./foo/", -1)
1203                                 c.Check(-1, Not(Equals), strings.Index(manifest, "./foo"+origManifestWithDotReplacedAsFoo[1:]))
1204
1205                                 c.Check(-1, Not(Equals), strings.Index(manifest, "./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 9:18:bar"))
1206
1207                                 c.Check(-1, Not(Equals), strings.Index(manifest, "./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt"))
1208
1209                                 c.Check(-1, Not(Equals), strings.Index(manifest, "./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:sub1file2"))
1210
1211                                 c.Check(-1, Not(Equals), strings.Index(manifest, "./foo/bar 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2"))
1212                         }
1213                 }
1214         }
1215 }
1216
1217 func (s *TestSuite) TestStdoutWithMountPointForFileUnderOutputDir(c *C) {
1218         helperRecord := `{
1219                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1220                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1221                 "cwd": "/bin",
1222                 "environment": {"FROBIZ": "bilbo"},
1223                 "mounts": {
1224         "/tmp": {"kind": "tmp"},
1225         "/tmp/foo": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367"},
1226         "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt"},
1227         "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367/subdir1/"},
1228         "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt"},
1229         "/tmp/foo/bar/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt"},
1230         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1231     },
1232                 "output_path": "/tmp",
1233                 "priority": 1,
1234                 "runtime_constraints": {}
1235         }`
1236
1237         extraMounts := []string{
1238                 "a0def87f80dd594d4675809e83bd4f15+367",
1239                 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1240                 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1241                 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1242         }
1243
1244         api, _ := FullRunHelper(c, helperRecord, extraMounts, func(t *TestDockerClient) {
1245                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1246                 t.logWriter.Close()
1247                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1248         })
1249
1250         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1251         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1252         for _, v := range api.Content {
1253                 if v["collection"] != nil {
1254                         collection := v["collection"].(arvadosclient.Dict)
1255                         if strings.Index(collection["name"].(string), "output") == 0 {
1256                                 manifest := collection["manifest_text"].(string)
1257
1258                                 c.Check(-1, Not(Equals), strings.Index(manifest, "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out"))
1259
1260                                 origManifestWithDotReplacedAsFoo := strings.Replace(normalizedManifestWithSubdirs, "./", "./foo/", -1)
1261                                 c.Check(-1, Not(Equals), strings.Index(manifest, "./foo"+origManifestWithDotReplacedAsFoo[1:]))
1262
1263                                 c.Check(-1, Not(Equals), strings.Index(manifest, "./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 9:18:bar"))
1264
1265                                 c.Check(-1, Not(Equals), strings.Index(manifest, "./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt"))
1266
1267                                 c.Check(-1, Not(Equals), strings.Index(manifest, "./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:sub1file2"))
1268
1269                                 c.Check(-1, Not(Equals), strings.Index(manifest, "./foo/bar 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2"))
1270                         }
1271                 }
1272         }
1273 }
1274
1275 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
1276         helperRecord := `{
1277                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1278                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1279                 "cwd": "/bin",
1280                 "environment": {"FROBIZ": "bilbo"},
1281                 "mounts": {
1282         "/tmp": {"kind": "tmp"},
1283         "/tmp/foo": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path":"/"},
1284         "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path":"subdir1/file2_in_subdir1.txt"},
1285         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1286     },
1287                 "output_path": "/tmp",
1288                 "priority": 1,
1289                 "runtime_constraints": {}
1290         }`
1291
1292         extraMounts := []string{"b0def87f80dd594d4675809e83bd4f15+367"}
1293
1294         api, _ := FullRunHelper(c, helperRecord, extraMounts, func(t *TestDockerClient) {
1295                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1296                 t.logWriter.Close()
1297                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1298         })
1299
1300         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1301         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1302         for _, v := range api.Content {
1303                 if v["collection"] != nil {
1304                         collection := v["collection"].(arvadosclient.Dict)
1305                         if strings.Index(collection["name"].(string), "output") == 0 {
1306                                 manifest := collection["manifest_text"].(string)
1307
1308                                 c.Check(-1, Not(Equals), strings.Index(manifest, "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out"))
1309
1310                                 origManifestWithDotReplacedAsFoo := strings.Replace(denormalizedManifestWithSubdirs, "./", "./foo/", -1)
1311                                 c.Check(-1, Not(Equals), strings.Index(manifest, "./foo"+origManifestWithDotReplacedAsFoo[1:]))
1312
1313                                 c.Check(-1, Not(Equals), strings.Index(manifest, "./foo/bar 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 5686:18:subdir1/file2_in_subdir1.txt"))
1314                         }
1315                 }
1316         }
1317 }