10172: Add container.output check to TestFullRunWithAPI.
[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         WasSetRunning bool
45         sync.Mutex
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 fakeAuthUUID = "zzzzz-gj3su-55pqoyepgi2glem"
61 var fakeAuthToken = "a3ltuwzqcu2u4sc0q7yhpc2w7s00fdcqecg5d6e0u3pfohmbjt"
62
63 type TestDockerClient struct {
64         imageLoaded string
65         logReader   io.ReadCloser
66         logWriter   io.WriteCloser
67         fn          func(t *TestDockerClient)
68         finish      chan dockerclient.WaitResult
69         stop        chan bool
70         cwd         string
71         env         []string
72         api         *ArvTestClient
73 }
74
75 func NewTestDockerClient() *TestDockerClient {
76         t := &TestDockerClient{}
77         t.logReader, t.logWriter = io.Pipe()
78         t.finish = make(chan dockerclient.WaitResult)
79         t.stop = make(chan bool)
80         t.cwd = "/"
81         return t
82 }
83
84 func (t *TestDockerClient) StopContainer(id string, timeout int) error {
85         t.stop <- true
86         return nil
87 }
88
89 func (t *TestDockerClient) InspectImage(id string) (*dockerclient.ImageInfo, error) {
90         if t.imageLoaded == id {
91                 return &dockerclient.ImageInfo{}, nil
92         } else {
93                 return nil, errors.New("")
94         }
95 }
96
97 func (t *TestDockerClient) LoadImage(reader io.Reader) error {
98         _, err := io.Copy(ioutil.Discard, reader)
99         if err != nil {
100                 return err
101         } else {
102                 t.imageLoaded = hwImageId
103                 return nil
104         }
105 }
106
107 func (t *TestDockerClient) CreateContainer(config *dockerclient.ContainerConfig, name string, authConfig *dockerclient.AuthConfig) (string, error) {
108         if config.WorkingDir != "" {
109                 t.cwd = config.WorkingDir
110         }
111         t.env = config.Env
112         return "abcde", nil
113 }
114
115 func (t *TestDockerClient) StartContainer(id string, config *dockerclient.HostConfig) error {
116         if id == "abcde" {
117                 go t.fn(t)
118                 return nil
119         } else {
120                 return errors.New("Invalid container id")
121         }
122 }
123
124 func (t *TestDockerClient) AttachContainer(id string, options *dockerclient.AttachOptions) (io.ReadCloser, error) {
125         return t.logReader, nil
126 }
127
128 func (t *TestDockerClient) Wait(id string) <-chan dockerclient.WaitResult {
129         return t.finish
130 }
131
132 func (*TestDockerClient) RemoveImage(name string, force bool) ([]*dockerclient.ImageDelete, error) {
133         return nil, nil
134 }
135
136 func (client *ArvTestClient) Create(resourceType string,
137         parameters arvadosclient.Dict,
138         output interface{}) error {
139
140         client.Mutex.Lock()
141         defer client.Mutex.Unlock()
142
143         client.Calls++
144         client.Content = append(client.Content, parameters)
145
146         if resourceType == "logs" {
147                 et := parameters["log"].(arvadosclient.Dict)["event_type"].(string)
148                 if client.Logs == nil {
149                         client.Logs = make(map[string]*bytes.Buffer)
150                 }
151                 if client.Logs[et] == nil {
152                         client.Logs[et] = &bytes.Buffer{}
153                 }
154                 client.Logs[et].Write([]byte(parameters["log"].(arvadosclient.Dict)["properties"].(map[string]string)["text"]))
155         }
156
157         if resourceType == "collections" && output != nil {
158                 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
159                 outmap := output.(*arvados.Collection)
160                 outmap.PortableDataHash = fmt.Sprintf("%x+%d", md5.Sum([]byte(mt)), len(mt))
161         }
162
163         return nil
164 }
165
166 func (client *ArvTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
167         switch {
168         case method == "GET" && resourceType == "containers" && action == "auth":
169                 return json.Unmarshal([]byte(`{
170                         "kind": "arvados#api_client_authorization",
171                         "uuid": "`+fakeAuthUUID+`",
172                         "api_token": "`+fakeAuthToken+`"
173                         }`), output)
174         default:
175                 return fmt.Errorf("Not found")
176         }
177 }
178
179 func (client *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
180         if resourceType == "collections" {
181                 if uuid == hwPDH {
182                         output.(*arvados.Collection).ManifestText = hwManifest
183                 } else if uuid == otherPDH {
184                         output.(*arvados.Collection).ManifestText = otherManifest
185                 }
186         }
187         if resourceType == "containers" {
188                 (*output.(*arvados.Container)) = client.Container
189         }
190         return nil
191 }
192
193 func (client *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
194         client.Mutex.Lock()
195         defer client.Mutex.Unlock()
196         client.Calls++
197         client.Content = append(client.Content, parameters)
198         if resourceType == "containers" {
199                 if parameters["container"].(arvadosclient.Dict)["state"] == "Running" {
200                         client.WasSetRunning = true
201                 }
202         }
203         return nil
204 }
205
206 var discoveryMap = map[string]interface{}{"defaultTrashLifetime": float64(1209600)}
207
208 func (client *ArvTestClient) Discovery(key string) (interface{}, error) {
209         return discoveryMap[key], nil
210 }
211
212 // CalledWith returns the parameters from the first API call whose
213 // parameters match jpath/string. E.g., CalledWith(c, "foo.bar",
214 // "baz") returns parameters with parameters["foo"]["bar"]=="baz". If
215 // no call matches, it returns nil.
216 func (client *ArvTestClient) CalledWith(jpath string, expect interface{}) arvadosclient.Dict {
217 call:
218         for _, content := range client.Content {
219                 var v interface{} = content
220                 for _, k := range strings.Split(jpath, ".") {
221                         if dict, ok := v.(arvadosclient.Dict); !ok {
222                                 continue call
223                         } else {
224                                 v = dict[k]
225                         }
226                 }
227                 if v == expect {
228                         return content
229                 }
230         }
231         return nil
232 }
233
234 func (client *KeepTestClient) PutHB(hash string, buf []byte) (string, int, error) {
235         client.Content = buf
236         return fmt.Sprintf("%s+%d", hash, len(buf)), len(buf), nil
237 }
238
239 type FileWrapper struct {
240         io.ReadCloser
241         len uint64
242 }
243
244 func (fw FileWrapper) Len() uint64 {
245         return fw.len
246 }
247
248 func (client *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.ReadCloserWithLen, error) {
249         if filename == hwImageId+".tar" {
250                 rdr := ioutil.NopCloser(&bytes.Buffer{})
251                 client.Called = true
252                 return FileWrapper{rdr, 1321984}, nil
253         }
254         return nil, nil
255 }
256
257 func (s *TestSuite) TestLoadImage(c *C) {
258         kc := &KeepTestClient{}
259         docker := NewTestDockerClient()
260         cr := NewContainerRunner(&ArvTestClient{}, kc, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
261
262         _, err := cr.Docker.RemoveImage(hwImageId, true)
263
264         _, err = cr.Docker.InspectImage(hwImageId)
265         c.Check(err, NotNil)
266
267         cr.Container.ContainerImage = hwPDH
268
269         // (1) Test loading image from keep
270         c.Check(kc.Called, Equals, false)
271         c.Check(cr.ContainerConfig.Image, Equals, "")
272
273         err = cr.LoadImage()
274
275         c.Check(err, IsNil)
276         defer func() {
277                 cr.Docker.RemoveImage(hwImageId, true)
278         }()
279
280         c.Check(kc.Called, Equals, true)
281         c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
282
283         _, err = cr.Docker.InspectImage(hwImageId)
284         c.Check(err, IsNil)
285
286         // (2) Test using image that's already loaded
287         kc.Called = false
288         cr.ContainerConfig.Image = ""
289
290         err = cr.LoadImage()
291         c.Check(err, IsNil)
292         c.Check(kc.Called, Equals, false)
293         c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
294
295 }
296
297 type ArvErrorTestClient struct{}
298
299 func (ArvErrorTestClient) Create(resourceType string,
300         parameters arvadosclient.Dict,
301         output interface{}) error {
302         return nil
303 }
304
305 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
306         return errors.New("ArvError")
307 }
308
309 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
310         return errors.New("ArvError")
311 }
312
313 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
314         return nil
315 }
316
317 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
318         return discoveryMap[key], nil
319 }
320
321 type KeepErrorTestClient struct{}
322
323 func (KeepErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
324         return "", 0, errors.New("KeepError")
325 }
326
327 func (KeepErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.ReadCloserWithLen, error) {
328         return nil, errors.New("KeepError")
329 }
330
331 type KeepReadErrorTestClient struct{}
332
333 func (KeepReadErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
334         return "", 0, nil
335 }
336
337 type ErrorReader struct{}
338
339 func (ErrorReader) Read(p []byte) (n int, err error) {
340         return 0, errors.New("ErrorReader")
341 }
342
343 func (ErrorReader) Close() error {
344         return nil
345 }
346
347 func (ErrorReader) Len() uint64 {
348         return 0
349 }
350
351 func (KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.ReadCloserWithLen, error) {
352         return ErrorReader{}, nil
353 }
354
355 func (s *TestSuite) TestLoadImageArvError(c *C) {
356         // (1) Arvados error
357         cr := NewContainerRunner(ArvErrorTestClient{}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
358         cr.Container.ContainerImage = hwPDH
359
360         err := cr.LoadImage()
361         c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
362 }
363
364 func (s *TestSuite) TestLoadImageKeepError(c *C) {
365         // (2) Keep error
366         docker := NewTestDockerClient()
367         cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
368         cr.Container.ContainerImage = hwPDH
369
370         err := cr.LoadImage()
371         c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
372 }
373
374 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
375         // (3) Collection doesn't contain image
376         cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
377         cr.Container.ContainerImage = otherPDH
378
379         err := cr.LoadImage()
380         c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
381 }
382
383 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
384         // (4) Collection doesn't contain image
385         docker := NewTestDockerClient()
386         cr := NewContainerRunner(&ArvTestClient{}, KeepReadErrorTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
387         cr.Container.ContainerImage = hwPDH
388
389         err := cr.LoadImage()
390         c.Check(err, NotNil)
391 }
392
393 type ClosableBuffer struct {
394         bytes.Buffer
395 }
396
397 func (*ClosableBuffer) Close() error {
398         return nil
399 }
400
401 type TestLogs struct {
402         Stdout ClosableBuffer
403         Stderr ClosableBuffer
404 }
405
406 func (tl *TestLogs) NewTestLoggingWriter(logstr string) io.WriteCloser {
407         if logstr == "stdout" {
408                 return &tl.Stdout
409         }
410         if logstr == "stderr" {
411                 return &tl.Stderr
412         }
413         return nil
414 }
415
416 func dockerLog(fd byte, msg string) []byte {
417         by := []byte(msg)
418         header := make([]byte, 8+len(by))
419         header[0] = fd
420         header[7] = byte(len(by))
421         copy(header[8:], by)
422         return header
423 }
424
425 func (s *TestSuite) TestRunContainer(c *C) {
426         docker := NewTestDockerClient()
427         docker.fn = func(t *TestDockerClient) {
428                 t.logWriter.Write(dockerLog(1, "Hello world\n"))
429                 t.logWriter.Close()
430                 t.finish <- dockerclient.WaitResult{}
431         }
432         cr := NewContainerRunner(&ArvTestClient{}, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
433
434         var logs TestLogs
435         cr.NewLogWriter = logs.NewTestLoggingWriter
436         cr.Container.ContainerImage = hwPDH
437         cr.Container.Command = []string{"./hw"}
438         err := cr.LoadImage()
439         c.Check(err, IsNil)
440
441         err = cr.CreateContainer()
442         c.Check(err, IsNil)
443
444         err = cr.StartContainer()
445         c.Check(err, IsNil)
446
447         err = cr.WaitFinish()
448         c.Check(err, IsNil)
449
450         c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
451         c.Check(logs.Stderr.String(), Equals, "")
452 }
453
454 func (s *TestSuite) TestCommitLogs(c *C) {
455         api := &ArvTestClient{}
456         kc := &KeepTestClient{}
457         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
458         cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
459
460         cr.CrunchLog.Print("Hello world!")
461         cr.CrunchLog.Print("Goodbye")
462         cr.finalState = "Complete"
463
464         err := cr.CommitLogs()
465         c.Check(err, IsNil)
466
467         c.Check(api.Calls, Equals, 2)
468         c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
469         c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
470         c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
471 }
472
473 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
474         api := &ArvTestClient{}
475         kc := &KeepTestClient{}
476         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
477
478         err := cr.UpdateContainerRunning()
479         c.Check(err, IsNil)
480
481         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
482 }
483
484 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
485         api := &ArvTestClient{}
486         kc := &KeepTestClient{}
487         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
488
489         cr.LogsPDH = new(string)
490         *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
491
492         cr.ExitCode = new(int)
493         *cr.ExitCode = 42
494         cr.finalState = "Complete"
495
496         err := cr.UpdateContainerFinal()
497         c.Check(err, IsNil)
498
499         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
500         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
501         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
502 }
503
504 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
505         api := &ArvTestClient{}
506         kc := &KeepTestClient{}
507         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
508         cr.Cancelled = true
509         cr.finalState = "Cancelled"
510
511         err := cr.UpdateContainerFinal()
512         c.Check(err, IsNil)
513
514         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
515         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
516         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
517 }
518
519 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
520 // dress rehearsal of the Run() function, starting from a JSON container record.
521 func FullRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner) {
522         rec := arvados.Container{}
523         err := json.Unmarshal([]byte(record), &rec)
524         c.Check(err, IsNil)
525
526         docker := NewTestDockerClient()
527         docker.fn = fn
528         docker.RemoveImage(hwImageId, true)
529
530         api = &ArvTestClient{Container: rec}
531         docker.api = api
532         cr = NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
533         cr.statInterval = 100 * time.Millisecond
534         am := &ArvMountCmdLine{}
535         cr.RunArvMount = am.ArvMountTest
536
537         err = cr.Run()
538         c.Check(err, IsNil)
539         c.Check(api.WasSetRunning, Equals, true)
540
541         c.Check(api.Content[api.Calls-1]["container"].(arvadosclient.Dict)["log"], NotNil)
542
543         if err != nil {
544                 for k, v := range api.Logs {
545                         c.Log(k)
546                         c.Log(v.String())
547                 }
548         }
549
550         return
551 }
552
553 func (s *TestSuite) TestFullRunHello(c *C) {
554         api, _ := FullRunHelper(c, `{
555     "command": ["echo", "hello world"],
556     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
557     "cwd": ".",
558     "environment": {},
559     "mounts": {"/tmp": {"kind": "tmp"} },
560     "output_path": "/tmp",
561     "priority": 1,
562     "runtime_constraints": {}
563 }`, func(t *TestDockerClient) {
564                 t.logWriter.Write(dockerLog(1, "hello world\n"))
565                 t.logWriter.Close()
566                 t.finish <- dockerclient.WaitResult{}
567         })
568
569         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
570         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
571         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
572
573 }
574
575 func (s *TestSuite) TestCrunchstat(c *C) {
576         api, _ := FullRunHelper(c, `{
577                 "command": ["sleep", "1"],
578                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
579                 "cwd": ".",
580                 "environment": {},
581                 "mounts": {"/tmp": {"kind": "tmp"} },
582                 "output_path": "/tmp",
583                 "priority": 1,
584                 "runtime_constraints": {}
585         }`, func(t *TestDockerClient) {
586                 time.Sleep(time.Second)
587                 t.logWriter.Close()
588                 t.finish <- dockerclient.WaitResult{}
589         })
590
591         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
592         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
593
594         // We didn't actually start a container, so crunchstat didn't
595         // find accounting files and therefore didn't log any stats.
596         // It should have logged a "can't find accounting files"
597         // message after one poll interval, though, so we can confirm
598         // it's alive:
599         c.Assert(api.Logs["crunchstat"], NotNil)
600         c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
601
602         // The "files never appeared" log assures us that we called
603         // (*crunchstat.Reporter)Stop(), and that we set it up with
604         // the correct container ID "abcde":
605         c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files never appeared for abcde\n`)
606 }
607
608 func (s *TestSuite) TestFullRunStderr(c *C) {
609         api, _ := FullRunHelper(c, `{
610     "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
611     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
612     "cwd": ".",
613     "environment": {},
614     "mounts": {"/tmp": {"kind": "tmp"} },
615     "output_path": "/tmp",
616     "priority": 1,
617     "runtime_constraints": {}
618 }`, func(t *TestDockerClient) {
619                 t.logWriter.Write(dockerLog(1, "hello\n"))
620                 t.logWriter.Write(dockerLog(2, "world\n"))
621                 t.logWriter.Close()
622                 t.finish <- dockerclient.WaitResult{ExitCode: 1}
623         })
624
625         final := api.CalledWith("container.state", "Complete")
626         c.Assert(final, NotNil)
627         c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
628         c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
629
630         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
631         c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
632 }
633
634 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
635         api, _ := FullRunHelper(c, `{
636     "command": ["pwd"],
637     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
638     "cwd": ".",
639     "environment": {},
640     "mounts": {"/tmp": {"kind": "tmp"} },
641     "output_path": "/tmp",
642     "priority": 1,
643     "runtime_constraints": {}
644 }`, func(t *TestDockerClient) {
645                 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
646                 t.logWriter.Close()
647                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
648         })
649
650         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
651         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
652         c.Log(api.Logs["stdout"])
653         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
654 }
655
656 func (s *TestSuite) TestFullRunSetCwd(c *C) {
657         api, _ := FullRunHelper(c, `{
658     "command": ["pwd"],
659     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
660     "cwd": "/bin",
661     "environment": {},
662     "mounts": {"/tmp": {"kind": "tmp"} },
663     "output_path": "/tmp",
664     "priority": 1,
665     "runtime_constraints": {}
666 }`, func(t *TestDockerClient) {
667                 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
668                 t.logWriter.Close()
669                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
670         })
671
672         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
673         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
674         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
675 }
676
677 func (s *TestSuite) TestCancel(c *C) {
678         record := `{
679     "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
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 }`
688
689         rec := arvados.Container{}
690         err := json.Unmarshal([]byte(record), &rec)
691         c.Check(err, IsNil)
692
693         docker := NewTestDockerClient()
694         docker.fn = func(t *TestDockerClient) {
695                 <-t.stop
696                 t.logWriter.Write(dockerLog(1, "foo\n"))
697                 t.logWriter.Close()
698                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
699         }
700         docker.RemoveImage(hwImageId, true)
701
702         api := &ArvTestClient{Container: rec}
703         cr := NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
704         am := &ArvMountCmdLine{}
705         cr.RunArvMount = am.ArvMountTest
706
707         go func() {
708                 for cr.ContainerID == "" {
709                         time.Sleep(time.Millisecond)
710                 }
711                 cr.SigChan <- syscall.SIGINT
712         }()
713
714         err = cr.Run()
715
716         c.Check(err, IsNil)
717         if err != nil {
718                 for k, v := range api.Logs {
719                         c.Log(k)
720                         c.Log(v.String())
721                 }
722         }
723
724         c.Check(api.CalledWith("container.log", nil), NotNil)
725         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
726         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "foo\n"), Equals, true)
727
728 }
729
730 func (s *TestSuite) TestFullRunSetEnv(c *C) {
731         api, _ := FullRunHelper(c, `{
732     "command": ["/bin/sh", "-c", "echo $FROBIZ"],
733     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
734     "cwd": "/bin",
735     "environment": {"FROBIZ": "bilbo"},
736     "mounts": {"/tmp": {"kind": "tmp"} },
737     "output_path": "/tmp",
738     "priority": 1,
739     "runtime_constraints": {}
740 }`, func(t *TestDockerClient) {
741                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
742                 t.logWriter.Close()
743                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
744         })
745
746         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
747         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
748         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)
749 }
750
751 type ArvMountCmdLine struct {
752         Cmd   []string
753         token string
754 }
755
756 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
757         am.Cmd = c
758         am.token = token
759         return nil, nil
760 }
761
762 func (s *TestSuite) TestSetupMounts(c *C) {
763         api := &ArvTestClient{}
764         kc := &KeepTestClient{}
765         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
766         am := &ArvMountCmdLine{}
767         cr.RunArvMount = am.ArvMountTest
768
769         realTemp, err := ioutil.TempDir("", "crunchrun_test-")
770         c.Assert(err, IsNil)
771         defer os.RemoveAll(realTemp)
772
773         i := 0
774         cr.MkTempDir = func(_ string, prefix string) (string, error) {
775                 i++
776                 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
777                 err := os.Mkdir(d, os.ModePerm)
778                 if err != nil && strings.Contains(err.Error(), ": file exists") {
779                         // Test case must have pre-populated the tempdir
780                         err = nil
781                 }
782                 return d, err
783         }
784
785         checkEmpty := func() {
786                 filepath.Walk(realTemp, func(path string, _ os.FileInfo, err error) error {
787                         c.Check(path, Equals, realTemp)
788                         c.Check(err, IsNil)
789                         return nil
790                 })
791         }
792
793         {
794                 i = 0
795                 cr.Container.Mounts = make(map[string]arvados.Mount)
796                 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
797                 cr.OutputPath = "/tmp"
798
799                 err := cr.SetupMounts()
800                 c.Check(err, IsNil)
801                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
802                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/tmp"})
803                 cr.CleanupDirs()
804                 checkEmpty()
805         }
806
807         {
808                 i = 0
809                 cr.Container.Mounts = map[string]arvados.Mount{
810                         "/keeptmp": {Kind: "collection", Writable: true},
811                 }
812                 cr.OutputPath = "/keeptmp"
813
814                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
815
816                 err := cr.SetupMounts()
817                 c.Check(err, IsNil)
818                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
819                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/tmp0:/keeptmp"})
820                 cr.CleanupDirs()
821                 checkEmpty()
822         }
823
824         {
825                 i = 0
826                 cr.Container.Mounts = map[string]arvados.Mount{
827                         "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
828                         "/keepout": {Kind: "collection", Writable: true},
829                 }
830                 cr.OutputPath = "/keepout"
831
832                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
833                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
834
835                 err := cr.SetupMounts()
836                 c.Check(err, IsNil)
837                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
838                 sort.StringSlice(cr.Binds).Sort()
839                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
840                         realTemp + "/keep1/tmp0:/keepout"})
841                 cr.CleanupDirs()
842                 checkEmpty()
843         }
844
845         for _, test := range []struct {
846                 in  interface{}
847                 out string
848         }{
849                 {in: "foo", out: `"foo"`},
850                 {in: nil, out: `null`},
851                 {in: map[string]int{"foo": 123}, out: `{"foo":123}`},
852         } {
853                 i = 0
854                 cr.Container.Mounts = map[string]arvados.Mount{
855                         "/mnt/test.json": {Kind: "json", Content: test.in},
856                 }
857                 err := cr.SetupMounts()
858                 c.Check(err, IsNil)
859                 sort.StringSlice(cr.Binds).Sort()
860                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2/mountdata.json:/mnt/test.json:ro"})
861                 content, err := ioutil.ReadFile(realTemp + "/2/mountdata.json")
862                 c.Check(err, IsNil)
863                 c.Check(content, DeepEquals, []byte(test.out))
864                 cr.CleanupDirs()
865                 checkEmpty()
866         }
867 }
868
869 func (s *TestSuite) TestStdout(c *C) {
870         helperRecord := `{
871                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
872                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
873                 "cwd": "/bin",
874                 "environment": {"FROBIZ": "bilbo"},
875                 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
876                 "output_path": "/tmp",
877                 "priority": 1,
878                 "runtime_constraints": {}
879         }`
880
881         api, _ := FullRunHelper(c, helperRecord, func(t *TestDockerClient) {
882                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
883                 t.logWriter.Close()
884                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
885         })
886
887         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
888         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
889         c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
890 }
891
892 // Used by the TestStdoutWithWrongPath*()
893 func StdoutErrorRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, err error) {
894         rec := arvados.Container{}
895         err = json.Unmarshal([]byte(record), &rec)
896         c.Check(err, IsNil)
897
898         docker := NewTestDockerClient()
899         docker.fn = fn
900         docker.RemoveImage(hwImageId, true)
901
902         api = &ArvTestClient{Container: rec}
903         cr = NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
904         am := &ArvMountCmdLine{}
905         cr.RunArvMount = am.ArvMountTest
906
907         err = cr.Run()
908         return
909 }
910
911 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
912         _, _, err := StdoutErrorRunHelper(c, `{
913     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
914     "output_path": "/tmp"
915 }`, func(t *TestDockerClient) {})
916
917         c.Check(err, NotNil)
918         c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
919 }
920
921 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
922         _, _, err := StdoutErrorRunHelper(c, `{
923     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
924     "output_path": "/tmp"
925 }`, func(t *TestDockerClient) {})
926
927         c.Check(err, NotNil)
928         c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'tmp' for stdout"), Equals, true)
929 }
930
931 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
932         _, _, err := StdoutErrorRunHelper(c, `{
933     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
934     "output_path": "/tmp"
935 }`, func(t *TestDockerClient) {})
936
937         c.Check(err, NotNil)
938         c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'collection' for stdout"), Equals, true)
939 }
940
941 func (s *TestSuite) TestFullRunWithAPI(c *C) {
942         os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
943         defer os.Unsetenv("ARVADOS_API_HOST")
944         api, _ := FullRunHelper(c, `{
945     "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
946     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
947     "cwd": "/bin",
948     "environment": {},
949     "mounts": {"/tmp": {"kind": "tmp"} },
950     "output_path": "/tmp",
951     "priority": 1,
952     "runtime_constraints": {"API": true}
953 }`, func(t *TestDockerClient) {
954                 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
955                 t.logWriter.Close()
956                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
957         })
958
959         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
960         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
961         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "test.arvados.org\n"), Equals, true)
962         c.Check(api.CalledWith("container.output", "d41d8cd98f00b204e9800998ecf8427e+0"), NotNil)
963 }
964
965 func (s *TestSuite) TestFullRunSetOutput(c *C) {
966         os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
967         defer os.Unsetenv("ARVADOS_API_HOST")
968         api, _ := FullRunHelper(c, `{
969     "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
970     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
971     "cwd": "/bin",
972     "environment": {},
973     "mounts": {"/tmp": {"kind": "tmp"} },
974     "output_path": "/tmp",
975     "priority": 1,
976     "runtime_constraints": {"API": true}
977 }`, func(t *TestDockerClient) {
978                 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
979                 t.logWriter.Close()
980                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
981         })
982
983         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
984         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
985         c.Check(api.CalledWith("container.output", "d4ab34d3d4f8a72f5c4973051ae69fab+122"), NotNil)
986 }