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"
28 // Gocheck boilerplate
29 func TestCrunchExec(t *testing.T) {
33 type TestSuite struct{}
35 // Gocheck boilerplate
36 var _ = Suite(&TestSuite{})
38 type ArvTestClient struct {
41 Content []arvadosclient.Dict
43 Logs map[string]*bytes.Buffer
48 type KeepTestClient struct {
53 var hwManifest = ". 82ab40c24fc8df01798e57ba66795bb1+841216+Aa124ac75e5168396c73c0a18eda641a4f41791c0@569fa8c3 0:841216:9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7.tar\n"
54 var hwPDH = "a45557269dcb65a6b78f9ac061c0850b+120"
55 var hwImageId = "9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7"
57 var otherManifest = ". 68a84f561b1d1708c6baff5e019a9ab3+46+Ae5d0af96944a3690becb1decdf60cc1c937f556d@5693216f 0:46:md5sum.txt\n"
58 var otherPDH = "a3e8f74c6f101eae01fa08bfb4e49b3a+54"
60 var fakeAuthUUID = "zzzzz-gj3su-55pqoyepgi2glem"
61 var fakeAuthToken = "a3ltuwzqcu2u4sc0q7yhpc2w7s00fdcqecg5d6e0u3pfohmbjt"
63 type TestDockerClient struct {
65 logReader io.ReadCloser
66 logWriter io.WriteCloser
67 fn func(t *TestDockerClient)
68 finish chan dockerclient.WaitResult
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)
84 func (t *TestDockerClient) StopContainer(id string, timeout int) error {
89 func (t *TestDockerClient) InspectImage(id string) (*dockerclient.ImageInfo, error) {
90 if t.imageLoaded == id {
91 return &dockerclient.ImageInfo{}, nil
93 return nil, errors.New("")
97 func (t *TestDockerClient) LoadImage(reader io.Reader) error {
98 _, err := io.Copy(ioutil.Discard, reader)
102 t.imageLoaded = hwImageId
107 func (t *TestDockerClient) CreateContainer(config *dockerclient.ContainerConfig, name string, authConfig *dockerclient.AuthConfig) (string, error) {
108 if config.WorkingDir != "" {
109 t.cwd = config.WorkingDir
115 func (t *TestDockerClient) StartContainer(id string, config *dockerclient.HostConfig) error {
120 return errors.New("Invalid container id")
124 func (t *TestDockerClient) AttachContainer(id string, options *dockerclient.AttachOptions) (io.ReadCloser, error) {
125 return t.logReader, nil
128 func (t *TestDockerClient) Wait(id string) <-chan dockerclient.WaitResult {
132 func (*TestDockerClient) RemoveImage(name string, force bool) ([]*dockerclient.ImageDelete, error) {
136 func (client *ArvTestClient) Create(resourceType string,
137 parameters arvadosclient.Dict,
138 output interface{}) error {
141 defer client.Mutex.Unlock()
144 client.Content = append(client.Content, parameters)
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)
151 if client.Logs[et] == nil {
152 client.Logs[et] = &bytes.Buffer{}
154 client.Logs[et].Write([]byte(parameters["log"].(arvadosclient.Dict)["properties"].(map[string]string)["text"]))
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))
166 func (client *ArvTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
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+`"
175 return fmt.Errorf("Not found")
179 func (client *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
180 if resourceType == "collections" {
182 output.(*arvados.Collection).ManifestText = hwManifest
183 } else if uuid == otherPDH {
184 output.(*arvados.Collection).ManifestText = otherManifest
187 if resourceType == "containers" {
188 (*output.(*arvados.Container)) = client.Container
193 func (client *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
195 defer client.Mutex.Unlock()
197 client.Content = append(client.Content, parameters)
198 if resourceType == "containers" {
199 if parameters["container"].(arvadosclient.Dict)["state"] == "Running" {
200 client.WasSetRunning = true
206 var discoveryMap = map[string]interface{}{"defaultTrashLifetime": float64(1209600)}
208 func (client *ArvTestClient) Discovery(key string) (interface{}, error) {
209 return discoveryMap[key], nil
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 {
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 {
234 func (client *KeepTestClient) PutHB(hash string, buf []byte) (string, int, error) {
236 return fmt.Sprintf("%s+%d", hash, len(buf)), len(buf), nil
239 type FileWrapper struct {
244 func (fw FileWrapper) Len() uint64 {
248 func (client *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.ReadCloserWithLen, error) {
249 if filename == hwImageId+".tar" {
250 rdr := ioutil.NopCloser(&bytes.Buffer{})
252 return FileWrapper{rdr, 1321984}, nil
257 func (s *TestSuite) TestLoadImage(c *C) {
258 kc := &KeepTestClient{}
259 docker := NewTestDockerClient()
260 cr := NewContainerRunner(&ArvTestClient{}, kc, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
262 _, err := cr.Docker.RemoveImage(hwImageId, true)
264 _, err = cr.Docker.InspectImage(hwImageId)
267 cr.Container.ContainerImage = hwPDH
269 // (1) Test loading image from keep
270 c.Check(kc.Called, Equals, false)
271 c.Check(cr.ContainerConfig.Image, Equals, "")
277 cr.Docker.RemoveImage(hwImageId, true)
280 c.Check(kc.Called, Equals, true)
281 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
283 _, err = cr.Docker.InspectImage(hwImageId)
286 // (2) Test using image that's already loaded
288 cr.ContainerConfig.Image = ""
292 c.Check(kc.Called, Equals, false)
293 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
297 type ArvErrorTestClient struct{}
299 func (ArvErrorTestClient) Create(resourceType string,
300 parameters arvadosclient.Dict,
301 output interface{}) error {
305 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
306 return errors.New("ArvError")
309 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
310 return errors.New("ArvError")
313 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
317 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
318 return discoveryMap[key], nil
321 type KeepErrorTestClient struct{}
323 func (KeepErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
324 return "", 0, errors.New("KeepError")
327 func (KeepErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.ReadCloserWithLen, error) {
328 return nil, errors.New("KeepError")
331 type KeepReadErrorTestClient struct{}
333 func (KeepReadErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
337 type ErrorReader struct{}
339 func (ErrorReader) Read(p []byte) (n int, err error) {
340 return 0, errors.New("ErrorReader")
343 func (ErrorReader) Close() error {
347 func (ErrorReader) Len() uint64 {
351 func (KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.ReadCloserWithLen, error) {
352 return ErrorReader{}, nil
355 func (s *TestSuite) TestLoadImageArvError(c *C) {
357 cr := NewContainerRunner(ArvErrorTestClient{}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
358 cr.Container.ContainerImage = hwPDH
360 err := cr.LoadImage()
361 c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
364 func (s *TestSuite) TestLoadImageKeepError(c *C) {
366 docker := NewTestDockerClient()
367 cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
368 cr.Container.ContainerImage = hwPDH
370 err := cr.LoadImage()
371 c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
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
379 err := cr.LoadImage()
380 c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
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
389 err := cr.LoadImage()
393 type ClosableBuffer struct {
397 func (*ClosableBuffer) Close() error {
401 type TestLogs struct {
402 Stdout ClosableBuffer
403 Stderr ClosableBuffer
406 func (tl *TestLogs) NewTestLoggingWriter(logstr string) io.WriteCloser {
407 if logstr == "stdout" {
410 if logstr == "stderr" {
416 func dockerLog(fd byte, msg string) []byte {
418 header := make([]byte, 8+len(by))
420 header[7] = byte(len(by))
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"))
430 t.finish <- dockerclient.WaitResult{}
432 cr := NewContainerRunner(&ArvTestClient{}, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
435 cr.NewLogWriter = logs.NewTestLoggingWriter
436 cr.Container.ContainerImage = hwPDH
437 cr.Container.Command = []string{"./hw"}
438 err := cr.LoadImage()
441 err = cr.CreateContainer()
444 err = cr.StartContainer()
447 err = cr.WaitFinish()
450 c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
451 c.Check(logs.Stderr.String(), Equals, "")
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
460 cr.CrunchLog.Print("Hello world!")
461 cr.CrunchLog.Print("Goodbye")
462 cr.finalState = "Complete"
464 err := cr.CommitLogs()
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")
473 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
474 api := &ArvTestClient{}
475 kc := &KeepTestClient{}
476 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
478 err := cr.UpdateContainerRunning()
481 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
484 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
485 api := &ArvTestClient{}
486 kc := &KeepTestClient{}
487 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
489 cr.LogsPDH = new(string)
490 *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
492 cr.ExitCode = new(int)
494 cr.finalState = "Complete"
496 err := cr.UpdateContainerFinal()
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")
504 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
505 api := &ArvTestClient{}
506 kc := &KeepTestClient{}
507 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
509 cr.finalState = "Cancelled"
511 err := cr.UpdateContainerFinal()
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")
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)
526 docker := NewTestDockerClient()
528 docker.RemoveImage(hwImageId, true)
530 api = &ArvTestClient{Container: rec}
532 cr = NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
533 cr.statInterval = 100 * time.Millisecond
534 am := &ArvMountCmdLine{}
535 cr.RunArvMount = am.ArvMountTest
539 c.Check(api.WasSetRunning, Equals, true)
541 c.Check(api.Content[api.Calls-1]["container"].(arvadosclient.Dict)["log"], NotNil)
544 for k, v := range api.Logs {
553 func (s *TestSuite) TestFullRunHello(c *C) {
554 api, _ := FullRunHelper(c, `{
555 "command": ["echo", "hello world"],
556 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
559 "mounts": {"/tmp": {"kind": "tmp"} },
560 "output_path": "/tmp",
562 "runtime_constraints": {}
563 }`, func(t *TestDockerClient) {
564 t.logWriter.Write(dockerLog(1, "hello world\n"))
566 t.finish <- dockerclient.WaitResult{}
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)
575 func (s *TestSuite) TestCrunchstat(c *C) {
576 api, _ := FullRunHelper(c, `{
577 "command": ["sleep", "1"],
578 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
581 "mounts": {"/tmp": {"kind": "tmp"} },
582 "output_path": "/tmp",
584 "runtime_constraints": {}
585 }`, func(t *TestDockerClient) {
586 time.Sleep(time.Second)
588 t.finish <- dockerclient.WaitResult{}
591 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
592 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
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
599 c.Assert(api.Logs["crunchstat"], NotNil)
600 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
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`)
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",
614 "mounts": {"/tmp": {"kind": "tmp"} },
615 "output_path": "/tmp",
617 "runtime_constraints": {}
618 }`, func(t *TestDockerClient) {
619 t.logWriter.Write(dockerLog(1, "hello\n"))
620 t.logWriter.Write(dockerLog(2, "world\n"))
622 t.finish <- dockerclient.WaitResult{ExitCode: 1}
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)
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)
634 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
635 api, _ := FullRunHelper(c, `{
637 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
640 "mounts": {"/tmp": {"kind": "tmp"} },
641 "output_path": "/tmp",
643 "runtime_constraints": {}
644 }`, func(t *TestDockerClient) {
645 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
647 t.finish <- dockerclient.WaitResult{ExitCode: 0}
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)
656 func (s *TestSuite) TestFullRunSetCwd(c *C) {
657 api, _ := FullRunHelper(c, `{
659 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
662 "mounts": {"/tmp": {"kind": "tmp"} },
663 "output_path": "/tmp",
665 "runtime_constraints": {}
666 }`, func(t *TestDockerClient) {
667 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
669 t.finish <- dockerclient.WaitResult{ExitCode: 0}
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)
677 func (s *TestSuite) TestCancel(c *C) {
679 "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
680 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
683 "mounts": {"/tmp": {"kind": "tmp"} },
684 "output_path": "/tmp",
686 "runtime_constraints": {}
689 rec := arvados.Container{}
690 err := json.Unmarshal([]byte(record), &rec)
693 docker := NewTestDockerClient()
694 docker.fn = func(t *TestDockerClient) {
696 t.logWriter.Write(dockerLog(1, "foo\n"))
698 t.finish <- dockerclient.WaitResult{ExitCode: 0}
700 docker.RemoveImage(hwImageId, true)
702 api := &ArvTestClient{Container: rec}
703 cr := NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
704 am := &ArvMountCmdLine{}
705 cr.RunArvMount = am.ArvMountTest
708 for cr.ContainerID == "" {
709 time.Sleep(time.Millisecond)
711 cr.SigChan <- syscall.SIGINT
718 for k, v := range api.Logs {
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)
730 func (s *TestSuite) TestFullRunSetEnv(c *C) {
731 api, _ := FullRunHelper(c, `{
732 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
733 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
735 "environment": {"FROBIZ": "bilbo"},
736 "mounts": {"/tmp": {"kind": "tmp"} },
737 "output_path": "/tmp",
739 "runtime_constraints": {}
740 }`, func(t *TestDockerClient) {
741 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
743 t.finish <- dockerclient.WaitResult{ExitCode: 0}
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)
751 type ArvMountCmdLine struct {
756 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
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
769 realTemp, err := ioutil.TempDir("", "crunchrun_test-")
771 defer os.RemoveAll(realTemp)
774 cr.MkTempDir = func(_ string, prefix string) (string, error) {
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
785 checkEmpty := func() {
786 filepath.Walk(realTemp, func(path string, _ os.FileInfo, err error) error {
787 c.Check(path, Equals, realTemp)
795 cr.Container.Mounts = make(map[string]arvados.Mount)
796 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
797 cr.OutputPath = "/tmp"
799 err := cr.SetupMounts()
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"})
809 cr.Container.Mounts = map[string]arvados.Mount{
810 "/keeptmp": {Kind: "collection", Writable: true},
812 cr.OutputPath = "/keeptmp"
814 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
816 err := cr.SetupMounts()
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"})
826 cr.Container.Mounts = map[string]arvados.Mount{
827 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
828 "/keepout": {Kind: "collection", Writable: true},
830 cr.OutputPath = "/keepout"
832 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
833 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
835 err := cr.SetupMounts()
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"})
845 for _, test := range []struct {
849 {in: "foo", out: `"foo"`},
850 {in: nil, out: `null`},
851 {in: map[string]int{"foo": 123}, out: `{"foo":123}`},
854 cr.Container.Mounts = map[string]arvados.Mount{
855 "/mnt/test.json": {Kind: "json", Content: test.in},
857 err := cr.SetupMounts()
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")
863 c.Check(content, DeepEquals, []byte(test.out))
869 func (s *TestSuite) TestStdout(c *C) {
871 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
872 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
874 "environment": {"FROBIZ": "bilbo"},
875 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
876 "output_path": "/tmp",
878 "runtime_constraints": {}
881 api, _ := FullRunHelper(c, helperRecord, func(t *TestDockerClient) {
882 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
884 t.finish <- dockerclient.WaitResult{ExitCode: 0}
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)
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)
898 docker := NewTestDockerClient()
900 docker.RemoveImage(hwImageId, true)
902 api = &ArvTestClient{Container: rec}
903 cr = NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
904 am := &ArvMountCmdLine{}
905 cr.RunArvMount = am.ArvMountTest
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) {})
918 c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
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) {})
928 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'tmp' for stdout"), Equals, true)
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) {})
938 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'collection' for stdout"), Equals, true)
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",
949 "mounts": {"/tmp": {"kind": "tmp"} },
950 "output_path": "/tmp",
952 "runtime_constraints": {"API": true}
953 }`, func(t *TestDockerClient) {
954 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
956 t.finish <- dockerclient.WaitResult{ExitCode: 0}
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)
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",
973 "mounts": {"/tmp": {"kind": "tmp"} },
974 "output_path": "/tmp",
976 "runtime_constraints": {"API": true}
977 }`, func(t *TestDockerClient) {
978 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
980 t.finish <- dockerclient.WaitResult{ExitCode: 0}
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)