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["log"].(arvadosclient.Dict)["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["log"].(arvadosclient.Dict)["properties"].(map[string]string)["text"]))
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))
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["container"].(arvadosclient.Dict)["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, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
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, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
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, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
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, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
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, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
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, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
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, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
393 cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
395 cr.CrunchLog.Print("Hello world!")
396 cr.CrunchLog.Print("Goodbye")
397 cr.finalState = "Complete"
399 err := cr.CommitLogs()
402 c.Check(api.Content["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
403 c.Check(api.Content["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
404 c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
407 func (s *TestSuite) TestUpdateContainerRecordRunning(c *C) {
408 api := &ArvTestClient{}
409 kc := &KeepTestClient{}
410 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
412 err := cr.UpdateContainerRecordRunning()
415 c.Check(api.Content["container"].(arvadosclient.Dict)["state"], Equals, "Running")
418 func (s *TestSuite) TestUpdateContainerRecordComplete(c *C) {
419 api := &ArvTestClient{}
420 kc := &KeepTestClient{}
421 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
423 cr.LogsPDH = new(string)
424 *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
426 cr.ExitCode = new(int)
428 cr.finalState = "Complete"
430 err := cr.UpdateContainerRecordComplete()
433 c.Check(api.Content["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
434 c.Check(api.Content["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
435 c.Check(api.Content["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
438 func (s *TestSuite) TestUpdateContainerRecordCancelled(c *C) {
439 api := &ArvTestClient{}
440 kc := &KeepTestClient{}
441 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
443 cr.finalState = "Cancelled"
445 err := cr.UpdateContainerRecordComplete()
448 c.Check(api.Content["container"].(arvadosclient.Dict)["log"], IsNil)
449 c.Check(api.Content["container"].(arvadosclient.Dict)["exit_code"], IsNil)
450 c.Check(api.Content["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
453 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
454 // dress rehersal of the Run() function, starting from a JSON container record.
455 func FullRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner) {
456 rec := ContainerRecord{}
457 err := json.NewDecoder(strings.NewReader(record)).Decode(&rec)
460 docker := NewTestDockerClient()
462 docker.RemoveImage(hwImageId, true)
464 api = &ArvTestClient{ContainerRecord: rec}
465 cr = NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
469 c.Check(api.WasSetRunning, Equals, true)
471 c.Check(api.Content["container"].(arvadosclient.Dict)["log"], NotNil)
474 for k, v := range api.Logs {
483 func (s *TestSuite) TestFullRunHello(c *C) {
484 api, _ := FullRunHelper(c, `{
485 "command": ["echo", "hello world"],
486 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
489 "mounts": {"/tmp": {"kind": "tmp"} },
490 "output_path": "/tmp",
492 "runtime_constraints": {}
493 }`, func(t *TestDockerClient) {
494 t.stdoutWriter.Write([]byte("hello world\n"))
495 t.stdoutWriter.Close()
496 t.stderrWriter.Close()
497 t.finish <- dockerclient.WaitResult{}
500 c.Check(api.Content["container"].(arvadosclient.Dict)["exit_code"], Equals, 0)
501 c.Check(api.Content["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
503 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
507 func (s *TestSuite) TestFullRunStderr(c *C) {
508 api, _ := FullRunHelper(c, `{
509 "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
510 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
513 "mounts": {"/tmp": {"kind": "tmp"} },
514 "output_path": "/tmp",
516 "runtime_constraints": {}
517 }`, func(t *TestDockerClient) {
518 t.stdoutWriter.Write([]byte("hello\n"))
519 t.stderrWriter.Write([]byte("world\n"))
520 t.stdoutWriter.Close()
521 t.stderrWriter.Close()
522 t.finish <- dockerclient.WaitResult{ExitCode: 1}
525 c.Check(api.Content["container"].(arvadosclient.Dict)["log"], NotNil)
526 c.Check(api.Content["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
527 c.Check(api.Content["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
529 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
530 c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
533 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
534 api, _ := FullRunHelper(c, `{
536 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
539 "mounts": {"/tmp": {"kind": "tmp"} },
540 "output_path": "/tmp",
542 "runtime_constraints": {}
543 }`, func(t *TestDockerClient) {
544 t.stdoutWriter.Write([]byte(t.cwd + "\n"))
545 t.stdoutWriter.Close()
546 t.stderrWriter.Close()
547 t.finish <- dockerclient.WaitResult{ExitCode: 0}
550 c.Check(api.Content["container"].(arvadosclient.Dict)["exit_code"], Equals, 0)
551 c.Check(api.Content["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
553 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
556 func (s *TestSuite) TestFullRunSetCwd(c *C) {
557 api, _ := FullRunHelper(c, `{
559 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
562 "mounts": {"/tmp": {"kind": "tmp"} },
563 "output_path": "/tmp",
565 "runtime_constraints": {}
566 }`, func(t *TestDockerClient) {
567 t.stdoutWriter.Write([]byte(t.cwd + "\n"))
568 t.stdoutWriter.Close()
569 t.stderrWriter.Close()
570 t.finish <- dockerclient.WaitResult{ExitCode: 0}
573 c.Check(api.Content["container"].(arvadosclient.Dict)["exit_code"], Equals, 0)
574 c.Check(api.Content["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
576 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
579 func (s *TestSuite) TestCancel(c *C) {
581 "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
582 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
585 "mounts": {"/tmp": {"kind": "tmp"} },
586 "output_path": "/tmp",
588 "runtime_constraints": {}
591 rec := ContainerRecord{}
592 err := json.NewDecoder(strings.NewReader(record)).Decode(&rec)
595 docker := NewTestDockerClient()
596 docker.fn = func(t *TestDockerClient) {
598 t.stdoutWriter.Write([]byte("foo\n"))
599 t.stdoutWriter.Close()
600 t.stderrWriter.Close()
601 t.finish <- dockerclient.WaitResult{ExitCode: 0}
603 docker.RemoveImage(hwImageId, true)
605 api := &ArvTestClient{ContainerRecord: rec}
606 cr := NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
609 for cr.ContainerID == "" {
610 time.Sleep(1 * time.Second)
612 cr.SigChan <- syscall.SIGINT
619 c.Check(api.Content["container"].(arvadosclient.Dict)["log"], NotNil)
622 for k, v := range api.Logs {
628 c.Check(api.Content["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
630 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "foo\n"), Equals, true)
634 func (s *TestSuite) TestFullRunSetEnv(c *C) {
635 api, _ := FullRunHelper(c, `{
636 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
637 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
639 "environment": {"FROBIZ": "bilbo"},
640 "mounts": {"/tmp": {"kind": "tmp"} },
641 "output_path": "/tmp",
643 "runtime_constraints": {}
644 }`, func(t *TestDockerClient) {
645 t.stdoutWriter.Write([]byte(t.env[0][7:] + "\n"))
646 t.stdoutWriter.Close()
647 t.stderrWriter.Close()
648 t.finish <- dockerclient.WaitResult{ExitCode: 0}
651 c.Check(api.Content["container"].(arvadosclient.Dict)["exit_code"], Equals, 0)
652 c.Check(api.Content["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
654 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)