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"
26 // Gocheck boilerplate
27 func TestCrunchExec(t *testing.T) {
31 type TestSuite struct{}
33 // Gocheck boilerplate
34 var _ = Suite(&TestSuite{})
36 type ArvTestClient struct {
39 Content arvadosclient.Dict
41 Logs map[string]*bytes.Buffer
45 type KeepTestClient struct {
50 var hwManifest = ". 82ab40c24fc8df01798e57ba66795bb1+841216+Aa124ac75e5168396c73c0a18eda641a4f41791c0@569fa8c3 0:841216:9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7.tar\n"
51 var hwPDH = "a45557269dcb65a6b78f9ac061c0850b+120"
52 var hwImageId = "9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7"
54 var otherManifest = ". 68a84f561b1d1708c6baff5e019a9ab3+46+Ae5d0af96944a3690becb1decdf60cc1c937f556d@5693216f 0:46:md5sum.txt\n"
55 var otherPDH = "a3e8f74c6f101eae01fa08bfb4e49b3a+54"
57 type TestDockerClient struct {
59 logReader io.ReadCloser
60 logWriter io.WriteCloser
61 fn func(t *TestDockerClient)
62 finish chan dockerclient.WaitResult
68 func NewTestDockerClient() *TestDockerClient {
69 t := &TestDockerClient{}
70 t.logReader, t.logWriter = io.Pipe()
71 t.finish = make(chan dockerclient.WaitResult)
72 t.stop = make(chan bool)
77 func (t *TestDockerClient) StopContainer(id string, timeout int) error {
82 func (t *TestDockerClient) InspectImage(id string) (*dockerclient.ImageInfo, error) {
83 if t.imageLoaded == id {
84 return &dockerclient.ImageInfo{}, nil
86 return nil, errors.New("")
90 func (t *TestDockerClient) LoadImage(reader io.Reader) error {
91 _, err := io.Copy(ioutil.Discard, reader)
95 t.imageLoaded = hwImageId
100 func (t *TestDockerClient) CreateContainer(config *dockerclient.ContainerConfig, name string, authConfig *dockerclient.AuthConfig) (string, error) {
101 if config.WorkingDir != "" {
102 t.cwd = config.WorkingDir
108 func (t *TestDockerClient) StartContainer(id string, config *dockerclient.HostConfig) error {
113 return errors.New("Invalid container id")
117 func (t *TestDockerClient) AttachContainer(id string, options *dockerclient.AttachOptions) (io.ReadCloser, error) {
118 return t.logReader, nil
121 func (t *TestDockerClient) Wait(id string) <-chan dockerclient.WaitResult {
125 func (*TestDockerClient) RemoveImage(name string, force bool) ([]*dockerclient.ImageDelete, error) {
129 func (this *ArvTestClient) Create(resourceType string,
130 parameters arvadosclient.Dict,
131 output interface{}) error {
134 this.Content = parameters
136 if resourceType == "logs" {
137 et := parameters["log"].(arvadosclient.Dict)["event_type"].(string)
138 if this.Logs == nil {
139 this.Logs = make(map[string]*bytes.Buffer)
141 if this.Logs[et] == nil {
142 this.Logs[et] = &bytes.Buffer{}
144 this.Logs[et].Write([]byte(parameters["log"].(arvadosclient.Dict)["properties"].(map[string]string)["text"]))
147 if resourceType == "collections" && output != nil {
148 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
149 outmap := output.(*CollectionRecord)
150 outmap.PortableDataHash = fmt.Sprintf("%x+%d", md5.Sum([]byte(mt)), len(mt))
156 func (this *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
157 if resourceType == "collections" {
159 output.(*CollectionRecord).ManifestText = hwManifest
160 } else if uuid == otherPDH {
161 output.(*CollectionRecord).ManifestText = otherManifest
164 if resourceType == "containers" {
165 (*output.(*ContainerRecord)) = this.ContainerRecord
170 func (this *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
172 this.Content = parameters
173 if resourceType == "containers" {
174 if parameters["container"].(arvadosclient.Dict)["state"] == "Running" {
175 this.WasSetRunning = true
182 func (this *KeepTestClient) PutHB(hash string, buf []byte) (string, int, error) {
184 return fmt.Sprintf("%s+%d", hash, len(buf)), len(buf), nil
187 type FileWrapper struct {
192 func (this FileWrapper) Len() uint64 {
196 func (this *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.ReadCloserWithLen, error) {
197 if filename == hwImageId+".tar" {
198 rdr := ioutil.NopCloser(&bytes.Buffer{})
200 return FileWrapper{rdr, 1321984}, nil
205 func (s *TestSuite) TestLoadImage(c *C) {
206 kc := &KeepTestClient{}
207 docker := NewTestDockerClient()
208 cr := NewContainerRunner(&ArvTestClient{}, kc, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
210 _, err := cr.Docker.RemoveImage(hwImageId, true)
212 _, err = cr.Docker.InspectImage(hwImageId)
215 cr.ContainerRecord.ContainerImage = hwPDH
217 // (1) Test loading image from keep
218 c.Check(kc.Called, Equals, false)
219 c.Check(cr.ContainerConfig.Image, Equals, "")
225 cr.Docker.RemoveImage(hwImageId, true)
228 c.Check(kc.Called, Equals, true)
229 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
231 _, err = cr.Docker.InspectImage(hwImageId)
234 // (2) Test using image that's already loaded
236 cr.ContainerConfig.Image = ""
240 c.Check(kc.Called, Equals, false)
241 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
245 type ArvErrorTestClient struct{}
246 type KeepErrorTestClient struct{}
247 type KeepReadErrorTestClient struct{}
249 func (this ArvErrorTestClient) Create(resourceType string,
250 parameters arvadosclient.Dict,
251 output interface{}) error {
255 func (this ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
256 return errors.New("ArvError")
259 func (this ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
263 func (this KeepErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
264 return "", 0, errors.New("KeepError")
267 func (this KeepErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.ReadCloserWithLen, error) {
268 return nil, errors.New("KeepError")
271 func (this KeepReadErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
275 type ErrorReader struct{}
277 func (this ErrorReader) Read(p []byte) (n int, err error) {
278 return 0, errors.New("ErrorReader")
281 func (this ErrorReader) Close() error {
285 func (this ErrorReader) Len() uint64 {
289 func (this KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.ReadCloserWithLen, error) {
290 return ErrorReader{}, nil
293 func (s *TestSuite) TestLoadImageArvError(c *C) {
295 cr := NewContainerRunner(ArvErrorTestClient{}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
296 cr.ContainerRecord.ContainerImage = hwPDH
298 err := cr.LoadImage()
299 c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
302 func (s *TestSuite) TestLoadImageKeepError(c *C) {
304 docker := NewTestDockerClient()
305 cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
306 cr.ContainerRecord.ContainerImage = hwPDH
308 err := cr.LoadImage()
309 c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
312 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
313 // (3) Collection doesn't contain image
314 cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
315 cr.ContainerRecord.ContainerImage = otherPDH
317 err := cr.LoadImage()
318 c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
321 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
322 // (4) Collection doesn't contain image
323 docker := NewTestDockerClient()
324 cr := NewContainerRunner(&ArvTestClient{}, KeepReadErrorTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
325 cr.ContainerRecord.ContainerImage = hwPDH
327 err := cr.LoadImage()
331 type ClosableBuffer struct {
335 type TestLogs struct {
336 Stdout ClosableBuffer
337 Stderr ClosableBuffer
340 func (this *ClosableBuffer) Close() error {
344 func (this *TestLogs) NewTestLoggingWriter(logstr string) io.WriteCloser {
345 if logstr == "stdout" {
348 if logstr == "stderr" {
354 func dockerLog(fd byte, msg string) []byte {
356 header := make([]byte, 8+len(by))
358 header[7] = byte(len(by))
363 func (s *TestSuite) TestRunContainer(c *C) {
364 docker := NewTestDockerClient()
365 docker.fn = func(t *TestDockerClient) {
366 t.logWriter.Write(dockerLog(1, "Hello world\n"))
368 t.finish <- dockerclient.WaitResult{}
370 cr := NewContainerRunner(&ArvTestClient{}, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
373 cr.NewLogWriter = logs.NewTestLoggingWriter
374 cr.ContainerRecord.ContainerImage = hwPDH
375 cr.ContainerRecord.Command = []string{"./hw"}
376 err := cr.LoadImage()
379 err = cr.StartContainer()
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")
466 am := &ArvMountCmdLine{}
467 cr.RunArvMount = am.ArvMountTest
471 c.Check(api.WasSetRunning, Equals, true)
473 c.Check(api.Content["container"].(arvadosclient.Dict)["log"], NotNil)
476 for k, v := range api.Logs {
485 func (s *TestSuite) TestFullRunHello(c *C) {
486 api, _ := FullRunHelper(c, `{
487 "command": ["echo", "hello world"],
488 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
491 "mounts": {"/tmp": {"kind": "tmp"} },
492 "output_path": "/tmp",
494 "runtime_constraints": {}
495 }`, func(t *TestDockerClient) {
496 t.logWriter.Write(dockerLog(1, "hello world\n"))
498 t.finish <- dockerclient.WaitResult{}
501 c.Check(api.Content["container"].(arvadosclient.Dict)["exit_code"], Equals, 0)
502 c.Check(api.Content["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
504 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
508 func (s *TestSuite) TestFullRunStderr(c *C) {
509 api, _ := FullRunHelper(c, `{
510 "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
511 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
514 "mounts": {"/tmp": {"kind": "tmp"} },
515 "output_path": "/tmp",
517 "runtime_constraints": {}
518 }`, func(t *TestDockerClient) {
519 t.logWriter.Write(dockerLog(1, "hello\n"))
520 t.logWriter.Write(dockerLog(2, "world\n"))
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.logWriter.Write(dockerLog(1, t.cwd+"\n"))
546 t.finish <- dockerclient.WaitResult{ExitCode: 0}
549 c.Check(api.Content["container"].(arvadosclient.Dict)["exit_code"], Equals, 0)
550 c.Check(api.Content["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
552 log.Print(api.Logs["stdout"].String())
554 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
557 func (s *TestSuite) TestFullRunSetCwd(c *C) {
558 api, _ := FullRunHelper(c, `{
560 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
563 "mounts": {"/tmp": {"kind": "tmp"} },
564 "output_path": "/tmp",
566 "runtime_constraints": {}
567 }`, func(t *TestDockerClient) {
568 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
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.logWriter.Write(dockerLog(1, "foo\n"))
600 t.finish <- dockerclient.WaitResult{ExitCode: 0}
602 docker.RemoveImage(hwImageId, true)
604 api := &ArvTestClient{ContainerRecord: rec}
605 cr := NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
606 am := &ArvMountCmdLine{}
607 cr.RunArvMount = am.ArvMountTest
610 for cr.ContainerID == "" {
611 time.Sleep(1 * time.Second)
613 cr.SigChan <- syscall.SIGINT
620 c.Check(api.Content["container"].(arvadosclient.Dict)["log"], NotNil)
623 for k, v := range api.Logs {
629 c.Check(api.Content["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
631 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "foo\n"), Equals, true)
635 func (s *TestSuite) TestFullRunSetEnv(c *C) {
636 api, _ := FullRunHelper(c, `{
637 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
638 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
640 "environment": {"FROBIZ": "bilbo"},
641 "mounts": {"/tmp": {"kind": "tmp"} },
642 "output_path": "/tmp",
644 "runtime_constraints": {}
645 }`, func(t *TestDockerClient) {
646 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
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)
657 type ArvMountCmdLine struct {
661 func (am *ArvMountCmdLine) ArvMountTest(c []string) (*exec.Cmd, error) {
666 func (s *TestSuite) TestSetupMounts(c *C) {
667 api := &ArvTestClient{}
668 kc := &KeepTestClient{}
669 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
670 am := &ArvMountCmdLine{}
671 cr.RunArvMount = am.ArvMountTest
674 cr.MkTempDir = func(string, string) (string, error) {
676 d := fmt.Sprintf("/tmp/mktmpdir%d", i)
677 os.Mkdir(d, os.ModePerm)
682 cr.ContainerRecord.Mounts = make(map[string]Mount)
683 cr.ContainerRecord.Mounts["/tmp"] = Mount{Kind: "tmp"}
684 cr.OutputPath = "/tmp"
686 err := cr.SetupMounts()
688 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-by-pdh", "by_id", "/tmp/mktmpdir1"})
689 c.Check(cr.Binds, DeepEquals, []string{"/tmp/mktmpdir2:/tmp"})
695 cr.ContainerRecord.Mounts = make(map[string]Mount)
696 cr.ContainerRecord.Mounts["/keeptmp"] = Mount{Kind: "collection", Writable: true}
697 cr.OutputPath = "/keeptmp"
699 os.MkdirAll("/tmp/mktmpdir1/tmp0", os.ModePerm)
701 err := cr.SetupMounts()
703 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", "/tmp/mktmpdir1"})
704 c.Check(cr.Binds, DeepEquals, []string{"/tmp/mktmpdir1/tmp0:/keeptmp"})
710 cr.ContainerRecord.Mounts = make(map[string]Mount)
711 cr.ContainerRecord.Mounts["/keepinp"] = Mount{Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"}
712 cr.ContainerRecord.Mounts["/keepout"] = Mount{Kind: "collection", Writable: true}
713 cr.OutputPath = "/keepout"
715 os.MkdirAll("/tmp/mktmpdir1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
716 os.MkdirAll("/tmp/mktmpdir1/tmp0", os.ModePerm)
718 err := cr.SetupMounts()
720 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", "/tmp/mktmpdir1"})
721 var ss sort.StringSlice = cr.Binds
723 c.Check(cr.Binds, DeepEquals, []string{"/tmp/mktmpdir1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
724 "/tmp/mktmpdir1/tmp0:/keepout"})