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 0:27: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 denormalizedManifestWithSubdirs = ". 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 0:9:file1_in_main.txt 9:18:file2_in_main.txt 0:27:zzzzz-8i9sb-bcdefghijkdhvnk.log.txt 0:10:subdir1/file1_in_subdir1.txt 10:17:subdir1/file2_in_subdir1.txt\n"
64 var denormalizedWithSubdirsPDH = "b0def87f80dd594d4675809e83bd4f15+367"
66 var fakeAuthUUID = "zzzzz-gj3su-55pqoyepgi2glem"
67 var fakeAuthToken = "a3ltuwzqcu2u4sc0q7yhpc2w7s00fdcqecg5d6e0u3pfohmbjt"
69 type TestDockerClient struct {
71 logReader io.ReadCloser
72 logWriter io.WriteCloser
73 fn func(t *TestDockerClient)
74 finish chan dockerclient.WaitResult
81 func NewTestDockerClient() *TestDockerClient {
82 t := &TestDockerClient{}
83 t.logReader, t.logWriter = io.Pipe()
84 t.finish = make(chan dockerclient.WaitResult)
85 t.stop = make(chan bool)
90 func (t *TestDockerClient) StopContainer(id string, timeout int) error {
95 func (t *TestDockerClient) InspectImage(id string) (*dockerclient.ImageInfo, error) {
96 if t.imageLoaded == id {
97 return &dockerclient.ImageInfo{}, nil
99 return nil, errors.New("")
103 func (t *TestDockerClient) LoadImage(reader io.Reader) error {
104 _, err := io.Copy(ioutil.Discard, reader)
108 t.imageLoaded = hwImageId
113 func (t *TestDockerClient) CreateContainer(config *dockerclient.ContainerConfig, name string, authConfig *dockerclient.AuthConfig) (string, error) {
114 if config.WorkingDir != "" {
115 t.cwd = config.WorkingDir
121 func (t *TestDockerClient) StartContainer(id string, config *dockerclient.HostConfig) error {
126 return errors.New("Invalid container id")
130 func (t *TestDockerClient) AttachContainer(id string, options *dockerclient.AttachOptions) (io.ReadCloser, error) {
131 return t.logReader, nil
134 func (t *TestDockerClient) Wait(id string) <-chan dockerclient.WaitResult {
138 func (*TestDockerClient) RemoveImage(name string, force bool) ([]*dockerclient.ImageDelete, error) {
142 func (client *ArvTestClient) Create(resourceType string,
143 parameters arvadosclient.Dict,
144 output interface{}) error {
147 defer client.Mutex.Unlock()
150 client.Content = append(client.Content, parameters)
152 if resourceType == "logs" {
153 et := parameters["log"].(arvadosclient.Dict)["event_type"].(string)
154 if client.Logs == nil {
155 client.Logs = make(map[string]*bytes.Buffer)
157 if client.Logs[et] == nil {
158 client.Logs[et] = &bytes.Buffer{}
160 client.Logs[et].Write([]byte(parameters["log"].(arvadosclient.Dict)["properties"].(map[string]string)["text"]))
163 if resourceType == "collections" && output != nil {
164 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
165 outmap := output.(*arvados.Collection)
166 outmap.PortableDataHash = fmt.Sprintf("%x+%d", md5.Sum([]byte(mt)), len(mt))
172 func (client *ArvTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
174 case method == "GET" && resourceType == "containers" && action == "auth":
175 return json.Unmarshal([]byte(`{
176 "kind": "arvados#api_client_authorization",
177 "uuid": "`+fakeAuthUUID+`",
178 "api_token": "`+fakeAuthToken+`"
181 return fmt.Errorf("Not found")
185 func (client *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
186 if resourceType == "collections" {
188 output.(*arvados.Collection).ManifestText = hwManifest
189 } else if uuid == otherPDH {
190 output.(*arvados.Collection).ManifestText = otherManifest
191 } else if uuid == normalizedWithSubdirsPDH {
192 output.(*arvados.Collection).ManifestText = normalizedManifestWithSubdirs
193 } else if uuid == denormalizedWithSubdirsPDH {
194 output.(*arvados.Collection).ManifestText = denormalizedManifestWithSubdirs
197 if resourceType == "containers" {
198 (*output.(*arvados.Container)) = client.Container
203 func (client *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
205 defer client.Mutex.Unlock()
207 client.Content = append(client.Content, parameters)
208 if resourceType == "containers" {
209 if parameters["container"].(arvadosclient.Dict)["state"] == "Running" {
210 client.WasSetRunning = true
216 var discoveryMap = map[string]interface{}{"defaultTrashLifetime": float64(1209600)}
218 func (client *ArvTestClient) Discovery(key string) (interface{}, error) {
219 return discoveryMap[key], nil
222 // CalledWith returns the parameters from the first API call whose
223 // parameters match jpath/string. E.g., CalledWith(c, "foo.bar",
224 // "baz") returns parameters with parameters["foo"]["bar"]=="baz". If
225 // no call matches, it returns nil.
226 func (client *ArvTestClient) CalledWith(jpath string, expect interface{}) arvadosclient.Dict {
228 for _, content := range client.Content {
229 var v interface{} = content
230 for _, k := range strings.Split(jpath, ".") {
231 if dict, ok := v.(arvadosclient.Dict); !ok {
244 func (client *KeepTestClient) PutHB(hash string, buf []byte) (string, int, error) {
246 return fmt.Sprintf("%s+%d", hash, len(buf)), len(buf), nil
249 type FileWrapper struct {
254 func (fw FileWrapper) Len() uint64 {
258 func (fw FileWrapper) Seek(int64, int) (int64, error) {
259 return 0, errors.New("not implemented")
262 func (client *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.Reader, error) {
263 if filename == hwImageId+".tar" {
264 rdr := ioutil.NopCloser(&bytes.Buffer{})
266 return FileWrapper{rdr, 1321984}, nil
271 func (s *TestSuite) TestLoadImage(c *C) {
272 kc := &KeepTestClient{}
273 docker := NewTestDockerClient()
274 cr := NewContainerRunner(&ArvTestClient{}, kc, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
276 _, err := cr.Docker.RemoveImage(hwImageId, true)
278 _, err = cr.Docker.InspectImage(hwImageId)
281 cr.Container.ContainerImage = hwPDH
283 // (1) Test loading image from keep
284 c.Check(kc.Called, Equals, false)
285 c.Check(cr.ContainerConfig.Image, Equals, "")
291 cr.Docker.RemoveImage(hwImageId, true)
294 c.Check(kc.Called, Equals, true)
295 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
297 _, err = cr.Docker.InspectImage(hwImageId)
300 // (2) Test using image that's already loaded
302 cr.ContainerConfig.Image = ""
306 c.Check(kc.Called, Equals, false)
307 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
311 type ArvErrorTestClient struct{}
313 func (ArvErrorTestClient) Create(resourceType string,
314 parameters arvadosclient.Dict,
315 output interface{}) error {
319 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
320 return errors.New("ArvError")
323 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
324 return errors.New("ArvError")
327 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
331 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
332 return discoveryMap[key], nil
335 type KeepErrorTestClient struct{}
337 func (KeepErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
338 return "", 0, errors.New("KeepError")
341 func (KeepErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.Reader, error) {
342 return nil, errors.New("KeepError")
345 type KeepReadErrorTestClient struct{}
347 func (KeepReadErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
351 type ErrorReader struct{}
353 func (ErrorReader) Read(p []byte) (n int, err error) {
354 return 0, errors.New("ErrorReader")
357 func (ErrorReader) Close() error {
361 func (ErrorReader) Len() uint64 {
365 func (ErrorReader) Seek(int64, int) (int64, error) {
366 return 0, errors.New("ErrorReader")
369 func (KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.Reader, error) {
370 return ErrorReader{}, nil
373 func (s *TestSuite) TestLoadImageArvError(c *C) {
375 cr := NewContainerRunner(ArvErrorTestClient{}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
376 cr.Container.ContainerImage = hwPDH
378 err := cr.LoadImage()
379 c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
382 func (s *TestSuite) TestLoadImageKeepError(c *C) {
384 docker := NewTestDockerClient()
385 cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
386 cr.Container.ContainerImage = hwPDH
388 err := cr.LoadImage()
389 c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
392 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
393 // (3) Collection doesn't contain image
394 cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
395 cr.Container.ContainerImage = otherPDH
397 err := cr.LoadImage()
398 c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
401 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
402 // (4) Collection doesn't contain image
403 docker := NewTestDockerClient()
404 cr := NewContainerRunner(&ArvTestClient{}, KeepReadErrorTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
405 cr.Container.ContainerImage = hwPDH
407 err := cr.LoadImage()
411 type ClosableBuffer struct {
415 func (*ClosableBuffer) Close() error {
419 type TestLogs struct {
420 Stdout ClosableBuffer
421 Stderr ClosableBuffer
424 func (tl *TestLogs) NewTestLoggingWriter(logstr string) io.WriteCloser {
425 if logstr == "stdout" {
428 if logstr == "stderr" {
434 func dockerLog(fd byte, msg string) []byte {
436 header := make([]byte, 8+len(by))
438 header[7] = byte(len(by))
443 func (s *TestSuite) TestRunContainer(c *C) {
444 docker := NewTestDockerClient()
445 docker.fn = func(t *TestDockerClient) {
446 t.logWriter.Write(dockerLog(1, "Hello world\n"))
448 t.finish <- dockerclient.WaitResult{}
450 cr := NewContainerRunner(&ArvTestClient{}, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
453 cr.NewLogWriter = logs.NewTestLoggingWriter
454 cr.Container.ContainerImage = hwPDH
455 cr.Container.Command = []string{"./hw"}
456 err := cr.LoadImage()
459 err = cr.CreateContainer()
462 err = cr.StartContainer()
465 err = cr.WaitFinish()
468 c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
469 c.Check(logs.Stderr.String(), Equals, "")
472 func (s *TestSuite) TestCommitLogs(c *C) {
473 api := &ArvTestClient{}
474 kc := &KeepTestClient{}
475 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
476 cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
478 cr.CrunchLog.Print("Hello world!")
479 cr.CrunchLog.Print("Goodbye")
480 cr.finalState = "Complete"
482 err := cr.CommitLogs()
485 c.Check(api.Calls, Equals, 2)
486 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
487 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
488 c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
491 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
492 api := &ArvTestClient{}
493 kc := &KeepTestClient{}
494 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
496 err := cr.UpdateContainerRunning()
499 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
502 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
503 api := &ArvTestClient{}
504 kc := &KeepTestClient{}
505 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
507 cr.LogsPDH = new(string)
508 *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
510 cr.ExitCode = new(int)
512 cr.finalState = "Complete"
514 err := cr.UpdateContainerFinal()
517 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
518 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
519 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
522 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
523 api := &ArvTestClient{}
524 kc := &KeepTestClient{}
525 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
527 cr.finalState = "Cancelled"
529 err := cr.UpdateContainerFinal()
532 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
533 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
534 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
537 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
538 // dress rehearsal of the Run() function, starting from a JSON container record.
539 func FullRunHelper(c *C, record string, extraMounts []string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, realTemp string) {
540 rec := arvados.Container{}
541 err := json.Unmarshal([]byte(record), &rec)
544 docker := NewTestDockerClient()
546 docker.RemoveImage(hwImageId, true)
548 api = &ArvTestClient{Container: rec}
550 cr = NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
551 cr.statInterval = 100 * time.Millisecond
552 am := &ArvMountCmdLine{}
553 cr.RunArvMount = am.ArvMountTest
555 realTemp, err = ioutil.TempDir("", "crunchrun_test1-")
557 defer os.RemoveAll(realTemp)
560 cr.MkTempDir = func(_ string, prefix string) (string, error) {
562 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, tempcount)
563 err := os.Mkdir(d, os.ModePerm)
564 if err != nil && strings.Contains(err.Error(), ": file exists") {
565 // Test case must have pre-populated the tempdir
571 if extraMounts != nil && len(extraMounts) > 0 {
572 err := cr.SetupArvMountPoint("keep")
575 for _, m := range extraMounts {
576 os.MkdirAll(cr.ArvMountPoint+"/by_id/"+m, os.ModePerm)
582 c.Check(api.WasSetRunning, Equals, true)
584 c.Check(api.Content[api.Calls-1]["container"].(arvadosclient.Dict)["log"], NotNil)
587 for k, v := range api.Logs {
596 func (s *TestSuite) TestFullRunHello(c *C) {
597 api, _, _ := FullRunHelper(c, `{
598 "command": ["echo", "hello world"],
599 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
602 "mounts": {"/tmp": {"kind": "tmp"} },
603 "output_path": "/tmp",
605 "runtime_constraints": {}
606 }`, nil, func(t *TestDockerClient) {
607 t.logWriter.Write(dockerLog(1, "hello world\n"))
609 t.finish <- dockerclient.WaitResult{}
612 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
613 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
614 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
618 func (s *TestSuite) TestCrunchstat(c *C) {
619 api, _, _ := FullRunHelper(c, `{
620 "command": ["sleep", "1"],
621 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
624 "mounts": {"/tmp": {"kind": "tmp"} },
625 "output_path": "/tmp",
627 "runtime_constraints": {}
628 }`, nil, func(t *TestDockerClient) {
629 time.Sleep(time.Second)
631 t.finish <- dockerclient.WaitResult{}
634 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
635 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
637 // We didn't actually start a container, so crunchstat didn't
638 // find accounting files and therefore didn't log any stats.
639 // It should have logged a "can't find accounting files"
640 // message after one poll interval, though, so we can confirm
642 c.Assert(api.Logs["crunchstat"], NotNil)
643 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
645 // The "files never appeared" log assures us that we called
646 // (*crunchstat.Reporter)Stop(), and that we set it up with
647 // the correct container ID "abcde":
648 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files never appeared for abcde\n`)
651 func (s *TestSuite) TestFullRunStderr(c *C) {
652 api, _, _ := FullRunHelper(c, `{
653 "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
654 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
657 "mounts": {"/tmp": {"kind": "tmp"} },
658 "output_path": "/tmp",
660 "runtime_constraints": {}
661 }`, nil, func(t *TestDockerClient) {
662 t.logWriter.Write(dockerLog(1, "hello\n"))
663 t.logWriter.Write(dockerLog(2, "world\n"))
665 t.finish <- dockerclient.WaitResult{ExitCode: 1}
668 final := api.CalledWith("container.state", "Complete")
669 c.Assert(final, NotNil)
670 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
671 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
673 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
674 c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
677 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
678 api, _, _ := FullRunHelper(c, `{
680 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
683 "mounts": {"/tmp": {"kind": "tmp"} },
684 "output_path": "/tmp",
686 "runtime_constraints": {}
687 }`, nil, func(t *TestDockerClient) {
688 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
690 t.finish <- dockerclient.WaitResult{ExitCode: 0}
693 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
694 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
695 c.Log(api.Logs["stdout"])
696 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
699 func (s *TestSuite) TestFullRunSetCwd(c *C) {
700 api, _, _ := FullRunHelper(c, `{
702 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
705 "mounts": {"/tmp": {"kind": "tmp"} },
706 "output_path": "/tmp",
708 "runtime_constraints": {}
709 }`, nil, func(t *TestDockerClient) {
710 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
712 t.finish <- dockerclient.WaitResult{ExitCode: 0}
715 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
716 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
717 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
720 func (s *TestSuite) TestCancel(c *C) {
722 "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
723 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
726 "mounts": {"/tmp": {"kind": "tmp"} },
727 "output_path": "/tmp",
729 "runtime_constraints": {}
732 rec := arvados.Container{}
733 err := json.Unmarshal([]byte(record), &rec)
736 docker := NewTestDockerClient()
737 docker.fn = func(t *TestDockerClient) {
739 t.logWriter.Write(dockerLog(1, "foo\n"))
741 t.finish <- dockerclient.WaitResult{ExitCode: 0}
743 docker.RemoveImage(hwImageId, true)
745 api := &ArvTestClient{Container: rec}
746 cr := NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
747 am := &ArvMountCmdLine{}
748 cr.RunArvMount = am.ArvMountTest
751 for cr.ContainerID == "" {
752 time.Sleep(time.Millisecond)
754 cr.SigChan <- syscall.SIGINT
761 for k, v := range api.Logs {
767 c.Check(api.CalledWith("container.log", nil), NotNil)
768 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
769 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "foo\n"), Equals, true)
773 func (s *TestSuite) TestFullRunSetEnv(c *C) {
774 api, _, _ := FullRunHelper(c, `{
775 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
776 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
778 "environment": {"FROBIZ": "bilbo"},
779 "mounts": {"/tmp": {"kind": "tmp"} },
780 "output_path": "/tmp",
782 "runtime_constraints": {}
783 }`, nil, func(t *TestDockerClient) {
784 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
786 t.finish <- dockerclient.WaitResult{ExitCode: 0}
789 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
790 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
791 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)
794 type ArvMountCmdLine struct {
799 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
805 func stubCert(temp string) string {
806 path := temp + "/ca-certificates.crt"
807 crt, _ := os.Create(path)
809 arvadosclient.CertFiles = []string{path}
813 func (s *TestSuite) TestSetupMounts(c *C) {
814 api := &ArvTestClient{}
815 kc := &KeepTestClient{}
816 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
817 am := &ArvMountCmdLine{}
818 cr.RunArvMount = am.ArvMountTest
820 realTemp, err := ioutil.TempDir("", "crunchrun_test1-")
822 certTemp, err := ioutil.TempDir("", "crunchrun_test2-")
824 stubCertPath := stubCert(certTemp)
826 defer os.RemoveAll(realTemp)
827 defer os.RemoveAll(certTemp)
830 cr.MkTempDir = func(_ string, prefix string) (string, error) {
832 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
833 err := os.Mkdir(d, os.ModePerm)
834 if err != nil && strings.Contains(err.Error(), ": file exists") {
835 // Test case must have pre-populated the tempdir
841 checkEmpty := func() {
842 filepath.Walk(realTemp, func(path string, _ os.FileInfo, err error) error {
843 c.Check(path, Equals, realTemp)
851 cr.ArvMountPoint = ""
852 cr.Container.Mounts = make(map[string]arvados.Mount)
853 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
854 cr.OutputPath = "/tmp"
856 err := cr.SetupMounts()
858 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
859 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/tmp"})
866 cr.ArvMountPoint = ""
867 cr.Container.Mounts = make(map[string]arvados.Mount)
868 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
869 cr.OutputPath = "/tmp"
872 cr.Container.RuntimeConstraints.API = &apiflag
874 err := cr.SetupMounts()
876 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
877 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/tmp", stubCertPath + ":/etc/arvados/ca-certificates.crt:ro"})
886 cr.ArvMountPoint = ""
887 cr.Container.Mounts = map[string]arvados.Mount{
888 "/keeptmp": {Kind: "collection", Writable: true},
890 cr.OutputPath = "/keeptmp"
892 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
894 err := cr.SetupMounts()
896 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
897 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/tmp0:/keeptmp"})
904 cr.ArvMountPoint = ""
905 cr.Container.Mounts = map[string]arvados.Mount{
906 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
907 "/keepout": {Kind: "collection", Writable: true},
909 cr.OutputPath = "/keepout"
911 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
912 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
914 err := cr.SetupMounts()
916 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
917 sort.StringSlice(cr.Binds).Sort()
918 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
919 realTemp + "/keep1/tmp0:/keepout"})
926 cr.ArvMountPoint = ""
927 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
928 cr.Container.Mounts = map[string]arvados.Mount{
929 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
930 "/keepout": {Kind: "collection", Writable: true},
932 cr.OutputPath = "/keepout"
934 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
935 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
937 err := cr.SetupMounts()
939 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
940 sort.StringSlice(cr.Binds).Sort()
941 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
942 realTemp + "/keep1/tmp0:/keepout"})
947 for _, test := range []struct {
951 {in: "foo", out: `"foo"`},
952 {in: nil, out: `null`},
953 {in: map[string]int{"foo": 123}, out: `{"foo":123}`},
956 cr.ArvMountPoint = ""
957 cr.Container.Mounts = map[string]arvados.Mount{
958 "/mnt/test.json": {Kind: "json", Content: test.in},
960 err := cr.SetupMounts()
962 sort.StringSlice(cr.Binds).Sort()
963 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2/mountdata.json:/mnt/test.json:ro"})
964 content, err := ioutil.ReadFile(realTemp + "/2/mountdata.json")
966 c.Check(content, DeepEquals, []byte(test.out))
971 // Read-only mount points are 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"},
980 cr.OutputPath = "/tmp"
982 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
984 err := cr.SetupMounts()
986 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
987 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/tmp", realTemp + "/keep1/tmp0:/tmp/foo:ro"})
992 // Writable mount points are not allowed underneath output_dir mount point
995 cr.ArvMountPoint = ""
996 cr.Container.Mounts = make(map[string]arvados.Mount)
997 cr.Container.Mounts = map[string]arvados.Mount{
998 "/tmp": {Kind: "tmp"},
999 "/tmp/foo": {Kind: "collection", Writable: true},
1001 cr.OutputPath = "/tmp"
1003 err := cr.SetupMounts()
1004 c.Check(err, NotNil)
1005 c.Check(err, ErrorMatches, `Writable mount points are not permitted underneath the output_path.*`)
1010 // Only mount points of kind 'collection' are allowed underneath output_dir mount point
1013 cr.ArvMountPoint = ""
1014 cr.Container.Mounts = make(map[string]arvados.Mount)
1015 cr.Container.Mounts = map[string]arvados.Mount{
1016 "/tmp": {Kind: "tmp"},
1017 "/tmp/foo": {Kind: "json"},
1019 cr.OutputPath = "/tmp"
1021 err := cr.SetupMounts()
1022 c.Check(err, NotNil)
1023 c.Check(err, ErrorMatches, `Only mount points of kind 'collection' are supported underneath the output_path.*`)
1029 func (s *TestSuite) TestStdout(c *C) {
1031 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1032 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1034 "environment": {"FROBIZ": "bilbo"},
1035 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1036 "output_path": "/tmp",
1038 "runtime_constraints": {}
1041 api, _, _ := FullRunHelper(c, helperRecord, nil, func(t *TestDockerClient) {
1042 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1044 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1047 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1048 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1049 c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1052 // Used by the TestStdoutWithWrongPath*()
1053 func StdoutErrorRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, err error) {
1054 rec := arvados.Container{}
1055 err = json.Unmarshal([]byte(record), &rec)
1058 docker := NewTestDockerClient()
1060 docker.RemoveImage(hwImageId, true)
1062 api = &ArvTestClient{Container: rec}
1063 cr = NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1064 am := &ArvMountCmdLine{}
1065 cr.RunArvMount = am.ArvMountTest
1071 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1072 _, _, err := StdoutErrorRunHelper(c, `{
1073 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1074 "output_path": "/tmp"
1075 }`, func(t *TestDockerClient) {})
1077 c.Check(err, NotNil)
1078 c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
1081 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1082 _, _, err := StdoutErrorRunHelper(c, `{
1083 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1084 "output_path": "/tmp"
1085 }`, func(t *TestDockerClient) {})
1087 c.Check(err, NotNil)
1088 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'tmp' for stdout"), Equals, true)
1091 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1092 _, _, err := StdoutErrorRunHelper(c, `{
1093 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1094 "output_path": "/tmp"
1095 }`, func(t *TestDockerClient) {})
1097 c.Check(err, NotNil)
1098 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'collection' for stdout"), Equals, true)
1101 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1102 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1103 defer os.Unsetenv("ARVADOS_API_HOST")
1104 api, _, _ := FullRunHelper(c, `{
1105 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1106 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1109 "mounts": {"/tmp": {"kind": "tmp"} },
1110 "output_path": "/tmp",
1112 "runtime_constraints": {"API": true}
1113 }`, nil, func(t *TestDockerClient) {
1114 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
1116 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1119 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1120 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1121 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "test.arvados.org\n"), Equals, true)
1122 c.Check(api.CalledWith("container.output", "d41d8cd98f00b204e9800998ecf8427e+0"), NotNil)
1125 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1126 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1127 defer os.Unsetenv("ARVADOS_API_HOST")
1128 api, _, _ := FullRunHelper(c, `{
1129 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1130 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1133 "mounts": {"/tmp": {"kind": "tmp"} },
1134 "output_path": "/tmp",
1136 "runtime_constraints": {"API": true}
1137 }`, nil, func(t *TestDockerClient) {
1138 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
1140 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1143 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1144 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1145 c.Check(api.CalledWith("container.output", "d4ab34d3d4f8a72f5c4973051ae69fab+122"), NotNil)
1148 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1150 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1151 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1153 "environment": {"FROBIZ": "bilbo"},
1155 "/tmp": {"kind": "tmp"},
1156 "/tmp/foo": {"kind": "collection",
1157 "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1158 "exclude_from_output": true
1160 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1162 "output_path": "/tmp",
1164 "runtime_constraints": {}
1167 extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1169 api, _, _ := FullRunHelper(c, helperRecord, extraMounts, func(t *TestDockerClient) {
1170 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1172 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1175 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1176 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1177 c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1180 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1182 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1183 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1185 "environment": {"FROBIZ": "bilbo"},
1187 "/tmp": {"kind": "tmp"},
1188 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1189 "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1190 "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1191 "/tmp/foo/baz/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1192 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1194 "output_path": "/tmp",
1196 "runtime_constraints": {}
1199 extraMounts := []string{
1200 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1201 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1202 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1205 api, runner, realtemp := FullRunHelper(c, helperRecord, extraMounts, func(t *TestDockerClient) {
1206 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1208 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1211 c.Check(runner.Binds, DeepEquals, []string{realtemp + "/2:/tmp",
1212 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt:/tmp/foo/bar:ro",
1213 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt:/tmp/foo/baz/sub2file2:ro",
1214 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1:/tmp/foo/sub1:ro",
1215 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt:/tmp/foo/sub1file2:ro",
1218 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1219 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1220 for _, v := range api.Content {
1221 if v["collection"] != nil {
1222 collection := v["collection"].(arvadosclient.Dict)
1223 if strings.Index(collection["name"].(string), "output") == 0 {
1224 manifest := collection["manifest_text"].(string)
1226 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1227 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 9:18:bar 9:18:sub1file2
1228 ./foo/baz 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2
1229 ./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1230 ./foo/sub1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1237 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
1239 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1240 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1242 "environment": {"FROBIZ": "bilbo"},
1244 "/tmp": {"kind": "tmp"},
1245 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt"},
1246 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1248 "output_path": "/tmp",
1250 "runtime_constraints": {}
1253 extraMounts := []string{
1254 "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1257 api, _, _ := FullRunHelper(c, helperRecord, extraMounts, func(t *TestDockerClient) {
1258 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1260 t.finish <- dockerclient.WaitResult{ExitCode: 0}
1263 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1264 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1265 for _, v := range api.Content {
1266 if v["collection"] != nil {
1267 collection := v["collection"].(arvadosclient.Dict)
1268 if strings.Index(collection["name"].(string), "output") == 0 {
1269 manifest := collection["manifest_text"].(string)
1271 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1272 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 10:17:bar