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"
22 // Gocheck boilerplate
23 func TestCrunchExec(t *testing.T) {
27 type TestSuite struct{}
29 // Gocheck boilerplate
30 var _ = Suite(&TestSuite{})
32 type ArvTestClient struct {
35 Content arvadosclient.Dict
37 Logs map[string]*bytes.Buffer
41 type KeepTestClient struct {
46 var hwManifest = ". 82ab40c24fc8df01798e57ba66795bb1+841216+Aa124ac75e5168396c73c0a18eda641a4f41791c0@569fa8c3 0:841216:9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7.tar\n"
47 var hwPDH = "a45557269dcb65a6b78f9ac061c0850b+120"
48 var hwImageId = "9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7"
50 var otherManifest = ". 68a84f561b1d1708c6baff5e019a9ab3+46+Ae5d0af96944a3690becb1decdf60cc1c937f556d@5693216f 0:46:md5sum.txt\n"
51 var otherPDH = "a3e8f74c6f101eae01fa08bfb4e49b3a+54"
53 type TestDockerClient struct {
55 stdoutReader io.ReadCloser
56 stderrReader io.ReadCloser
57 stdoutWriter io.WriteCloser
58 stderrWriter io.WriteCloser
59 fn func(t *TestDockerClient)
60 finish chan dockerclient.WaitResult
66 func NewTestDockerClient() *TestDockerClient {
67 t := &TestDockerClient{}
68 t.stdoutReader, t.stdoutWriter = io.Pipe()
69 t.stderrReader, t.stderrWriter = io.Pipe()
70 t.finish = make(chan dockerclient.WaitResult)
71 t.stop = make(chan bool)
76 func (t *TestDockerClient) StopContainer(id string, timeout int) error {
81 func (t *TestDockerClient) InspectImage(id string) (*dockerclient.ImageInfo, error) {
82 if t.imageLoaded == id {
83 return &dockerclient.ImageInfo{}, nil
85 return nil, errors.New("")
89 func (t *TestDockerClient) LoadImage(reader io.Reader) error {
90 _, err := io.Copy(ioutil.Discard, reader)
94 t.imageLoaded = hwImageId
99 func (t *TestDockerClient) CreateContainer(config *dockerclient.ContainerConfig, name string, authConfig *dockerclient.AuthConfig) (string, error) {
100 if config.WorkingDir != "" {
101 t.cwd = config.WorkingDir
107 func (t *TestDockerClient) StartContainer(id string, config *dockerclient.HostConfig) error {
112 return errors.New("Invalid container id")
116 func (t *TestDockerClient) ContainerLogs(id string, options *dockerclient.LogOptions) (io.ReadCloser, error) {
118 return t.stdoutReader, nil
121 return t.stderrReader, nil
126 func (t *TestDockerClient) Wait(id string) <-chan dockerclient.WaitResult {
130 func (*TestDockerClient) RemoveImage(name string, force bool) ([]*dockerclient.ImageDelete, error) {
134 func (this *ArvTestClient) Create(resourceType string,
135 parameters arvadosclient.Dict,
136 output interface{}) error {
139 this.Content = parameters
141 if resourceType == "logs" {
142 et := parameters["event_type"].(string)
143 if this.Logs == nil {
144 this.Logs = make(map[string]*bytes.Buffer)
146 if this.Logs[et] == nil {
147 this.Logs[et] = &bytes.Buffer{}
149 this.Logs[et].Write([]byte(parameters["properties"].(map[string]string)["text"]))
152 if resourceType == "collections" && output != nil {
153 mt := parameters["manifest_text"].(string)
154 outmap := output.(*CollectionRecord)
155 outmap.PortableDataHash = fmt.Sprintf("%x+%d", md5.Sum([]byte(mt)), len(mt))
161 func (this *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
162 if resourceType == "collections" {
164 output.(*CollectionRecord).ManifestText = hwManifest
165 } else if uuid == otherPDH {
166 output.(*CollectionRecord).ManifestText = otherManifest
169 if resourceType == "containers" {
170 (*output.(*ContainerRecord)) = this.ContainerRecord
175 func (this *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
177 this.Content = parameters
178 if resourceType == "containers" {
179 if parameters["state"] == "Running" {
180 this.WasSetRunning = true
187 func (this *KeepTestClient) PutHB(hash string, buf []byte) (string, int, error) {
189 return fmt.Sprintf("%s+%d", hash, len(buf)), len(buf), nil
192 type FileWrapper struct {
197 func (this FileWrapper) Len() uint64 {
201 func (this *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.ReadCloserWithLen, error) {
202 if filename == hwImageId+".tar" {
203 rdr := ioutil.NopCloser(&bytes.Buffer{})
205 return FileWrapper{rdr, 1321984}, nil
210 func (s *TestSuite) TestLoadImage(c *C) {
211 kc := &KeepTestClient{}
212 docker := NewTestDockerClient()
213 cr := NewContainerRunner(&ArvTestClient{}, kc, docker)
215 _, err := cr.Docker.RemoveImage(hwImageId, true)
217 _, err = cr.Docker.InspectImage(hwImageId)
220 cr.ContainerRecord.ContainerImage = hwPDH
222 // (1) Test loading image from keep
223 c.Check(kc.Called, Equals, false)
224 c.Check(cr.ContainerConfig.Image, Equals, "")
230 cr.Docker.RemoveImage(hwImageId, true)
233 c.Check(kc.Called, Equals, true)
234 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
236 _, err = cr.Docker.InspectImage(hwImageId)
239 // (2) Test using image that's already loaded
241 cr.ContainerConfig.Image = ""
245 c.Check(kc.Called, Equals, false)
246 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
250 type ArvErrorTestClient struct{}
251 type KeepErrorTestClient struct{}
252 type KeepReadErrorTestClient struct{}
254 func (this ArvErrorTestClient) Create(resourceType string,
255 parameters arvadosclient.Dict,
256 output interface{}) error {
260 func (this ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
261 return errors.New("ArvError")
264 func (this ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
268 func (this KeepErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
269 return "", 0, errors.New("KeepError")
272 func (this KeepErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.ReadCloserWithLen, error) {
273 return nil, errors.New("KeepError")
276 func (this KeepReadErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
280 type ErrorReader struct{}
282 func (this ErrorReader) Read(p []byte) (n int, err error) {
283 return 0, errors.New("ErrorReader")
286 func (this ErrorReader) Close() error {
290 func (this ErrorReader) Len() uint64 {
294 func (this KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.ReadCloserWithLen, error) {
295 return ErrorReader{}, nil
298 func (s *TestSuite) TestLoadImageArvError(c *C) {
300 cr := NewContainerRunner(ArvErrorTestClient{}, &KeepTestClient{}, nil)
301 cr.ContainerRecord.ContainerImage = hwPDH
303 err := cr.LoadImage()
304 c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
307 func (s *TestSuite) TestLoadImageKeepError(c *C) {
309 docker := NewTestDockerClient()
310 cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, docker)
311 cr.ContainerRecord.ContainerImage = hwPDH
313 err := cr.LoadImage()
314 c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
317 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
318 // (3) Collection doesn't contain image
319 cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, nil)
320 cr.ContainerRecord.ContainerImage = otherPDH
322 err := cr.LoadImage()
323 c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
326 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
327 // (4) Collection doesn't contain image
328 docker := NewTestDockerClient()
329 cr := NewContainerRunner(&ArvTestClient{}, KeepReadErrorTestClient{}, docker)
330 cr.ContainerRecord.ContainerImage = hwPDH
332 err := cr.LoadImage()
336 type ClosableBuffer struct {
340 type TestLogs struct {
341 Stdout ClosableBuffer
342 Stderr ClosableBuffer
345 func (this *ClosableBuffer) Close() error {
349 func (this *TestLogs) NewTestLoggingWriter(logstr string) io.WriteCloser {
350 if logstr == "stdout" {
353 if logstr == "stderr" {
359 func (s *TestSuite) TestRunContainer(c *C) {
360 docker := NewTestDockerClient()
361 docker.fn = func(t *TestDockerClient) {
362 t.stdoutWriter.Write([]byte("Hello world\n"))
363 t.stdoutWriter.Close()
364 t.stderrWriter.Close()
365 t.finish <- dockerclient.WaitResult{}
367 cr := NewContainerRunner(&ArvTestClient{}, &KeepTestClient{}, docker)
370 cr.NewLogWriter = logs.NewTestLoggingWriter
371 cr.ContainerRecord.ContainerImage = hwPDH
372 cr.ContainerRecord.Command = []string{"./hw"}
373 err := cr.LoadImage()
376 err = cr.StartContainer()
379 err = cr.AttachLogs()
382 err = cr.WaitFinish()
385 c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
386 c.Check(logs.Stderr.String(), Equals, "")
389 func (s *TestSuite) TestCommitLogs(c *C) {
390 api := &ArvTestClient{}
391 kc := &KeepTestClient{}
392 cr := NewContainerRunner(api, kc, nil)
393 cr.ContainerRecord.UUID = "zzzzz-zzzzz-zzzzzzzzzzzzzzz"
394 cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
396 cr.CrunchLog.Print("Hello world!")
397 cr.CrunchLog.Print("Goodbye")
398 cr.finalState = "Complete"
400 err := cr.CommitLogs()
403 c.Check(api.Content["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
404 c.Check(api.Content["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
405 c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
408 func (s *TestSuite) TestUpdateContainerRecordRunning(c *C) {
409 api := &ArvTestClient{}
410 kc := &KeepTestClient{}
411 cr := NewContainerRunner(api, kc, nil)
412 cr.ContainerRecord.UUID = "zzzzz-zzzzz-zzzzzzzzzzzzzzz"
414 err := cr.UpdateContainerRecordRunning()
417 c.Check(api.Content["state"], Equals, "Running")
420 func (s *TestSuite) TestUpdateContainerRecordComplete(c *C) {
421 api := &ArvTestClient{}
422 kc := &KeepTestClient{}
423 cr := NewContainerRunner(api, kc, nil)
424 cr.ContainerRecord.UUID = "zzzzz-zzzzz-zzzzzzzzzzzzzzz"
426 cr.LogsPDH = new(string)
427 *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
429 cr.ExitCode = new(int)
431 cr.finalState = "Complete"
433 err := cr.UpdateContainerRecordComplete()
436 c.Check(api.Content["log"], Equals, *cr.LogsPDH)
437 c.Check(api.Content["exit_code"], Equals, *cr.ExitCode)
438 c.Check(api.Content["state"], Equals, "Complete")
441 func (s *TestSuite) TestUpdateContainerRecordCancelled(c *C) {
442 api := &ArvTestClient{}
443 kc := &KeepTestClient{}
444 cr := NewContainerRunner(api, kc, nil)
445 cr.ContainerRecord.UUID = "zzzzz-zzzzz-zzzzzzzzzzzzzzz"
447 cr.finalState = "Cancelled"
449 err := cr.UpdateContainerRecordComplete()
452 c.Check(api.Content["log"], IsNil)
453 c.Check(api.Content["exit_code"], IsNil)
454 c.Check(api.Content["state"], Equals, "Cancelled")
457 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
458 // dress rehersal of the Run() function, starting from a JSON container record.
459 func FullRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner) {
460 rec := ContainerRecord{}
461 err := json.NewDecoder(strings.NewReader(record)).Decode(&rec)
464 docker := NewTestDockerClient()
466 docker.RemoveImage(hwImageId, true)
468 api = &ArvTestClient{ContainerRecord: rec}
469 cr = NewContainerRunner(api, &KeepTestClient{}, docker)
471 err = cr.Run("zzzzz-zzzzz-zzzzzzzzzzzzzzz")
473 c.Check(api.WasSetRunning, Equals, true)
475 c.Check(api.Content["log"], NotNil)
478 for k, v := range api.Logs {
487 func (s *TestSuite) TestFullRunHello(c *C) {
488 api, _ := FullRunHelper(c, `{
489 "command": ["echo", "hello world"],
490 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
493 "mounts": {"/tmp": {"kind": "tmp"} },
494 "output_path": "/tmp",
496 "runtime_constraints": {}
497 }`, func(t *TestDockerClient) {
498 t.stdoutWriter.Write([]byte("hello world\n"))
499 t.stdoutWriter.Close()
500 t.stderrWriter.Close()
501 t.finish <- dockerclient.WaitResult{}
504 c.Check(api.Content["exit_code"], Equals, 0)
505 c.Check(api.Content["state"], Equals, "Complete")
507 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
511 func (s *TestSuite) TestFullRunStderr(c *C) {
512 api, _ := FullRunHelper(c, `{
513 "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
514 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
517 "mounts": {"/tmp": {"kind": "tmp"} },
518 "output_path": "/tmp",
520 "runtime_constraints": {}
521 }`, func(t *TestDockerClient) {
522 t.stdoutWriter.Write([]byte("hello\n"))
523 t.stderrWriter.Write([]byte("world\n"))
524 t.stdoutWriter.Close()
525 t.stderrWriter.Close()
526 t.finish <- dockerclient.WaitResult{ExitCode: 1}
529 c.Check(api.Content["log"], NotNil)
530 c.Check(api.Content["exit_code"], Equals, 1)
531 c.Check(api.Content["state"], Equals, "Complete")
533 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
534 c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
537 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
538 api, _ := FullRunHelper(c, `{
540 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
543 "mounts": {"/tmp": {"kind": "tmp"} },
544 "output_path": "/tmp",
546 "runtime_constraints": {}
547 }`, func(t *TestDockerClient) {
548 t.stdoutWriter.Write([]byte(t.cwd + "\n"))
549 t.stdoutWriter.Close()
550 t.stderrWriter.Close()
551 t.finish <- dockerclient.WaitResult{ExitCode: 0}
554 c.Check(api.Content["exit_code"], Equals, 0)
555 c.Check(api.Content["state"], Equals, "Complete")
557 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
560 func (s *TestSuite) TestFullRunSetCwd(c *C) {
561 api, _ := FullRunHelper(c, `{
563 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
566 "mounts": {"/tmp": {"kind": "tmp"} },
567 "output_path": "/tmp",
569 "runtime_constraints": {}
570 }`, func(t *TestDockerClient) {
571 t.stdoutWriter.Write([]byte(t.cwd + "\n"))
572 t.stdoutWriter.Close()
573 t.stderrWriter.Close()
574 t.finish <- dockerclient.WaitResult{ExitCode: 0}
577 c.Check(api.Content["exit_code"], Equals, 0)
578 c.Check(api.Content["state"], Equals, "Complete")
580 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
583 func (s *TestSuite) TestCancel(c *C) {
585 "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
586 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
589 "mounts": {"/tmp": {"kind": "tmp"} },
590 "output_path": "/tmp",
592 "runtime_constraints": {}
595 rec := ContainerRecord{}
596 err := json.NewDecoder(strings.NewReader(record)).Decode(&rec)
599 docker := NewTestDockerClient()
600 docker.fn = func(t *TestDockerClient) {
602 t.stdoutWriter.Write([]byte("foo\n"))
603 t.stdoutWriter.Close()
604 t.stderrWriter.Close()
605 t.finish <- dockerclient.WaitResult{ExitCode: 0}
607 docker.RemoveImage(hwImageId, true)
609 api := &ArvTestClient{ContainerRecord: rec}
610 cr := NewContainerRunner(api, &KeepTestClient{}, docker)
613 for cr.ContainerID == "" {
614 time.Sleep(1 * time.Second)
616 cr.SigChan <- syscall.SIGINT
619 err = cr.Run("zzzzz-zzzzz-zzzzzzzzzzzzzzz")
623 c.Check(api.Content["log"], NotNil)
626 for k, v := range api.Logs {
632 c.Check(api.Content["state"], Equals, "Cancelled")
634 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "foo\n"), Equals, true)
638 func (s *TestSuite) TestFullRunSetEnv(c *C) {
639 api, _ := FullRunHelper(c, `{
640 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
641 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
643 "environment": {"FROBIZ": "bilbo"},
644 "mounts": {"/tmp": {"kind": "tmp"} },
645 "output_path": "/tmp",
647 "runtime_constraints": {}
648 }`, func(t *TestDockerClient) {
649 t.stdoutWriter.Write([]byte(t.env[0][7:] + "\n"))
650 t.stdoutWriter.Close()
651 t.stderrWriter.Close()
652 t.finish <- dockerclient.WaitResult{ExitCode: 0}
655 c.Check(api.Content["exit_code"], Equals, 0)
656 c.Check(api.Content["state"], Equals, "Complete")
658 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)