Merge branch '8876-work-unit' into 8650-container-work-unit
[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/arvadosclient"
10         "git.curoverse.com/arvados.git/sdk/go/keepclient"
11         "git.curoverse.com/arvados.git/sdk/go/manifest"
12         "github.com/curoverse/dockerclient"
13         . "gopkg.in/check.v1"
14         "io"
15         "io/ioutil"
16         "log"
17         "os"
18         "os/exec"
19         "sort"
20         "strings"
21         "sync"
22         "syscall"
23         "testing"
24         "time"
25 )
26
27 // Gocheck boilerplate
28 func TestCrunchExec(t *testing.T) {
29         TestingT(t)
30 }
31
32 type TestSuite struct{}
33
34 // Gocheck boilerplate
35 var _ = Suite(&TestSuite{})
36
37 type ArvTestClient struct {
38         Total   int64
39         Calls   int
40         Content []arvadosclient.Dict
41         ContainerRecord
42         Logs          map[string]*bytes.Buffer
43         WasSetRunning bool
44         sync.Mutex
45 }
46
47 type KeepTestClient struct {
48         Called  bool
49         Content []byte
50 }
51
52 var hwManifest = ". 82ab40c24fc8df01798e57ba66795bb1+841216+Aa124ac75e5168396c73c0a18eda641a4f41791c0@569fa8c3 0:841216:9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7.tar\n"
53 var hwPDH = "a45557269dcb65a6b78f9ac061c0850b+120"
54 var hwImageId = "9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7"
55
56 var otherManifest = ". 68a84f561b1d1708c6baff5e019a9ab3+46+Ae5d0af96944a3690becb1decdf60cc1c937f556d@5693216f 0:46:md5sum.txt\n"
57 var otherPDH = "a3e8f74c6f101eae01fa08bfb4e49b3a+54"
58
59 type TestDockerClient struct {
60         imageLoaded string
61         logReader   io.ReadCloser
62         logWriter   io.WriteCloser
63         fn          func(t *TestDockerClient)
64         finish      chan dockerclient.WaitResult
65         stop        chan bool
66         cwd         string
67         env         []string
68 }
69
70 func NewTestDockerClient() *TestDockerClient {
71         t := &TestDockerClient{}
72         t.logReader, t.logWriter = io.Pipe()
73         t.finish = make(chan dockerclient.WaitResult)
74         t.stop = make(chan bool)
75         t.cwd = "/"
76         return t
77 }
78
79 func (t *TestDockerClient) StopContainer(id string, timeout int) error {
80         t.stop <- true
81         return nil
82 }
83
84 func (t *TestDockerClient) InspectImage(id string) (*dockerclient.ImageInfo, error) {
85         if t.imageLoaded == id {
86                 return &dockerclient.ImageInfo{}, nil
87         } else {
88                 return nil, errors.New("")
89         }
90 }
91
92 func (t *TestDockerClient) LoadImage(reader io.Reader) error {
93         _, err := io.Copy(ioutil.Discard, reader)
94         if err != nil {
95                 return err
96         } else {
97                 t.imageLoaded = hwImageId
98                 return nil
99         }
100 }
101
102 func (t *TestDockerClient) CreateContainer(config *dockerclient.ContainerConfig, name string, authConfig *dockerclient.AuthConfig) (string, error) {
103         if config.WorkingDir != "" {
104                 t.cwd = config.WorkingDir
105         }
106         t.env = config.Env
107         return "abcde", nil
108 }
109
110 func (t *TestDockerClient) StartContainer(id string, config *dockerclient.HostConfig) error {
111         if id == "abcde" {
112                 go t.fn(t)
113                 return nil
114         } else {
115                 return errors.New("Invalid container id")
116         }
117 }
118
119 func (t *TestDockerClient) AttachContainer(id string, options *dockerclient.AttachOptions) (io.ReadCloser, error) {
120         return t.logReader, nil
121 }
122
123 func (t *TestDockerClient) Wait(id string) <-chan dockerclient.WaitResult {
124         return t.finish
125 }
126
127 func (*TestDockerClient) RemoveImage(name string, force bool) ([]*dockerclient.ImageDelete, error) {
128         return nil, nil
129 }
130
131 func (this *ArvTestClient) Create(resourceType string,
132         parameters arvadosclient.Dict,
133         output interface{}) error {
134
135         this.Mutex.Lock()
136         defer this.Mutex.Unlock()
137
138         this.Calls += 1
139         this.Content = append(this.Content, parameters)
140
141         if resourceType == "logs" {
142                 et := parameters["log"].(arvadosclient.Dict)["event_type"].(string)
143                 if this.Logs == nil {
144                         this.Logs = make(map[string]*bytes.Buffer)
145                 }
146                 if this.Logs[et] == nil {
147                         this.Logs[et] = &bytes.Buffer{}
148                 }
149                 this.Logs[et].Write([]byte(parameters["log"].(arvadosclient.Dict)["properties"].(map[string]string)["text"]))
150         }
151
152         if resourceType == "collections" && output != nil {
153                 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
154                 outmap := output.(*CollectionRecord)
155                 outmap.PortableDataHash = fmt.Sprintf("%x+%d", md5.Sum([]byte(mt)), len(mt))
156         }
157
158         return nil
159 }
160
161 func (this *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
162         if resourceType == "collections" {
163                 if uuid == hwPDH {
164                         output.(*CollectionRecord).ManifestText = hwManifest
165                 } else if uuid == otherPDH {
166                         output.(*CollectionRecord).ManifestText = otherManifest
167                 }
168         }
169         if resourceType == "containers" {
170                 (*output.(*ContainerRecord)) = this.ContainerRecord
171         }
172         return nil
173 }
174
175 func (this *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
176         this.Mutex.Lock()
177         defer this.Mutex.Unlock()
178         this.Calls += 1
179         this.Content = append(this.Content, parameters)
180         if resourceType == "containers" {
181                 if parameters["container"].(arvadosclient.Dict)["state"] == "Running" {
182                         this.WasSetRunning = true
183                 }
184         }
185         return nil
186 }
187
188 // CalledWith returns the parameters from the first API call whose
189 // parameters match jpath/string. E.g., CalledWith(c, "foo.bar",
190 // "baz") returns parameters with parameters["foo"]["bar"]=="baz". If
191 // no call matches, it returns nil.
192 func (this *ArvTestClient) CalledWith(jpath, expect string) arvadosclient.Dict {
193         call: for _, content := range this.Content {
194                 var v interface{} = content
195                 for _, k := range strings.Split(jpath, ".") {
196                         if dict, ok := v.(arvadosclient.Dict); !ok {
197                                 continue call
198                         } else {
199                                 v = dict[k]
200                         }
201                 }
202                 if v, ok := v.(string); ok && v == expect {
203                         return content
204                 }
205         }
206         return nil
207 }
208
209 func (this *KeepTestClient) PutHB(hash string, buf []byte) (string, int, error) {
210         this.Content = buf
211         return fmt.Sprintf("%s+%d", hash, len(buf)), len(buf), nil
212 }
213
214 type FileWrapper struct {
215         io.ReadCloser
216         len uint64
217 }
218
219 func (this FileWrapper) Len() uint64 {
220         return this.len
221 }
222
223 func (this *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.ReadCloserWithLen, error) {
224         if filename == hwImageId+".tar" {
225                 rdr := ioutil.NopCloser(&bytes.Buffer{})
226                 this.Called = true
227                 return FileWrapper{rdr, 1321984}, nil
228         }
229         return nil, nil
230 }
231
232 func (s *TestSuite) TestLoadImage(c *C) {
233         kc := &KeepTestClient{}
234         docker := NewTestDockerClient()
235         cr := NewContainerRunner(&ArvTestClient{}, kc, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
236
237         _, err := cr.Docker.RemoveImage(hwImageId, true)
238
239         _, err = cr.Docker.InspectImage(hwImageId)
240         c.Check(err, NotNil)
241
242         cr.ContainerRecord.ContainerImage = hwPDH
243
244         // (1) Test loading image from keep
245         c.Check(kc.Called, Equals, false)
246         c.Check(cr.ContainerConfig.Image, Equals, "")
247
248         err = cr.LoadImage()
249
250         c.Check(err, IsNil)
251         defer func() {
252                 cr.Docker.RemoveImage(hwImageId, true)
253         }()
254
255         c.Check(kc.Called, Equals, true)
256         c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
257
258         _, err = cr.Docker.InspectImage(hwImageId)
259         c.Check(err, IsNil)
260
261         // (2) Test using image that's already loaded
262         kc.Called = false
263         cr.ContainerConfig.Image = ""
264
265         err = cr.LoadImage()
266         c.Check(err, IsNil)
267         c.Check(kc.Called, Equals, false)
268         c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
269
270 }
271
272 type ArvErrorTestClient struct{}
273 type KeepErrorTestClient struct{}
274 type KeepReadErrorTestClient struct{}
275
276 func (this ArvErrorTestClient) Create(resourceType string,
277         parameters arvadosclient.Dict,
278         output interface{}) error {
279         return nil
280 }
281
282 func (this ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
283         return errors.New("ArvError")
284 }
285
286 func (this ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
287         return nil
288 }
289
290 func (this KeepErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
291         return "", 0, errors.New("KeepError")
292 }
293
294 func (this KeepErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.ReadCloserWithLen, error) {
295         return nil, errors.New("KeepError")
296 }
297
298 func (this KeepReadErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
299         return "", 0, nil
300 }
301
302 type ErrorReader struct{}
303
304 func (this ErrorReader) Read(p []byte) (n int, err error) {
305         return 0, errors.New("ErrorReader")
306 }
307
308 func (this ErrorReader) Close() error {
309         return nil
310 }
311
312 func (this ErrorReader) Len() uint64 {
313         return 0
314 }
315
316 func (this KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.ReadCloserWithLen, error) {
317         return ErrorReader{}, nil
318 }
319
320 func (s *TestSuite) TestLoadImageArvError(c *C) {
321         // (1) Arvados error
322         cr := NewContainerRunner(ArvErrorTestClient{}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
323         cr.ContainerRecord.ContainerImage = hwPDH
324
325         err := cr.LoadImage()
326         c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
327 }
328
329 func (s *TestSuite) TestLoadImageKeepError(c *C) {
330         // (2) Keep error
331         docker := NewTestDockerClient()
332         cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
333         cr.ContainerRecord.ContainerImage = hwPDH
334
335         err := cr.LoadImage()
336         c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
337 }
338
339 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
340         // (3) Collection doesn't contain image
341         cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
342         cr.ContainerRecord.ContainerImage = otherPDH
343
344         err := cr.LoadImage()
345         c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
346 }
347
348 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
349         // (4) Collection doesn't contain image
350         docker := NewTestDockerClient()
351         cr := NewContainerRunner(&ArvTestClient{}, KeepReadErrorTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
352         cr.ContainerRecord.ContainerImage = hwPDH
353
354         err := cr.LoadImage()
355         c.Check(err, NotNil)
356 }
357
358 type ClosableBuffer struct {
359         bytes.Buffer
360 }
361
362 type TestLogs struct {
363         Stdout ClosableBuffer
364         Stderr ClosableBuffer
365 }
366
367 func (this *ClosableBuffer) Close() error {
368         return nil
369 }
370
371 func (this *TestLogs) NewTestLoggingWriter(logstr string) io.WriteCloser {
372         if logstr == "stdout" {
373                 return &this.Stdout
374         }
375         if logstr == "stderr" {
376                 return &this.Stderr
377         }
378         return nil
379 }
380
381 func dockerLog(fd byte, msg string) []byte {
382         by := []byte(msg)
383         header := make([]byte, 8+len(by))
384         header[0] = fd
385         header[7] = byte(len(by))
386         copy(header[8:], by)
387         return header
388 }
389
390 func (s *TestSuite) TestRunContainer(c *C) {
391         docker := NewTestDockerClient()
392         docker.fn = func(t *TestDockerClient) {
393                 t.logWriter.Write(dockerLog(1, "Hello world\n"))
394                 t.logWriter.Close()
395                 t.finish <- dockerclient.WaitResult{}
396         }
397         cr := NewContainerRunner(&ArvTestClient{}, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
398
399         var logs TestLogs
400         cr.NewLogWriter = logs.NewTestLoggingWriter
401         cr.ContainerRecord.ContainerImage = hwPDH
402         cr.ContainerRecord.Command = []string{"./hw"}
403         err := cr.LoadImage()
404         c.Check(err, IsNil)
405
406         err = cr.StartContainer()
407         c.Check(err, IsNil)
408
409         err = cr.WaitFinish()
410         c.Check(err, IsNil)
411
412         c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
413         c.Check(logs.Stderr.String(), Equals, "")
414 }
415
416 func (s *TestSuite) TestCommitLogs(c *C) {
417         api := &ArvTestClient{}
418         kc := &KeepTestClient{}
419         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
420         cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
421
422         cr.CrunchLog.Print("Hello world!")
423         cr.CrunchLog.Print("Goodbye")
424         cr.finalState = "Complete"
425
426         err := cr.CommitLogs()
427         c.Check(err, IsNil)
428
429         c.Check(api.Calls, Equals, 2)
430         c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
431         c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
432         c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
433 }
434
435 func (s *TestSuite) TestUpdateContainerRecordRunning(c *C) {
436         api := &ArvTestClient{}
437         kc := &KeepTestClient{}
438         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
439
440         err := cr.UpdateContainerRecordRunning()
441         c.Check(err, IsNil)
442
443         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
444 }
445
446 func (s *TestSuite) TestUpdateContainerRecordComplete(c *C) {
447         api := &ArvTestClient{}
448         kc := &KeepTestClient{}
449         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
450
451         cr.LogsPDH = new(string)
452         *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
453
454         cr.ExitCode = new(int)
455         *cr.ExitCode = 42
456         cr.finalState = "Complete"
457
458         err := cr.UpdateContainerRecordComplete()
459         c.Check(err, IsNil)
460
461         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
462         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
463         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
464 }
465
466 func (s *TestSuite) TestUpdateContainerRecordCancelled(c *C) {
467         api := &ArvTestClient{}
468         kc := &KeepTestClient{}
469         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
470         cr.Cancelled = true
471         cr.finalState = "Cancelled"
472
473         err := cr.UpdateContainerRecordComplete()
474         c.Check(err, IsNil)
475
476         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
477         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
478         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
479 }
480
481 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
482 // dress rehearsal of the Run() function, starting from a JSON container record.
483 func FullRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner) {
484         rec := ContainerRecord{}
485         err := json.NewDecoder(strings.NewReader(record)).Decode(&rec)
486         c.Check(err, IsNil)
487
488         docker := NewTestDockerClient()
489         docker.fn = fn
490         docker.RemoveImage(hwImageId, true)
491
492         api = &ArvTestClient{ContainerRecord: rec}
493         cr = NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
494         am := &ArvMountCmdLine{}
495         cr.RunArvMount = am.ArvMountTest
496
497         err = cr.Run()
498         c.Check(err, IsNil)
499         c.Check(api.WasSetRunning, Equals, true)
500
501         c.Check(api.Content[api.Calls-1]["container"].(arvadosclient.Dict)["log"], NotNil)
502
503         if err != nil {
504                 for k, v := range api.Logs {
505                         c.Log(k)
506                         c.Log(v.String())
507                 }
508         }
509
510         return
511 }
512
513 func (s *TestSuite) TestFullRunHello(c *C) {
514         api, _ := FullRunHelper(c, `{
515     "command": ["echo", "hello world"],
516     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
517     "cwd": ".",
518     "environment": {},
519     "mounts": {"/tmp": {"kind": "tmp"} },
520     "output_path": "/tmp",
521     "priority": 1,
522     "runtime_constraints": {}
523 }`, func(t *TestDockerClient) {
524                 t.logWriter.Write(dockerLog(1, "hello world\n"))
525                 t.logWriter.Close()
526                 t.finish <- dockerclient.WaitResult{}
527         })
528
529         c.Check(api.Calls, Equals, 7)
530         c.Check(api.Content[6]["container"].(arvadosclient.Dict)["exit_code"], Equals, 0)
531         c.Check(api.Content[6]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
532
533         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
534
535 }
536
537 func (s *TestSuite) TestFullRunStderr(c *C) {
538         api, _ := FullRunHelper(c, `{
539     "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
540     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
541     "cwd": ".",
542     "environment": {},
543     "mounts": {"/tmp": {"kind": "tmp"} },
544     "output_path": "/tmp",
545     "priority": 1,
546     "runtime_constraints": {}
547 }`, func(t *TestDockerClient) {
548                 t.logWriter.Write(dockerLog(1, "hello\n"))
549                 t.logWriter.Write(dockerLog(2, "world\n"))
550                 t.logWriter.Close()
551                 t.finish <- dockerclient.WaitResult{ExitCode: 1}
552         })
553
554         c.Assert(api.Calls, Equals, 8)
555         c.Check(api.Content[7]["container"].(arvadosclient.Dict)["log"], NotNil)
556         c.Check(api.Content[7]["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
557         c.Check(api.Content[7]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
558
559         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
560         c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
561 }
562
563 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
564         api, _ := FullRunHelper(c, `{
565     "command": ["pwd"],
566     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
567     "cwd": ".",
568     "environment": {},
569     "mounts": {"/tmp": {"kind": "tmp"} },
570     "output_path": "/tmp",
571     "priority": 1,
572     "runtime_constraints": {}
573 }`, func(t *TestDockerClient) {
574                 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
575                 t.logWriter.Close()
576                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
577         })
578
579         c.Check(api.Calls, Equals, 7)
580         c.Check(api.Content[6]["container"].(arvadosclient.Dict)["exit_code"], Equals, 0)
581         c.Check(api.Content[6]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
582
583         log.Print(api.Logs["stdout"].String())
584
585         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
586 }
587
588 func (s *TestSuite) TestFullRunSetCwd(c *C) {
589         api, _ := FullRunHelper(c, `{
590     "command": ["pwd"],
591     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
592     "cwd": "/bin",
593     "environment": {},
594     "mounts": {"/tmp": {"kind": "tmp"} },
595     "output_path": "/tmp",
596     "priority": 1,
597     "runtime_constraints": {}
598 }`, func(t *TestDockerClient) {
599                 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
600                 t.logWriter.Close()
601                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
602         })
603
604         c.Check(api.Calls, Equals, 7)
605         c.Check(api.Content[6]["container"].(arvadosclient.Dict)["exit_code"], Equals, 0)
606         c.Check(api.Content[6]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
607
608         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
609 }
610
611 func (s *TestSuite) TestCancel(c *C) {
612         record := `{
613     "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
614     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
615     "cwd": ".",
616     "environment": {},
617     "mounts": {"/tmp": {"kind": "tmp"} },
618     "output_path": "/tmp",
619     "priority": 1,
620     "runtime_constraints": {}
621 }`
622
623         rec := ContainerRecord{}
624         err := json.NewDecoder(strings.NewReader(record)).Decode(&rec)
625         c.Check(err, IsNil)
626
627         docker := NewTestDockerClient()
628         docker.fn = func(t *TestDockerClient) {
629                 <-t.stop
630                 t.logWriter.Write(dockerLog(1, "foo\n"))
631                 t.logWriter.Close()
632                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
633         }
634         docker.RemoveImage(hwImageId, true)
635
636         api := &ArvTestClient{ContainerRecord: rec}
637         cr := NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
638         am := &ArvMountCmdLine{}
639         cr.RunArvMount = am.ArvMountTest
640
641         go func() {
642                 for cr.ContainerID == "" {
643                         time.Sleep(time.Millisecond)
644                 }
645                 cr.SigChan <- syscall.SIGINT
646         }()
647
648         err = cr.Run()
649
650         c.Check(err, IsNil)
651
652         c.Check(api.Calls, Equals, 6)
653         c.Check(api.Content[5]["container"].(arvadosclient.Dict)["log"], NotNil)
654
655         if err != nil {
656                 for k, v := range api.Logs {
657                         c.Log(k)
658                         c.Log(v.String())
659                 }
660         }
661
662         c.Check(api.Content[5]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
663
664         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "foo\n"), Equals, true)
665
666 }
667
668 func (s *TestSuite) TestFullRunSetEnv(c *C) {
669         api, _ := FullRunHelper(c, `{
670     "command": ["/bin/sh", "-c", "echo $FROBIZ"],
671     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
672     "cwd": "/bin",
673     "environment": {"FROBIZ": "bilbo"},
674     "mounts": {"/tmp": {"kind": "tmp"} },
675     "output_path": "/tmp",
676     "priority": 1,
677     "runtime_constraints": {}
678 }`, func(t *TestDockerClient) {
679                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
680                 t.logWriter.Close()
681                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
682         })
683
684         c.Check(api.Calls, Equals, 7)
685         c.Check(api.Content[6]["container"].(arvadosclient.Dict)["exit_code"], Equals, 0)
686         c.Check(api.Content[6]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
687
688         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)
689 }
690
691 type ArvMountCmdLine struct {
692         Cmd []string
693 }
694
695 func (am *ArvMountCmdLine) ArvMountTest(c []string) (*exec.Cmd, error) {
696         am.Cmd = c
697         return nil, nil
698 }
699
700 func (s *TestSuite) TestSetupMounts(c *C) {
701         api := &ArvTestClient{}
702         kc := &KeepTestClient{}
703         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
704         am := &ArvMountCmdLine{}
705         cr.RunArvMount = am.ArvMountTest
706
707         i := 0
708         cr.MkTempDir = func(string, string) (string, error) {
709                 i += 1
710                 d := fmt.Sprintf("/tmp/mktmpdir%d", i)
711                 os.Mkdir(d, os.ModePerm)
712                 return d, nil
713         }
714
715         {
716                 cr.ContainerRecord.Mounts = make(map[string]Mount)
717                 cr.ContainerRecord.Mounts["/tmp"] = Mount{Kind: "tmp"}
718                 cr.OutputPath = "/tmp"
719
720                 err := cr.SetupMounts()
721                 c.Check(err, IsNil)
722                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-by-pdh", "by_id", "/tmp/mktmpdir1"})
723                 c.Check(cr.Binds, DeepEquals, []string{"/tmp/mktmpdir2:/tmp"})
724                 cr.CleanupDirs()
725         }
726
727         {
728                 i = 0
729                 cr.ContainerRecord.Mounts = make(map[string]Mount)
730                 cr.ContainerRecord.Mounts["/keeptmp"] = Mount{Kind: "collection", Writable: true}
731                 cr.OutputPath = "/keeptmp"
732
733                 os.MkdirAll("/tmp/mktmpdir1/tmp0", os.ModePerm)
734
735                 err := cr.SetupMounts()
736                 c.Check(err, IsNil)
737                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", "/tmp/mktmpdir1"})
738                 c.Check(cr.Binds, DeepEquals, []string{"/tmp/mktmpdir1/tmp0:/keeptmp"})
739                 cr.CleanupDirs()
740         }
741
742         {
743                 i = 0
744                 cr.ContainerRecord.Mounts = make(map[string]Mount)
745                 cr.ContainerRecord.Mounts["/keepinp"] = Mount{Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"}
746                 cr.ContainerRecord.Mounts["/keepout"] = Mount{Kind: "collection", Writable: true}
747                 cr.OutputPath = "/keepout"
748
749                 os.MkdirAll("/tmp/mktmpdir1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
750                 os.MkdirAll("/tmp/mktmpdir1/tmp0", os.ModePerm)
751
752                 err := cr.SetupMounts()
753                 c.Check(err, IsNil)
754                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", "/tmp/mktmpdir1"})
755                 var ss sort.StringSlice = cr.Binds
756                 ss.Sort()
757                 c.Check(cr.Binds, DeepEquals, []string{"/tmp/mktmpdir1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
758                         "/tmp/mktmpdir1/tmp0:/keepout"})
759                 cr.CleanupDirs()
760         }
761 }
762
763 func (s *TestSuite) TestStdout(c *C) {
764         helperRecord := `{`
765         helperRecord += `"command": ["/bin/sh", "-c", "echo $FROBIZ"],`
766         helperRecord += `"container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",`
767         helperRecord += `"cwd": "/bin",`
768         helperRecord += `"environment": {"FROBIZ": "bilbo"},`
769         helperRecord += `"mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },`
770         helperRecord += `"output_path": "/tmp",`
771         helperRecord += `"priority": 1,`
772         helperRecord += `"runtime_constraints": {}`
773         helperRecord += `}`
774
775         api, _ := FullRunHelper(c, helperRecord, func(t *TestDockerClient) {
776                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
777                 t.logWriter.Close()
778                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
779         })
780
781         c.Assert(api.Calls, Equals, 6)
782         c.Check(api.Content[5]["container"].(arvadosclient.Dict)["exit_code"], Equals, 0)
783         c.Check(api.Content[5]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
784         c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), Not(IsNil))
785 }
786
787 // Used by the TestStdoutWithWrongPath*()
788 func StdoutErrorRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, err error) {
789         rec := ContainerRecord{}
790         err = json.NewDecoder(strings.NewReader(record)).Decode(&rec)
791         c.Check(err, IsNil)
792
793         docker := NewTestDockerClient()
794         docker.fn = fn
795         docker.RemoveImage(hwImageId, true)
796
797         api = &ArvTestClient{ContainerRecord: rec}
798         cr = NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
799         am := &ArvMountCmdLine{}
800         cr.RunArvMount = am.ArvMountTest
801
802         err = cr.Run()
803         return
804 }
805
806 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
807         _, _, err := StdoutErrorRunHelper(c, `{
808     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
809     "output_path": "/tmp"
810 }`, func(t *TestDockerClient) {})
811
812         c.Check(err, NotNil)
813         c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
814 }
815
816 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
817         _, _, err := StdoutErrorRunHelper(c, `{
818     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
819     "output_path": "/tmp"
820 }`, func(t *TestDockerClient) {})
821
822         c.Check(err, NotNil)
823         c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'tmp' for stdout"), Equals, true)
824 }
825
826 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
827         _, _, err := StdoutErrorRunHelper(c, `{
828     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
829     "output_path": "/tmp"
830 }`, func(t *TestDockerClient) {})
831
832         c.Check(err, NotNil)
833         c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'collection' for stdout"), Equals, true)
834 }