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 normalizedManifestWithSubdirs = ". 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 0:9:file1_in_main.txt 9:18:file2_in_main.txt 27:5649:zzzzz-8i9sb-bcdefghijkdhvnk.log.txt\n./subdir1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt\n./subdir1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt\n"
61 var normalizedWithSubdirsPDH = "a0def87f80dd594d4675809e83bd4f15+367"
63 var fakeAuthUUID = "zzzzz-gj3su-55pqoyepgi2glem"
64 var fakeAuthToken = "a3ltuwzqcu2u4sc0q7yhpc2w7s00fdcqecg5d6e0u3pfohmbjt"
66 type TestDockerClient struct {
68 logReader io.ReadCloser
69 logWriter io.WriteCloser
70 fn func(t *TestDockerClient)
71 finish chan dockerclient.WaitResult
78 func NewTestDockerClient() *TestDockerClient {
79 t := &TestDockerClient{}
80 t.logReader, t.logWriter = io.Pipe()
81 t.finish = make(chan dockerclient.WaitResult)
82 t.stop = make(chan bool)
87 func (t *TestDockerClient) StopContainer(id string, timeout int) error {
92 func (t *TestDockerClient) InspectImage(id string) (*dockerclient.ImageInfo, error) {
93 if t.imageLoaded == id {
94 return &dockerclient.ImageInfo{}, nil
96 return nil, errors.New("")
100 func (t *TestDockerClient) LoadImage(reader io.Reader) error {
101 _, err := io.Copy(ioutil.Discard, reader)
105 t.imageLoaded = hwImageId
110 func (t *TestDockerClient) CreateContainer(config *dockerclient.ContainerConfig, name string, authConfig *dockerclient.AuthConfig) (string, error) {
111 if config.WorkingDir != "" {
112 t.cwd = config.WorkingDir
118 func (t *TestDockerClient) StartContainer(id string, config *dockerclient.HostConfig) error {
123 return errors.New("Invalid container id")
127 func (t *TestDockerClient) AttachContainer(id string, options *dockerclient.AttachOptions) (io.ReadCloser, error) {
128 return t.logReader, nil
131 func (t *TestDockerClient) Wait(id string) <-chan dockerclient.WaitResult {
135 func (*TestDockerClient) RemoveImage(name string, force bool) ([]*dockerclient.ImageDelete, error) {
139 func (client *ArvTestClient) Create(resourceType string,
140 parameters arvadosclient.Dict,
141 output interface{}) error {
144 defer client.Mutex.Unlock()
147 client.Content = append(client.Content, parameters)
149 if resourceType == "logs" {
150 et := parameters["log"].(arvadosclient.Dict)["event_type"].(string)
151 if client.Logs == nil {
152 client.Logs = make(map[string]*bytes.Buffer)
154 if client.Logs[et] == nil {
155 client.Logs[et] = &bytes.Buffer{}
157 client.Logs[et].Write([]byte(parameters["log"].(arvadosclient.Dict)["properties"].(map[string]string)["text"]))
160 if resourceType == "collections" && output != nil {
161 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
162 outmap := output.(*arvados.Collection)
163 outmap.PortableDataHash = fmt.Sprintf("%x+%d", md5.Sum([]byte(mt)), len(mt))
169 func (client *ArvTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
171 case method == "GET" && resourceType == "containers" && action == "auth":
172 return json.Unmarshal([]byte(`{
173 "kind": "arvados#api_client_authorization",
174 "uuid": "`+fakeAuthUUID+`",
175 "api_token": "`+fakeAuthToken+`"
178 return fmt.Errorf("Not found")
182 func (client *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
183 if resourceType == "collections" {
185 output.(*arvados.Collection).ManifestText = hwManifest
186 } else if uuid == otherPDH {
187 output.(*arvados.Collection).ManifestText = otherManifest
188 } else if uuid == normalizedWithSubdirsPDH {
189 output.(*arvados.Collection).ManifestText = normalizedManifestWithSubdirs
192 if resourceType == "containers" {
193 (*output.(*arvados.Container)) = client.Container
198 func (client *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
200 defer client.Mutex.Unlock()
202 client.Content = append(client.Content, parameters)
203 if resourceType == "containers" {
204 if parameters["container"].(arvadosclient.Dict)["state"] == "Running" {
205 client.WasSetRunning = true
211 var discoveryMap = map[string]interface{}{"defaultTrashLifetime": float64(1209600)}
213 func (client *ArvTestClient) Discovery(key string) (interface{}, error) {
214 return discoveryMap[key], nil
217 // CalledWith returns the parameters from the first API call whose
218 // parameters match jpath/string. E.g., CalledWith(c, "foo.bar",
219 // "baz") returns parameters with parameters["foo"]["bar"]=="baz". If
220 // no call matches, it returns nil.
221 func (client *ArvTestClient) CalledWith(jpath string, expect interface{}) arvadosclient.Dict {
223 for _, content := range client.Content {
224 var v interface{} = content
225 for _, k := range strings.Split(jpath, ".") {
226 if dict, ok := v.(arvadosclient.Dict); !ok {
239 func (client *KeepTestClient) PutHB(hash string, buf []byte) (string, int, error) {
241 return fmt.Sprintf("%s+%d", hash, len(buf)), len(buf), nil
244 type FileWrapper struct {
249 func (fw FileWrapper) Len() uint64 {
253 func (fw FileWrapper) Seek(int64, int) (int64, error) {
254 return 0, errors.New("not implemented")
257 func (client *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.Reader, error) {
258 if filename == hwImageId+".tar" {
259 rdr := ioutil.NopCloser(&bytes.Buffer{})
261 return FileWrapper{rdr, 1321984}, nil
266 func (s *TestSuite) TestLoadImage(c *C) {
267 kc := &KeepTestClient{}
268 docker := NewTestDockerClient()
269 cr := NewContainerRunner(&ArvTestClient{}, kc, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
271 _, err := cr.Docker.RemoveImage(hwImageId, true)
273 _, err = cr.Docker.InspectImage(hwImageId)
276 cr.Container.ContainerImage = hwPDH
278 // (1) Test loading image from keep
279 c.Check(kc.Called, Equals, false)
280 c.Check(cr.ContainerConfig.Image, Equals, "")
286 cr.Docker.RemoveImage(hwImageId, true)
289 c.Check(kc.Called, Equals, true)
290 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
292 _, err = cr.Docker.InspectImage(hwImageId)
295 // (2) Test using image that's already loaded
297 cr.ContainerConfig.Image = ""
301 c.Check(kc.Called, Equals, false)
302 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
306 type ArvErrorTestClient struct{}
308 func (ArvErrorTestClient) Create(resourceType string,
309 parameters arvadosclient.Dict,
310 output interface{}) error {
314 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
315 return errors.New("ArvError")
318 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
319 return errors.New("ArvError")
322 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
326 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
327 return discoveryMap[key], nil
330 type KeepErrorTestClient struct{}
332 func (KeepErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
333 return "", 0, errors.New("KeepError")
336 func (KeepErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.Reader, error) {
337 return nil, errors.New("KeepError")
340 type KeepReadErrorTestClient struct{}
342 func (KeepReadErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
346 type ErrorReader struct{}
348 func (ErrorReader) Read(p []byte) (n int, err error) {
349 return 0, errors.New("ErrorReader")
352 func (ErrorReader) Close() error {
356 func (ErrorReader) Len() uint64 {
360 func (ErrorReader) Seek(int64, int) (int64, error) {
361 return 0, errors.New("ErrorReader")
364 func (KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.Reader, error) {
365 return ErrorReader{}, nil
368 func (s *TestSuite) TestLoadImageArvError(c *C) {
370 cr := NewContainerRunner(ArvErrorTestClient{}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
371 cr.Container.ContainerImage = hwPDH
373 err := cr.LoadImage()
374 c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
377 func (s *TestSuite) TestLoadImageKeepError(c *C) {
379 docker := NewTestDockerClient()
380 cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
381 cr.Container.ContainerImage = hwPDH
383 err := cr.LoadImage()
384 c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
387 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
388 // (3) Collection doesn't contain image
389 cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
390 cr.Container.ContainerImage = otherPDH
392 err := cr.LoadImage()
393 c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
396 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
397 // (4) Collection doesn't contain image
398 docker := NewTestDockerClient()
399 cr := NewContainerRunner(&ArvTestClient{}, KeepReadErrorTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
400 cr.Container.ContainerImage = hwPDH
402 err := cr.LoadImage()
406 type ClosableBuffer struct {
410 func (*ClosableBuffer) Close() error {
414 type TestLogs struct {
415 Stdout ClosableBuffer
416 Stderr ClosableBuffer
419 func (tl *TestLogs) NewTestLoggingWriter(logstr string) io.WriteCloser {
420 if logstr == "stdout" {
423 if logstr == "stderr" {
429 func dockerLog(fd byte, msg string) []byte {
431 header := make([]byte, 8+len(by))
433 header[7] = byte(len(by))
438 func (s *TestSuite) TestRunContainer(c *C) {
439 docker := NewTestDockerClient()
440 docker.fn = func(t *TestDockerClient) {
441 t.logWriter.Write(dockerLog(1, "Hello world\n"))
443 t.finish <- dockerclient.WaitResult{}
445 cr := NewContainerRunner(&ArvTestClient{}, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
448 cr.NewLogWriter = logs.NewTestLoggingWriter
449 cr.Container.ContainerImage = hwPDH
450 cr.Container.Command = []string{"./hw"}
451 err := cr.LoadImage()
454 err = cr.CreateContainer()
457 err = cr.StartContainer()
460 err = cr.WaitFinish()
463 c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
464 c.Check(logs.Stderr.String(), Equals, "")
467 func (s *TestSuite) TestCommitLogs(c *C) {
468 api := &ArvTestClient{}
469 kc := &KeepTestClient{}
470 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
471 cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
473 cr.CrunchLog.Print("Hello world!")
474 cr.CrunchLog.Print("Goodbye")
475 cr.finalState = "Complete"
477 err := cr.CommitLogs()
480 c.Check(api.Calls, Equals, 2)
481 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
482 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
483 c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
486 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
487 api := &ArvTestClient{}
488 kc := &KeepTestClient{}
489 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
491 err := cr.UpdateContainerRunning()
494 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
497 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
498 api := &ArvTestClient{}
499 kc := &KeepTestClient{}
500 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
502 cr.LogsPDH = new(string)
503 *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
505 cr.ExitCode = new(int)
507 cr.finalState = "Complete"
509 err := cr.UpdateContainerFinal()
512 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
513 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
514 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
517 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
518 api := &ArvTestClient{}
519 kc := &KeepTestClient{}
520 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
522 cr.finalState = "Cancelled"
524 err := cr.UpdateContainerFinal()
527 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
528 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
529 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
532 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
533 // dress rehearsal of the Run() function, starting from a JSON container record.
534 func FullRunHelper(c *C, record string, extraMounts []string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner) {
535 rec := arvados.Container{}
536 err := json.Unmarshal([]byte(record), &rec)
539 docker := NewTestDockerClient()
541 docker.RemoveImage(hwImageId, true)
543 api = &ArvTestClient{Container: rec}
545 cr = NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
546 cr.statInterval = 100 * time.Millisecond
547 am := &ArvMountCmdLine{}
548 cr.RunArvMount = am.ArvMountTest
550 if extraMounts != nil && len(extraMounts) > 0 {
551 err := cr.SetupArvMountPoint("keep")
554 for _, m := range extraMounts {
555 os.MkdirAll(cr.ArvMountPoint+"/by_id/"+m, os.ModePerm)
561 c.Check(api.WasSetRunning, Equals, true)
563 c.Check(api.Content[api.Calls-1]["container"].(arvadosclient.Dict)["log"], NotNil)
566 for k, v := range api.Logs {
575 func (s *TestSuite) TestFullRunHello(c *C) {
576 api, _ := FullRunHelper(c, `{
577 "command": ["echo", "hello world"],
578 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
581 "mounts": {"/tmp": {"kind": "tmp"} },
582 "output_path": "/tmp",
584 "runtime_constraints": {}
585 }`, nil, func(t *TestDockerClient) {
586 t.logWriter.Write(dockerLog(1, "hello world\n"))
588 t.finish <- dockerclient.WaitResult{}
591 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
592 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
593 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
597 func (s *TestSuite) TestCrunchstat(c *C) {
598 api, _ := FullRunHelper(c, `{
599 "command": ["sleep", "1"],
600 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
603 "mounts": {"/tmp": {"kind": "tmp"} },
604 "output_path": "/tmp",
606 "runtime_constraints": {}
607 }`, nil, func(t *TestDockerClient) {
608 time.Sleep(time.Second)
610 t.finish <- dockerclient.WaitResult{}
613 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
614 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
616 // We didn't actually start a container, so crunchstat didn't
617 // find accounting files and therefore didn't log any stats.
618 // It should have logged a "can't find accounting files"
619 // message after one poll interval, though, so we can confirm
621 c.Assert(api.Logs["crunchstat"], NotNil)
622 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
624 // The "files never appeared" log assures us that we called
625 // (*crunchstat.Reporter)Stop(), and that we set it up with
626 // the correct container ID "abcde":
627 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files never appeared for abcde\n`)
630 func (s *TestSuite) TestFullRunStderr(c *C) {
631 api, _ := FullRunHelper(c, `{
632 "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
633 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
636 "mounts": {"/tmp": {"kind": "tmp"} },
637 "output_path": "/tmp",
639 "runtime_constraints": {}
640 }`, nil, func(t *TestDockerClient) {
641 t.logWriter.Write(dockerLog(1, "hello\n"))
642 t.logWriter.Write(dockerLog(2, "world\n"))
644 t.finish <- dockerclient.WaitResult{ExitCode: 1}
647 final := api.CalledWith("container.state", "Complete")
648 c.Assert(final, NotNil)
649 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
650 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
652 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
653 c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
656 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
657 api, _ := FullRunHelper(c, `{
659 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
662 "mounts": {"/tmp": {"kind": "tmp"} },
663 "output_path": "/tmp",
665 "runtime_constraints": {}
666 }`, nil, 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.Log(api.Logs["stdout"])
675 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
678 func (s *TestSuite) TestFullRunSetCwd(c *C) {
679 api, _ := FullRunHelper(c, `{
681 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
684 "mounts": {"/tmp": {"kind": "tmp"} },
685 "output_path": "/tmp",
687 "runtime_constraints": {}
688 }`, nil, func(t *TestDockerClient) {
689 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
691 t.finish <- dockerclient.WaitResult{ExitCode: 0}
694 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
695 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
696 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
699 func (s *TestSuite) TestCancel(c *C) {
701 "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
702 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
705 "mounts": {"/tmp": {"kind": "tmp"} },
706 "output_path": "/tmp",
708 "runtime_constraints": {}
711 rec := arvados.Container{}
712 err := json.Unmarshal([]byte(record), &rec)
715 docker := NewTestDockerClient()
716 docker.fn = func(t *TestDockerClient) {
718 t.logWriter.Write(dockerLog(1, "foo\n"))
720 t.finish <- dockerclient.WaitResult{ExitCode: 0}
722 docker.RemoveImage(hwImageId, true)
724 api := &ArvTestClient{Container: rec}
725 cr := NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
726 am := &ArvMountCmdLine{}
727 cr.RunArvMount = am.ArvMountTest
730 for cr.ContainerID == "" {
731 time.Sleep(time.Millisecond)
733 cr.SigChan <- syscall.SIGINT
740 for k, v := range api.Logs {
746 c.Check(api.CalledWith("container.log", nil), NotNil)
747 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
748 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "foo\n"), Equals, true)
752 func (s *TestSuite) TestFullRunSetEnv(c *C) {
753 api, _ := FullRunHelper(c, `{
754 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
755 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
757 "environment": {"FROBIZ": "bilbo"},
758 "mounts": {"/tmp": {"kind": "tmp"} },
759 "output_path": "/tmp",
761 "runtime_constraints": {}
762 }`, nil, func(t *TestDockerClient) {
763 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
765 t.finish <- dockerclient.WaitResult{ExitCode: 0}
768 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
769 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
770 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)
773 type ArvMountCmdLine struct {
778 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
784 func stubCert(temp string) string {
785 path := temp + "/ca-certificates.crt"
786 crt, _ := os.Create(path)
788 arvadosclient.CertFiles = []string{path}
792 func (s *TestSuite) TestSetupMounts(c *C) {
793 api := &ArvTestClient{}
794 kc := &KeepTestClient{}
795 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
796 am := &ArvMountCmdLine{}
797 cr.RunArvMount = am.ArvMountTest
799 realTemp, err := ioutil.TempDir("", "crunchrun_test1-")
801 certTemp, err := ioutil.TempDir("", "crunchrun_test2-")
803 stubCertPath := stubCert(certTemp)
805 defer os.RemoveAll(realTemp)
806 defer os.RemoveAll(certTemp)
809 cr.MkTempDir = func(_ string, prefix string) (string, error) {
811 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
812 err := os.Mkdir(d, os.ModePerm)
813 if err != nil && strings.Contains(err.Error(), ": file exists") {
814 // Test case must have pre-populated the tempdir
820 checkEmpty := func() {
821 filepath.Walk(realTemp, func(path string, _ os.FileInfo, err error) error {
822 c.Check(path, Equals, realTemp)
830 cr.ArvMountPoint = ""
831 cr.Container.Mounts = make(map[string]arvados.Mount)
832 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
833 cr.OutputPath = "/tmp"
835 err := cr.SetupMounts()
837 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
838 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/tmp"})
845 cr.ArvMountPoint = ""
846 cr.Container.Mounts = make(map[string]arvados.Mount)
847 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
848 cr.OutputPath = "/tmp"
851 cr.Container.RuntimeConstraints.API = &apiflag
853 err := cr.SetupMounts()
855 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
856 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/tmp", stubCertPath + ":/etc/arvados/ca-certificates.crt:ro"})
865 cr.ArvMountPoint = ""
866 cr.Container.Mounts = map[string]arvados.Mount{
867 "/keeptmp": {Kind: "collection", Writable: true},
869 cr.OutputPath = "/keeptmp"
871 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
873 err := cr.SetupMounts()
875 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
876 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/tmp0:/keeptmp"})
883 cr.ArvMountPoint = ""
884 cr.Container.Mounts = map[string]arvados.Mount{
885 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
886 "/keepout": {Kind: "collection", Writable: true},
888 cr.OutputPath = "/keepout"
890 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
891 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
893 err := cr.SetupMounts()
895 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
896 sort.StringSlice(cr.Binds).Sort()
897 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
898 realTemp + "/keep1/tmp0:/keepout"})
905 cr.ArvMountPoint = ""
906 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
907 cr.Container.Mounts = map[string]arvados.Mount{
908 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
909 "/keepout": {Kind: "collection", Writable: true},
911 cr.OutputPath = "/keepout"
913 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
914 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
916 err := cr.SetupMounts()
918 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
919 sort.StringSlice(cr.Binds).Sort()
920 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
921 realTemp + "/keep1/tmp0:/keepout"})
926 for _, test := range []struct {
930 {in: "foo", out: `"foo"`},
931 {in: nil, out: `null`},
932 {in: map[string]int{"foo": 123}, out: `{"foo":123}`},
935 cr.ArvMountPoint = ""
936 cr.Container.Mounts = map[string]arvados.Mount{
937 "/mnt/test.json": {Kind: "json", Content: test.in},
939 err := cr.SetupMounts()
941 sort.StringSlice(cr.Binds).Sort()
942 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2/mountdata.json:/mnt/test.json:ro"})
943 content, err := ioutil.ReadFile(realTemp + "/2/mountdata.json")
945 c.Check(content, DeepEquals, []byte(test.out))
950 // Read-only mount points are allowed underneath output_dir mount point
953 cr.ArvMountPoint = ""
954 cr.Container.Mounts = make(map[string]arvados.Mount)
955 cr.Container.Mounts = map[string]arvados.Mount{
956 "/tmp": {Kind: "tmp"},
957 "/tmp/foo": {Kind: "collection"},
959 cr.OutputPath = "/tmp"
961 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
963 err := cr.SetupMounts()
965 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
966 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/tmp", realTemp + "/keep1/tmp0:/tmp/foo:ro"})
971 // Writable mount points are not allowed underneath output_dir mount point
974 cr.ArvMountPoint = ""
975 cr.Container.Mounts = make(map[string]arvados.Mount)
976 cr.Container.Mounts = map[string]arvados.Mount{
977 "/tmp": {Kind: "tmp"},
978 "/tmp/foo": {Kind: "collection", Writable: true},
980 cr.OutputPath = "/tmp"
982 err := cr.SetupMounts()
984 c.Check(err, ErrorMatches, `Writable mount points are not permitted underneath the output_path.*`)
989 // Only mount points of kind 'collection' are allowed underneath output_dir mount point
992 cr.ArvMountPoint = ""
993 cr.Container.Mounts = make(map[string]arvados.Mount)
994 cr.Container.Mounts = map[string]arvados.Mount{
995 "/tmp": {Kind: "tmp"},
996 "/tmp/foo": {Kind: "json"},
998 cr.OutputPath = "/tmp"
1000 err := cr.SetupMounts()
1001 c.Check(err, NotNil)
1002 c.Check(err, ErrorMatches, `Only mount points of kind 'collection' are supported underneath the output_path.*`)
1008 func (s *TestSuite) TestStdout(c *C) {
1010 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1011 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1013 "environment": {"FROBIZ": "bilbo"},
1014 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1015 "output_path": "/tmp",
1017 "runtime_constraints": {}
1020 api, _ := FullRunHelper(c, helperRecord, nil, func(t *TestDockerClient) {
1021 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1023 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1026 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1027 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1028 c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1031 // Used by the TestStdoutWithWrongPath*()
1032 func StdoutErrorRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, err error) {
1033 rec := arvados.Container{}
1034 err = json.Unmarshal([]byte(record), &rec)
1037 docker := NewTestDockerClient()
1039 docker.RemoveImage(hwImageId, true)
1041 api = &ArvTestClient{Container: rec}
1042 cr = NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1043 am := &ArvMountCmdLine{}
1044 cr.RunArvMount = am.ArvMountTest
1050 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1051 _, _, err := StdoutErrorRunHelper(c, `{
1052 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1053 "output_path": "/tmp"
1054 }`, func(t *TestDockerClient) {})
1056 c.Check(err, NotNil)
1057 c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
1060 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1061 _, _, err := StdoutErrorRunHelper(c, `{
1062 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1063 "output_path": "/tmp"
1064 }`, func(t *TestDockerClient) {})
1066 c.Check(err, NotNil)
1067 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'tmp' for stdout"), Equals, true)
1070 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1071 _, _, err := StdoutErrorRunHelper(c, `{
1072 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1073 "output_path": "/tmp"
1074 }`, func(t *TestDockerClient) {})
1076 c.Check(err, NotNil)
1077 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'collection' for stdout"), Equals, true)
1080 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1081 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1082 defer os.Unsetenv("ARVADOS_API_HOST")
1083 api, _ := FullRunHelper(c, `{
1084 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1085 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1088 "mounts": {"/tmp": {"kind": "tmp"} },
1089 "output_path": "/tmp",
1091 "runtime_constraints": {"API": true}
1092 }`, nil, func(t *TestDockerClient) {
1093 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
1095 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1098 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1099 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1100 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "test.arvados.org\n"), Equals, true)
1101 c.Check(api.CalledWith("container.output", "d41d8cd98f00b204e9800998ecf8427e+0"), NotNil)
1104 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1105 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1106 defer os.Unsetenv("ARVADOS_API_HOST")
1107 api, _ := FullRunHelper(c, `{
1108 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1109 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1112 "mounts": {"/tmp": {"kind": "tmp"} },
1113 "output_path": "/tmp",
1115 "runtime_constraints": {"API": true}
1116 }`, nil, func(t *TestDockerClient) {
1117 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
1119 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1122 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1123 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1124 c.Check(api.CalledWith("container.output", "d4ab34d3d4f8a72f5c4973051ae69fab+122"), NotNil)
1127 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1129 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1130 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1132 "environment": {"FROBIZ": "bilbo"},
1134 "/tmp": {"kind": "tmp"},
1135 "/tmp/foo": {"kind": "collection",
1136 "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1137 "exclude_from_output": true
1139 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1141 "output_path": "/tmp",
1143 "runtime_constraints": {}
1146 extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1148 api, _ := FullRunHelper(c, helperRecord, extraMounts, func(t *TestDockerClient) {
1149 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1151 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1154 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1155 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1156 c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1159 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1161 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1162 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1164 "environment": {"FROBIZ": "bilbo"},
1166 "/tmp": {"kind": "tmp"},
1167 "/tmp/foo": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/"},
1168 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1169 "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1170 "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1171 "/tmp/foo/bar/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1172 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1174 "output_path": "/tmp",
1176 "runtime_constraints": {}
1179 extraMounts := []string{"a0def87f80dd594d4675809e83bd4f15+367"}
1181 api, _ := FullRunHelper(c, helperRecord, extraMounts, func(t *TestDockerClient) {
1182 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1184 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1187 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1188 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1189 for _, v := range api.Content {
1190 if v["collection"] != nil {
1191 collection := v["collection"].(arvadosclient.Dict)
1192 if strings.Index(collection["name"].(string), "output") == 0 {
1193 manifest := collection["manifest_text"].(string)
1195 c.Check(-1, Not(Equals), strings.Index(manifest, "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out"))
1197 origManifestWithDotReplacedAsFoo := strings.Replace(normalizedManifestWithSubdirs, "./", "./foo/", -1)
1198 c.Check(-1, Not(Equals), strings.Index(manifest, "./foo"+origManifestWithDotReplacedAsFoo[1:]))
1200 c.Check(-1, Not(Equals), strings.Index(manifest, "./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 9:18:bar"))
1202 c.Check(-1, Not(Equals), strings.Index(manifest, "./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt"))
1204 c.Check(-1, Not(Equals), strings.Index(manifest, "./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:sub1file2"))
1206 c.Check(-1, Not(Equals), strings.Index(manifest, "./foo/bar 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2"))
1212 func (s *TestSuite) TestStdoutWithMountPointForFileUnderOutputDir(c *C) {
1214 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1215 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1217 "environment": {"FROBIZ": "bilbo"},
1219 "/tmp": {"kind": "tmp"},
1220 "/tmp/foo": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367"},
1221 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt"},
1222 "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367/subdir1/"},
1223 "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt"},
1224 "/tmp/foo/bar/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt"},
1225 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1227 "output_path": "/tmp",
1229 "runtime_constraints": {}
1232 extraMounts := []string{
1233 "a0def87f80dd594d4675809e83bd4f15+367",
1234 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1235 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1236 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1239 api, _ := FullRunHelper(c, helperRecord, extraMounts, func(t *TestDockerClient) {
1240 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1242 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1245 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1246 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1247 for _, v := range api.Content {
1248 if v["collection"] != nil {
1249 collection := v["collection"].(arvadosclient.Dict)
1250 if strings.Index(collection["name"].(string), "output") == 0 {
1251 manifest := collection["manifest_text"].(string)
1253 c.Check(-1, Not(Equals), strings.Index(manifest, "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out"))
1255 origManifestWithDotReplacedAsFoo := strings.Replace(normalizedManifestWithSubdirs, "./", "./foo/", -1)
1256 c.Check(-1, Not(Equals), strings.Index(manifest, "./foo"+origManifestWithDotReplacedAsFoo[1:]))
1258 c.Check(-1, Not(Equals), strings.Index(manifest, "./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 9:18:bar"))
1260 c.Check(-1, Not(Equals), strings.Index(manifest, "./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt"))
1262 c.Check(-1, Not(Equals), strings.Index(manifest, "./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:sub1file2"))
1264 c.Check(-1, Not(Equals), strings.Index(manifest, "./foo/bar 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2"))