1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
28 "git.curoverse.com/arvados.git/sdk/go/arvados"
29 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
30 "git.curoverse.com/arvados.git/sdk/go/arvadostest"
31 "git.curoverse.com/arvados.git/sdk/go/manifest"
32 "golang.org/x/net/context"
34 dockertypes "github.com/docker/docker/api/types"
35 dockercontainer "github.com/docker/docker/api/types/container"
36 dockernetwork "github.com/docker/docker/api/types/network"
40 // Gocheck boilerplate
41 func TestCrunchExec(t *testing.T) {
45 // Gocheck boilerplate
46 var _ = Suite(&TestSuite{})
48 type TestSuite struct {
49 docker *TestDockerClient
52 func (s *TestSuite) SetUpTest(c *C) {
53 s.docker = NewTestDockerClient()
56 type ArvTestClient struct {
59 Content []arvadosclient.Dict
62 Logs map[string]*bytes.Buffer
68 type KeepTestClient struct {
73 var hwManifest = ". 82ab40c24fc8df01798e57ba66795bb1+841216+Aa124ac75e5168396c73c0a18eda641a4f41791c0@569fa8c3 0:841216:9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7.tar\n"
74 var hwPDH = "a45557269dcb65a6b78f9ac061c0850b+120"
75 var hwImageId = "9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7"
77 var otherManifest = ". 68a84f561b1d1708c6baff5e019a9ab3+46+Ae5d0af96944a3690becb1decdf60cc1c937f556d@5693216f 0:46:md5sum.txt\n"
78 var otherPDH = "a3e8f74c6f101eae01fa08bfb4e49b3a+54"
80 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
81 ./subdir1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
82 ./subdir1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
85 var normalizedWithSubdirsPDH = "a0def87f80dd594d4675809e83bd4f15+367"
87 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"
88 var denormalizedWithSubdirsPDH = "b0def87f80dd594d4675809e83bd4f15+367"
90 var fakeAuthUUID = "zzzzz-gj3su-55pqoyepgi2glem"
91 var fakeAuthToken = "a3ltuwzqcu2u4sc0q7yhpc2w7s00fdcqecg5d6e0u3pfohmbjt"
93 type TestDockerClient struct {
95 logReader io.ReadCloser
96 logWriter io.WriteCloser
97 fn func(t *TestDockerClient)
107 func NewTestDockerClient() *TestDockerClient {
108 t := &TestDockerClient{}
109 t.logReader, t.logWriter = io.Pipe()
110 t.stop = make(chan bool, 1)
115 type MockConn struct {
119 func (m *MockConn) Write(b []byte) (int, error) {
123 func NewMockConn() *MockConn {
128 func (t *TestDockerClient) ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error) {
129 return dockertypes.HijackedResponse{Conn: NewMockConn(), Reader: bufio.NewReader(t.logReader)}, nil
132 func (t *TestDockerClient) ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig, networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error) {
133 if config.WorkingDir != "" {
134 t.cwd = config.WorkingDir
137 return dockercontainer.ContainerCreateCreatedBody{ID: "abcde"}, nil
140 func (t *TestDockerClient) ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error {
142 return errors.New(`Error response from daemon: oci runtime error: container_linux.go:247: starting container process caused "process_linux.go:359: container init caused \"rootfs_linux.go:54: mounting \\\"/tmp/keep453790790/by_id/99999999999999999999999999999999+99999/myGenome\\\" to rootfs \\\"/tmp/docker/overlay2/9999999999999999999999999999999999999999999999999999999999999999/merged\\\" at \\\"/tmp/docker/overlay2/9999999999999999999999999999999999999999999999999999999999999999/merged/keep/99999999999999999999999999999999+99999/myGenome\\\" caused \\\"no such file or directory\\\"\""`)
145 return errors.New(`panic: standard_init_linux.go:175: exec user process caused "no such file or directory"`)
148 return errors.New(`Error response from daemon: Cannot start container 41f26cbc43bcc1280f4323efb1830a394ba8660c9d1c2b564ba42bf7f7694845: [8] System error: no such file or directory`)
151 return errors.New(`Error response from daemon: Cannot start container 58099cd76c834f3dc2a4fb76c8028f049ae6d4fdf0ec373e1f2cfea030670c2d: [8] System error: exec: "foobar": executable file not found in $PATH`)
154 if container == "abcde" {
155 // t.fn gets executed in ContainerWait
158 return errors.New("Invalid container id")
162 func (t *TestDockerClient) ContainerRemove(ctx context.Context, container string, options dockertypes.ContainerRemoveOptions) error {
167 func (t *TestDockerClient) ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error) {
169 body := make(chan dockercontainer.ContainerWaitOKBody, 1)
170 err := make(chan error)
173 body <- dockercontainer.ContainerWaitOKBody{StatusCode: int64(t.exitCode)}
178 func (t *TestDockerClient) ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error) {
180 return dockertypes.ImageInspect{}, nil, fmt.Errorf("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?")
183 if t.imageLoaded == image {
184 return dockertypes.ImageInspect{}, nil, nil
186 return dockertypes.ImageInspect{}, nil, errors.New("")
190 func (t *TestDockerClient) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error) {
192 return dockertypes.ImageLoadResponse{}, fmt.Errorf("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?")
194 _, err := io.Copy(ioutil.Discard, input)
196 return dockertypes.ImageLoadResponse{}, err
198 t.imageLoaded = hwImageId
199 return dockertypes.ImageLoadResponse{Body: ioutil.NopCloser(input)}, nil
203 func (*TestDockerClient) ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {
207 func (client *ArvTestClient) Create(resourceType string,
208 parameters arvadosclient.Dict,
209 output interface{}) error {
212 defer client.Mutex.Unlock()
215 client.Content = append(client.Content, parameters)
217 if resourceType == "logs" {
218 et := parameters["log"].(arvadosclient.Dict)["event_type"].(string)
219 if client.Logs == nil {
220 client.Logs = make(map[string]*bytes.Buffer)
222 if client.Logs[et] == nil {
223 client.Logs[et] = &bytes.Buffer{}
225 client.Logs[et].Write([]byte(parameters["log"].(arvadosclient.Dict)["properties"].(map[string]string)["text"]))
228 if resourceType == "collections" && output != nil {
229 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
230 outmap := output.(*arvados.Collection)
231 outmap.PortableDataHash = fmt.Sprintf("%x+%d", md5.Sum([]byte(mt)), len(mt))
237 func (client *ArvTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
239 case method == "GET" && resourceType == "containers" && action == "auth":
240 return json.Unmarshal([]byte(`{
241 "kind": "arvados#api_client_authorization",
242 "uuid": "`+fakeAuthUUID+`",
243 "api_token": "`+fakeAuthToken+`"
245 case method == "GET" && resourceType == "containers" && action == "secret_mounts":
246 if client.secretMounts != nil {
247 return json.Unmarshal(client.secretMounts, output)
249 return json.Unmarshal([]byte(`{"secret_mounts":{}}`), output)
252 return fmt.Errorf("Not found")
256 func (client *ArvTestClient) CallRaw(method, resourceType, uuid, action string,
257 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
259 if method == "GET" && resourceType == "nodes" && uuid == "" && action == "" {
261 "kind": "arvados#nodeList",
263 "uuid": "zzzzz-7ekkf-2z3mc76g2q73aio",
264 "hostname": "compute2",
265 "properties": {"total_cpu_cores": 16}
267 } else if method == "GET" && resourceType == "containers" && action == "" && !client.callraw {
269 j, err = json.Marshal(map[string]interface{}{
270 "items": []interface{}{client.Container},
271 "kind": "arvados#nodeList",
274 j, err = json.Marshal(client.Container)
278 "command": ["sleep", "1"],
279 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
282 "mounts": {"/tmp": {"kind": "tmp"}, "/json": {"kind": "json", "content": {"number": 123456789123456789}}},
283 "output_path": "/tmp",
285 "runtime_constraints": {}
288 return ioutil.NopCloser(bytes.NewReader(j)), err
291 func (client *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
292 if resourceType == "collections" {
294 output.(*arvados.Collection).ManifestText = hwManifest
295 } else if uuid == otherPDH {
296 output.(*arvados.Collection).ManifestText = otherManifest
297 } else if uuid == normalizedWithSubdirsPDH {
298 output.(*arvados.Collection).ManifestText = normalizedManifestWithSubdirs
299 } else if uuid == denormalizedWithSubdirsPDH {
300 output.(*arvados.Collection).ManifestText = denormalizedManifestWithSubdirs
303 if resourceType == "containers" {
304 (*output.(*arvados.Container)) = client.Container
309 func (client *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
311 defer client.Mutex.Unlock()
313 client.Content = append(client.Content, parameters)
314 if resourceType == "containers" {
315 if parameters["container"].(arvadosclient.Dict)["state"] == "Running" {
316 client.WasSetRunning = true
322 var discoveryMap = map[string]interface{}{
323 "defaultTrashLifetime": float64(1209600),
324 "crunchLimitLogBytesPerJob": float64(67108864),
325 "crunchLogThrottleBytes": float64(65536),
326 "crunchLogThrottlePeriod": float64(60),
327 "crunchLogThrottleLines": float64(1024),
328 "crunchLogPartialLineThrottlePeriod": float64(5),
329 "crunchLogBytesPerEvent": float64(4096),
330 "crunchLogSecondsBetweenEvents": float64(1),
333 func (client *ArvTestClient) Discovery(key string) (interface{}, error) {
334 return discoveryMap[key], nil
337 // CalledWith returns the parameters from the first API call whose
338 // parameters match jpath/string. E.g., CalledWith(c, "foo.bar",
339 // "baz") returns parameters with parameters["foo"]["bar"]=="baz". If
340 // no call matches, it returns nil.
341 func (client *ArvTestClient) CalledWith(jpath string, expect interface{}) arvadosclient.Dict {
343 for _, content := range client.Content {
344 var v interface{} = content
345 for _, k := range strings.Split(jpath, ".") {
346 if dict, ok := v.(arvadosclient.Dict); !ok {
359 func (client *KeepTestClient) PutHB(hash string, buf []byte) (string, int, error) {
361 return fmt.Sprintf("%s+%d", hash, len(buf)), len(buf), nil
364 func (*KeepTestClient) ClearBlockCache() {
367 func (client *KeepTestClient) Close() {
371 type FileWrapper struct {
376 func (fw FileWrapper) Readdir(n int) ([]os.FileInfo, error) {
377 return nil, errors.New("not implemented")
380 func (fw FileWrapper) Seek(int64, int) (int64, error) {
381 return 0, errors.New("not implemented")
384 func (fw FileWrapper) Size() int64 {
388 func (fw FileWrapper) Stat() (os.FileInfo, error) {
389 return nil, errors.New("not implemented")
392 func (fw FileWrapper) Truncate(int64) error {
393 return errors.New("not implemented")
396 func (fw FileWrapper) Write([]byte) (int, error) {
397 return 0, errors.New("not implemented")
400 func (client *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
401 if filename == hwImageId+".tar" {
402 rdr := ioutil.NopCloser(&bytes.Buffer{})
404 return FileWrapper{rdr, 1321984}, nil
405 } else if filename == "/file1_in_main.txt" {
406 rdr := ioutil.NopCloser(strings.NewReader("foo"))
408 return FileWrapper{rdr, 3}, nil
413 func (s *TestSuite) TestLoadImage(c *C) {
414 kc := &KeepTestClient{}
416 cr := NewContainerRunner(&ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
418 _, err := cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
421 _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
424 cr.Container.ContainerImage = hwPDH
426 // (1) Test loading image from keep
427 c.Check(kc.Called, Equals, false)
428 c.Check(cr.ContainerConfig.Image, Equals, "")
434 cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
437 c.Check(kc.Called, Equals, true)
438 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
440 _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
443 // (2) Test using image that's already loaded
445 cr.ContainerConfig.Image = ""
449 c.Check(kc.Called, Equals, false)
450 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
454 type ArvErrorTestClient struct{}
456 func (ArvErrorTestClient) Create(resourceType string,
457 parameters arvadosclient.Dict,
458 output interface{}) error {
462 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
463 return errors.New("ArvError")
466 func (ArvErrorTestClient) CallRaw(method, resourceType, uuid, action string,
467 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
468 return nil, errors.New("ArvError")
471 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
472 return errors.New("ArvError")
475 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
479 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
480 return discoveryMap[key], nil
483 type KeepErrorTestClient struct{}
485 func (KeepErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
486 return "", 0, errors.New("KeepError")
489 func (KeepErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
490 return nil, errors.New("KeepError")
493 func (KeepErrorTestClient) ClearBlockCache() {
496 type KeepReadErrorTestClient struct{}
498 func (KeepReadErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
502 func (KeepReadErrorTestClient) ClearBlockCache() {
505 type ErrorReader struct {
509 func (ErrorReader) Read(p []byte) (n int, err error) {
510 return 0, errors.New("ErrorReader")
513 func (ErrorReader) Seek(int64, int) (int64, error) {
514 return 0, errors.New("ErrorReader")
517 func (KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
518 return ErrorReader{}, nil
521 func (s *TestSuite) TestLoadImageArvError(c *C) {
523 kc := &KeepTestClient{}
525 cr := NewContainerRunner(ArvErrorTestClient{}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
526 cr.Container.ContainerImage = hwPDH
528 err := cr.LoadImage()
529 c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
532 func (s *TestSuite) TestLoadImageKeepError(c *C) {
534 cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
535 cr.Container.ContainerImage = hwPDH
537 err := cr.LoadImage()
538 c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
541 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
542 // (3) Collection doesn't contain image
543 cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
544 cr.Container.ContainerImage = otherPDH
546 err := cr.LoadImage()
547 c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
550 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
551 // (4) Collection doesn't contain image
552 cr := NewContainerRunner(&ArvTestClient{}, KeepReadErrorTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
553 cr.Container.ContainerImage = hwPDH
555 err := cr.LoadImage()
559 type ClosableBuffer struct {
563 func (*ClosableBuffer) Close() error {
567 type TestLogs struct {
568 Stdout ClosableBuffer
569 Stderr ClosableBuffer
572 func (tl *TestLogs) NewTestLoggingWriter(logstr string) io.WriteCloser {
573 if logstr == "stdout" {
576 if logstr == "stderr" {
582 func dockerLog(fd byte, msg string) []byte {
584 header := make([]byte, 8+len(by))
586 header[7] = byte(len(by))
591 func (s *TestSuite) TestRunContainer(c *C) {
592 s.docker.fn = func(t *TestDockerClient) {
593 t.logWriter.Write(dockerLog(1, "Hello world\n"))
596 kc := &KeepTestClient{}
598 cr := NewContainerRunner(&ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
601 cr.NewLogWriter = logs.NewTestLoggingWriter
602 cr.Container.ContainerImage = hwPDH
603 cr.Container.Command = []string{"./hw"}
604 err := cr.LoadImage()
607 err = cr.CreateContainer()
610 err = cr.StartContainer()
613 err = cr.WaitFinish()
616 c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
617 c.Check(logs.Stderr.String(), Equals, "")
620 func (s *TestSuite) TestCommitLogs(c *C) {
621 api := &ArvTestClient{}
622 kc := &KeepTestClient{}
624 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
625 cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
627 cr.CrunchLog.Print("Hello world!")
628 cr.CrunchLog.Print("Goodbye")
629 cr.finalState = "Complete"
631 err := cr.CommitLogs()
634 c.Check(api.Calls, Equals, 2)
635 c.Check(api.Content[1]["ensure_unique_name"], Equals, true)
636 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
637 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
638 c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
641 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
642 api := &ArvTestClient{}
643 kc := &KeepTestClient{}
645 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
647 err := cr.UpdateContainerRunning()
650 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
653 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
654 api := &ArvTestClient{}
655 kc := &KeepTestClient{}
657 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
659 cr.LogsPDH = new(string)
660 *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
662 cr.ExitCode = new(int)
664 cr.finalState = "Complete"
666 err := cr.UpdateContainerFinal()
669 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
670 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
671 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
674 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
675 api := &ArvTestClient{}
676 kc := &KeepTestClient{}
678 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
680 cr.finalState = "Cancelled"
682 err := cr.UpdateContainerFinal()
685 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
686 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
687 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
690 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
691 // dress rehearsal of the Run() function, starting from a JSON container record.
692 func (s *TestSuite) fullRunHelper(c *C, record string, extraMounts []string, exitCode int, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, realTemp string) {
693 rec := arvados.Container{}
694 err := json.Unmarshal([]byte(record), &rec)
698 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
700 err = json.Unmarshal([]byte(record), &sm)
702 secretMounts, err := json.Marshal(sm)
703 log.Printf("%q %q", sm, secretMounts)
706 s.docker.exitCode = exitCode
708 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
710 api = &ArvTestClient{Container: rec}
712 kc := &KeepTestClient{}
714 cr = NewContainerRunner(api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
715 cr.statInterval = 100 * time.Millisecond
716 am := &ArvMountCmdLine{}
717 cr.RunArvMount = am.ArvMountTest
719 realTemp, err = ioutil.TempDir("", "crunchrun_test1-")
721 defer os.RemoveAll(realTemp)
723 s.docker.realTemp = realTemp
726 cr.MkTempDir = func(_ string, prefix string) (string, error) {
728 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, tempcount)
729 err := os.Mkdir(d, os.ModePerm)
730 if err != nil && strings.Contains(err.Error(), ": file exists") {
731 // Test case must have pre-populated the tempdir
736 cr.MkArvClient = func(token string) (IArvadosClient, error) {
737 return &ArvTestClient{secretMounts: secretMounts}, nil
740 if extraMounts != nil && len(extraMounts) > 0 {
741 err := cr.SetupArvMountPoint("keep")
744 for _, m := range extraMounts {
745 os.MkdirAll(cr.ArvMountPoint+"/by_id/"+m, os.ModePerm)
750 if api.CalledWith("container.state", "Complete") != nil {
754 c.Check(api.WasSetRunning, Equals, true)
755 c.Check(api.Content[api.Calls-2]["container"].(arvadosclient.Dict)["log"], NotNil)
759 for k, v := range api.Logs {
768 func (s *TestSuite) TestFullRunHello(c *C) {
769 api, _, _ := s.fullRunHelper(c, `{
770 "command": ["echo", "hello world"],
771 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
774 "mounts": {"/tmp": {"kind": "tmp"} },
775 "output_path": "/tmp",
777 "runtime_constraints": {}
778 }`, nil, 0, func(t *TestDockerClient) {
779 t.logWriter.Write(dockerLog(1, "hello world\n"))
783 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
784 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
785 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
789 func (s *TestSuite) TestCrunchstat(c *C) {
790 api, _, _ := s.fullRunHelper(c, `{
791 "command": ["sleep", "1"],
792 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
795 "mounts": {"/tmp": {"kind": "tmp"} },
796 "output_path": "/tmp",
798 "runtime_constraints": {}
799 }`, nil, 0, func(t *TestDockerClient) {
800 time.Sleep(time.Second)
804 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
805 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
807 // We didn't actually start a container, so crunchstat didn't
808 // find accounting files and therefore didn't log any stats.
809 // It should have logged a "can't find accounting files"
810 // message after one poll interval, though, so we can confirm
812 c.Assert(api.Logs["crunchstat"], NotNil)
813 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
815 // The "files never appeared" log assures us that we called
816 // (*crunchstat.Reporter)Stop(), and that we set it up with
817 // the correct container ID "abcde":
818 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files never appeared for abcde\n`)
821 func (s *TestSuite) TestNodeInfoLog(c *C) {
822 os.Setenv("SLURMD_NODENAME", "compute2")
823 api, _, _ := s.fullRunHelper(c, `{
824 "command": ["sleep", "1"],
825 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
828 "mounts": {"/tmp": {"kind": "tmp"} },
829 "output_path": "/tmp",
831 "runtime_constraints": {}
833 func(t *TestDockerClient) {
834 time.Sleep(time.Second)
838 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
839 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
841 c.Assert(api.Logs["node"], NotNil)
842 json := api.Logs["node"].String()
843 c.Check(json, Matches, `(?ms).*"uuid": *"zzzzz-7ekkf-2z3mc76g2q73aio".*`)
844 c.Check(json, Matches, `(?ms).*"total_cpu_cores": *16.*`)
845 c.Check(json, Not(Matches), `(?ms).*"info":.*`)
847 c.Assert(api.Logs["node-info"], NotNil)
848 json = api.Logs["node-info"].String()
849 c.Check(json, Matches, `(?ms).*Host Information.*`)
850 c.Check(json, Matches, `(?ms).*CPU Information.*`)
851 c.Check(json, Matches, `(?ms).*Memory Information.*`)
852 c.Check(json, Matches, `(?ms).*Disk Space.*`)
853 c.Check(json, Matches, `(?ms).*Disk INodes.*`)
856 func (s *TestSuite) TestContainerRecordLog(c *C) {
857 api, _, _ := s.fullRunHelper(c, `{
858 "command": ["sleep", "1"],
859 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
862 "mounts": {"/tmp": {"kind": "tmp"} },
863 "output_path": "/tmp",
865 "runtime_constraints": {}
867 func(t *TestDockerClient) {
868 time.Sleep(time.Second)
872 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
873 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
875 c.Assert(api.Logs["container"], NotNil)
876 c.Check(api.Logs["container"].String(), Matches, `(?ms).*container_image.*`)
879 func (s *TestSuite) TestFullRunStderr(c *C) {
880 api, _, _ := s.fullRunHelper(c, `{
881 "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
882 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
885 "mounts": {"/tmp": {"kind": "tmp"} },
886 "output_path": "/tmp",
888 "runtime_constraints": {}
889 }`, nil, 1, func(t *TestDockerClient) {
890 t.logWriter.Write(dockerLog(1, "hello\n"))
891 t.logWriter.Write(dockerLog(2, "world\n"))
895 final := api.CalledWith("container.state", "Complete")
896 c.Assert(final, NotNil)
897 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
898 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
900 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
901 c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
904 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
905 api, _, _ := s.fullRunHelper(c, `{
907 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
910 "mounts": {"/tmp": {"kind": "tmp"} },
911 "output_path": "/tmp",
913 "runtime_constraints": {}
914 }`, nil, 0, func(t *TestDockerClient) {
915 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
919 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
920 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
921 c.Log(api.Logs["stdout"])
922 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
925 func (s *TestSuite) TestFullRunSetCwd(c *C) {
926 api, _, _ := s.fullRunHelper(c, `{
928 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
931 "mounts": {"/tmp": {"kind": "tmp"} },
932 "output_path": "/tmp",
934 "runtime_constraints": {}
935 }`, nil, 0, func(t *TestDockerClient) {
936 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
940 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
941 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
942 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
945 func (s *TestSuite) TestStopOnSignal(c *C) {
946 s.testStopContainer(c, func(cr *ContainerRunner) {
948 for !s.docker.calledWait {
949 time.Sleep(time.Millisecond)
951 cr.SigChan <- syscall.SIGINT
956 func (s *TestSuite) TestStopOnArvMountDeath(c *C) {
957 s.testStopContainer(c, func(cr *ContainerRunner) {
958 cr.ArvMountExit = make(chan error)
960 cr.ArvMountExit <- exec.Command("true").Run()
961 close(cr.ArvMountExit)
966 func (s *TestSuite) testStopContainer(c *C, setup func(cr *ContainerRunner)) {
968 "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
969 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
972 "mounts": {"/tmp": {"kind": "tmp"} },
973 "output_path": "/tmp",
975 "runtime_constraints": {}
978 rec := arvados.Container{}
979 err := json.Unmarshal([]byte(record), &rec)
982 s.docker.fn = func(t *TestDockerClient) {
984 t.logWriter.Write(dockerLog(1, "foo\n"))
987 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
989 api := &ArvTestClient{Container: rec}
990 kc := &KeepTestClient{}
992 cr := NewContainerRunner(api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
993 cr.RunArvMount = func([]string, string) (*exec.Cmd, error) { return nil, nil }
994 cr.MkArvClient = func(token string) (IArvadosClient, error) {
995 return &ArvTestClient{}, nil
999 done := make(chan error)
1004 case <-time.After(20 * time.Second):
1005 pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
1006 c.Fatal("timed out")
1010 for k, v := range api.Logs {
1015 c.Check(api.CalledWith("container.log", nil), NotNil)
1016 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1017 c.Check(api.Logs["stdout"].String(), Matches, "(?ms).*foo\n$")
1020 func (s *TestSuite) TestFullRunSetEnv(c *C) {
1021 api, _, _ := s.fullRunHelper(c, `{
1022 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1023 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1025 "environment": {"FROBIZ": "bilbo"},
1026 "mounts": {"/tmp": {"kind": "tmp"} },
1027 "output_path": "/tmp",
1029 "runtime_constraints": {}
1030 }`, nil, 0, func(t *TestDockerClient) {
1031 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1035 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1036 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1037 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)
1040 type ArvMountCmdLine struct {
1045 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
1051 func stubCert(temp string) string {
1052 path := temp + "/ca-certificates.crt"
1053 crt, _ := os.Create(path)
1055 arvadosclient.CertFiles = []string{path}
1059 func (s *TestSuite) TestSetupMounts(c *C) {
1060 api := &ArvTestClient{}
1061 kc := &KeepTestClient{}
1063 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1064 am := &ArvMountCmdLine{}
1065 cr.RunArvMount = am.ArvMountTest
1067 realTemp, err := ioutil.TempDir("", "crunchrun_test1-")
1068 c.Assert(err, IsNil)
1069 certTemp, err := ioutil.TempDir("", "crunchrun_test2-")
1070 c.Assert(err, IsNil)
1071 stubCertPath := stubCert(certTemp)
1073 cr.parentTemp = realTemp
1075 defer os.RemoveAll(realTemp)
1076 defer os.RemoveAll(certTemp)
1079 cr.MkTempDir = func(_ string, prefix string) (string, error) {
1081 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
1082 err := os.Mkdir(d, os.ModePerm)
1083 if err != nil && strings.Contains(err.Error(), ": file exists") {
1084 // Test case must have pre-populated the tempdir
1090 checkEmpty := func() {
1091 // Should be deleted.
1092 _, err := os.Stat(realTemp)
1093 c.Assert(os.IsNotExist(err), Equals, true)
1095 // Now recreate it for the next test.
1096 c.Assert(os.Mkdir(realTemp, 0777), IsNil)
1101 cr.ArvMountPoint = ""
1102 cr.Container.Mounts = make(map[string]arvados.Mount)
1103 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1104 cr.OutputPath = "/tmp"
1105 cr.statInterval = 5 * time.Second
1106 err := cr.SetupMounts()
1108 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1109 "--read-write", "--crunchstat-interval=5",
1110 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1111 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp"})
1112 os.RemoveAll(cr.ArvMountPoint)
1119 cr.ArvMountPoint = ""
1120 cr.Container.Mounts = make(map[string]arvados.Mount)
1121 cr.Container.Mounts["/out"] = arvados.Mount{Kind: "tmp"}
1122 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1123 cr.OutputPath = "/out"
1125 err := cr.SetupMounts()
1127 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1128 "--read-write", "--crunchstat-interval=5",
1129 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1130 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/out", realTemp + "/tmp3:/tmp"})
1131 os.RemoveAll(cr.ArvMountPoint)
1138 cr.ArvMountPoint = ""
1139 cr.Container.Mounts = make(map[string]arvados.Mount)
1140 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1141 cr.OutputPath = "/tmp"
1144 cr.Container.RuntimeConstraints.API = &apiflag
1146 err := cr.SetupMounts()
1148 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1149 "--read-write", "--crunchstat-interval=5",
1150 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1151 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", stubCertPath + ":/etc/arvados/ca-certificates.crt:ro"})
1152 os.RemoveAll(cr.ArvMountPoint)
1161 cr.ArvMountPoint = ""
1162 cr.Container.Mounts = map[string]arvados.Mount{
1163 "/keeptmp": {Kind: "collection", Writable: true},
1165 cr.OutputPath = "/keeptmp"
1167 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1169 err := cr.SetupMounts()
1171 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1172 "--read-write", "--crunchstat-interval=5",
1173 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1174 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/tmp0:/keeptmp"})
1175 os.RemoveAll(cr.ArvMountPoint)
1182 cr.ArvMountPoint = ""
1183 cr.Container.Mounts = map[string]arvados.Mount{
1184 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1185 "/keepout": {Kind: "collection", Writable: true},
1187 cr.OutputPath = "/keepout"
1189 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1190 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1192 err := cr.SetupMounts()
1194 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1195 "--read-write", "--crunchstat-interval=5",
1196 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1197 sort.StringSlice(cr.Binds).Sort()
1198 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1199 realTemp + "/keep1/tmp0:/keepout"})
1200 os.RemoveAll(cr.ArvMountPoint)
1207 cr.ArvMountPoint = ""
1208 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
1209 cr.Container.Mounts = map[string]arvados.Mount{
1210 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1211 "/keepout": {Kind: "collection", Writable: true},
1213 cr.OutputPath = "/keepout"
1215 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1216 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1218 err := cr.SetupMounts()
1220 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1221 "--read-write", "--crunchstat-interval=5",
1222 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1223 sort.StringSlice(cr.Binds).Sort()
1224 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1225 realTemp + "/keep1/tmp0:/keepout"})
1226 os.RemoveAll(cr.ArvMountPoint)
1231 for _, test := range []struct {
1235 {in: "foo", out: `"foo"`},
1236 {in: nil, out: `null`},
1237 {in: map[string]int64{"foo": 123456789123456789}, out: `{"foo":123456789123456789}`},
1240 cr.ArvMountPoint = ""
1241 cr.Container.Mounts = map[string]arvados.Mount{
1242 "/mnt/test.json": {Kind: "json", Content: test.in},
1244 err := cr.SetupMounts()
1246 sort.StringSlice(cr.Binds).Sort()
1247 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/json2/mountdata.json:/mnt/test.json:ro"})
1248 content, err := ioutil.ReadFile(realTemp + "/json2/mountdata.json")
1250 c.Check(content, DeepEquals, []byte(test.out))
1251 os.RemoveAll(cr.ArvMountPoint)
1256 for _, test := range []struct {
1260 {in: "foo", out: `foo`},
1261 {in: nil, out: "error"},
1262 {in: map[string]int64{"foo": 123456789123456789}, out: "error"},
1265 cr.ArvMountPoint = ""
1266 cr.Container.Mounts = map[string]arvados.Mount{
1267 "/mnt/test.txt": {Kind: "text", Content: test.in},
1269 err := cr.SetupMounts()
1270 if test.out == "error" {
1271 c.Check(err.Error(), Equals, "content for mount \"/mnt/test.txt\" must be a string")
1274 sort.StringSlice(cr.Binds).Sort()
1275 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/text2/mountdata.text:/mnt/test.txt:ro"})
1276 content, err := ioutil.ReadFile(realTemp + "/text2/mountdata.text")
1278 c.Check(content, DeepEquals, []byte(test.out))
1280 os.RemoveAll(cr.ArvMountPoint)
1285 // Read-only mount points are allowed underneath output_dir mount point
1288 cr.ArvMountPoint = ""
1289 cr.Container.Mounts = make(map[string]arvados.Mount)
1290 cr.Container.Mounts = map[string]arvados.Mount{
1291 "/tmp": {Kind: "tmp"},
1292 "/tmp/foo": {Kind: "collection"},
1294 cr.OutputPath = "/tmp"
1296 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1298 err := cr.SetupMounts()
1300 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1301 "--read-write", "--crunchstat-interval=5",
1302 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1303 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", realTemp + "/keep1/tmp0:/tmp/foo:ro"})
1304 os.RemoveAll(cr.ArvMountPoint)
1309 // Writable mount points copied to output_dir mount point
1312 cr.ArvMountPoint = ""
1313 cr.Container.Mounts = make(map[string]arvados.Mount)
1314 cr.Container.Mounts = map[string]arvados.Mount{
1315 "/tmp": {Kind: "tmp"},
1316 "/tmp/foo": {Kind: "collection",
1317 PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53",
1319 "/tmp/bar": {Kind: "collection",
1320 PortableDataHash: "59389a8f9ee9d399be35462a0f92541d+53",
1324 cr.OutputPath = "/tmp"
1326 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1327 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz", os.ModePerm)
1329 rf, _ := os.Create(realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz/quux")
1330 rf.Write([]byte("bar"))
1333 err := cr.SetupMounts()
1335 _, err = os.Stat(cr.HostOutputDir + "/foo")
1337 _, err = os.Stat(cr.HostOutputDir + "/bar/quux")
1339 os.RemoveAll(cr.ArvMountPoint)
1344 // Only mount points of kind 'collection' are allowed underneath output_dir mount point
1347 cr.ArvMountPoint = ""
1348 cr.Container.Mounts = make(map[string]arvados.Mount)
1349 cr.Container.Mounts = map[string]arvados.Mount{
1350 "/tmp": {Kind: "tmp"},
1351 "/tmp/foo": {Kind: "tmp"},
1353 cr.OutputPath = "/tmp"
1355 err := cr.SetupMounts()
1356 c.Check(err, NotNil)
1357 c.Check(err, ErrorMatches, `Only mount points of kind 'collection', 'text' or 'json' are supported underneath the output_path.*`)
1358 os.RemoveAll(cr.ArvMountPoint)
1363 // Only mount point of kind 'collection' is allowed for stdin
1366 cr.ArvMountPoint = ""
1367 cr.Container.Mounts = make(map[string]arvados.Mount)
1368 cr.Container.Mounts = map[string]arvados.Mount{
1369 "stdin": {Kind: "tmp"},
1372 err := cr.SetupMounts()
1373 c.Check(err, NotNil)
1374 c.Check(err, ErrorMatches, `Unsupported mount kind 'tmp' for stdin.*`)
1375 os.RemoveAll(cr.ArvMountPoint)
1383 cr.ArvMountPoint = ""
1384 (*GitMountSuite)(nil).useTestGitServer(c)
1385 cr.token = arvadostest.ActiveToken
1386 cr.Container.Mounts = make(map[string]arvados.Mount)
1387 cr.Container.Mounts = map[string]arvados.Mount{
1390 UUID: arvadostest.Repository2UUID,
1391 Commit: "fd3531f42995344f36c30b79f55f27b502f3d344",
1396 UUID: arvadostest.Repository2UUID,
1397 Commit: "5ebfab0522851df01fec11ec55a6d0f4877b542e",
1401 cr.OutputPath = "/tmp"
1403 err := cr.SetupMounts()
1406 // dirMap[mountpoint] == tmpdir
1407 dirMap := make(map[string]string)
1408 for _, bind := range cr.Binds {
1409 tokens := strings.Split(bind, ":")
1410 dirMap[tokens[1]] = tokens[0]
1412 if cr.Container.Mounts[tokens[1]].Writable {
1413 c.Check(len(tokens), Equals, 2)
1415 c.Check(len(tokens), Equals, 3)
1416 c.Check(tokens[2], Equals, "ro")
1420 data, err := ioutil.ReadFile(dirMap["/tip"] + "/dir1/dir2/file with mode 0644")
1422 c.Check(string(data), Equals, "\000\001\002\003")
1423 _, err = ioutil.ReadFile(dirMap["/tip"] + "/file only on testbranch")
1424 c.Check(err, FitsTypeOf, &os.PathError{})
1425 c.Check(os.IsNotExist(err), Equals, true)
1427 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/dir1/dir2/file with mode 0644")
1429 c.Check(string(data), Equals, "\000\001\002\003")
1430 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/file only on testbranch")
1432 c.Check(string(data), Equals, "testfile\n")
1439 func (s *TestSuite) TestStdout(c *C) {
1441 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1442 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1444 "environment": {"FROBIZ": "bilbo"},
1445 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1446 "output_path": "/tmp",
1448 "runtime_constraints": {}
1451 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1452 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1456 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1457 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1458 c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1461 // Used by the TestStdoutWithWrongPath*()
1462 func (s *TestSuite) stdoutErrorRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, err error) {
1463 rec := arvados.Container{}
1464 err = json.Unmarshal([]byte(record), &rec)
1468 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
1470 api = &ArvTestClient{Container: rec}
1471 kc := &KeepTestClient{}
1473 cr = NewContainerRunner(api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1474 am := &ArvMountCmdLine{}
1475 cr.RunArvMount = am.ArvMountTest
1476 cr.MkArvClient = func(token string) (IArvadosClient, error) {
1477 return &ArvTestClient{}, nil
1484 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1485 _, _, err := s.stdoutErrorRunHelper(c, `{
1486 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1487 "output_path": "/tmp"
1488 }`, func(t *TestDockerClient) {})
1490 c.Check(err, NotNil)
1491 c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
1494 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1495 _, _, err := s.stdoutErrorRunHelper(c, `{
1496 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1497 "output_path": "/tmp"
1498 }`, func(t *TestDockerClient) {})
1500 c.Check(err, NotNil)
1501 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'tmp' for stdout"), Equals, true)
1504 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1505 _, _, err := s.stdoutErrorRunHelper(c, `{
1506 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1507 "output_path": "/tmp"
1508 }`, func(t *TestDockerClient) {})
1510 c.Check(err, NotNil)
1511 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'collection' for stdout"), Equals, true)
1514 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1515 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1516 defer os.Unsetenv("ARVADOS_API_HOST")
1517 api, _, _ := s.fullRunHelper(c, `{
1518 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1519 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1522 "mounts": {"/tmp": {"kind": "tmp"} },
1523 "output_path": "/tmp",
1525 "runtime_constraints": {"API": true}
1526 }`, nil, 0, func(t *TestDockerClient) {
1527 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
1531 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1532 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1533 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "test.arvados.org\n"), Equals, true)
1534 c.Check(api.CalledWith("container.output", "d41d8cd98f00b204e9800998ecf8427e+0"), NotNil)
1537 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1538 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1539 defer os.Unsetenv("ARVADOS_API_HOST")
1540 api, _, _ := s.fullRunHelper(c, `{
1541 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1542 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1545 "mounts": {"/tmp": {"kind": "tmp"} },
1546 "output_path": "/tmp",
1548 "runtime_constraints": {"API": true}
1549 }`, nil, 0, func(t *TestDockerClient) {
1550 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
1554 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1555 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1556 c.Check(api.CalledWith("container.output", "d4ab34d3d4f8a72f5c4973051ae69fab+122"), NotNil)
1559 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1561 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1562 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1564 "environment": {"FROBIZ": "bilbo"},
1566 "/tmp": {"kind": "tmp"},
1567 "/tmp/foo": {"kind": "collection",
1568 "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1569 "exclude_from_output": true
1571 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1573 "output_path": "/tmp",
1575 "runtime_constraints": {}
1578 extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1580 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1581 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1585 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1586 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1587 c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1590 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1592 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1593 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1595 "environment": {"FROBIZ": "bilbo"},
1597 "/tmp": {"kind": "tmp"},
1598 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1599 "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1600 "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1601 "/tmp/foo/baz/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1602 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1604 "output_path": "/tmp",
1606 "runtime_constraints": {}
1609 extraMounts := []string{
1610 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1611 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1612 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1615 api, runner, realtemp := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1616 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1620 c.Check(runner.Binds, DeepEquals, []string{realtemp + "/tmp2:/tmp",
1621 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt:/tmp/foo/bar:ro",
1622 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt:/tmp/foo/baz/sub2file2:ro",
1623 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1:/tmp/foo/sub1:ro",
1624 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt:/tmp/foo/sub1file2:ro",
1627 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1628 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1629 for _, v := range api.Content {
1630 if v["collection"] != nil {
1631 c.Check(v["ensure_unique_name"], Equals, true)
1632 collection := v["collection"].(arvadosclient.Dict)
1633 if strings.Index(collection["name"].(string), "output") == 0 {
1634 manifest := collection["manifest_text"].(string)
1636 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1637 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 9:18:bar 9:18:sub1file2
1638 ./foo/baz 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2
1639 ./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1640 ./foo/sub1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1647 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
1649 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1650 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1652 "environment": {"FROBIZ": "bilbo"},
1654 "/tmp": {"kind": "tmp"},
1655 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt"},
1656 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1658 "output_path": "/tmp",
1660 "runtime_constraints": {}
1663 extraMounts := []string{
1664 "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1667 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1668 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1672 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1673 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1674 for _, v := range api.Content {
1675 if v["collection"] != nil {
1676 collection := v["collection"].(arvadosclient.Dict)
1677 if strings.Index(collection["name"].(string), "output") == 0 {
1678 manifest := collection["manifest_text"].(string)
1680 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1681 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 10:17:bar
1688 func (s *TestSuite) TestOutputSymlinkToInput(c *C) {
1690 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1691 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1693 "environment": {"FROBIZ": "bilbo"},
1695 "/tmp": {"kind": "tmp"},
1696 "/keep/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path": "/subdir1/file2_in_subdir1.txt"},
1697 "/keep/foo2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367"}
1699 "output_path": "/tmp",
1701 "runtime_constraints": {}
1704 extraMounts := []string{
1705 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1708 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1709 os.Symlink("/keep/foo/sub1file2", t.realTemp+"/tmp2/baz")
1710 os.Symlink("/keep/foo2/subdir1/file2_in_subdir1.txt", t.realTemp+"/tmp2/baz2")
1711 os.Symlink("/keep/foo2/subdir1", t.realTemp+"/tmp2/baz3")
1712 os.Mkdir(t.realTemp+"/tmp2/baz4", 0700)
1713 os.Symlink("/keep/foo2/subdir1/file2_in_subdir1.txt", t.realTemp+"/tmp2/baz4/baz5")
1717 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1718 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1719 for _, v := range api.Content {
1720 if v["collection"] != nil {
1721 collection := v["collection"].(arvadosclient.Dict)
1722 if strings.Index(collection["name"].(string), "output") == 0 {
1723 manifest := collection["manifest_text"].(string)
1724 c.Check(manifest, Equals, `. 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:baz 9:18:baz2
1725 ./baz3 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1726 ./baz3/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1727 ./baz4 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:baz5
1734 func (s *TestSuite) TestOutputError(c *C) {
1736 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1737 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1739 "environment": {"FROBIZ": "bilbo"},
1741 "/tmp": {"kind": "tmp"}
1743 "output_path": "/tmp",
1745 "runtime_constraints": {}
1748 extraMounts := []string{}
1750 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1751 os.Symlink("/etc/hosts", t.realTemp+"/tmp2/baz")
1755 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1758 func (s *TestSuite) TestOutputSymlinkToOutput(c *C) {
1760 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1761 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1763 "environment": {"FROBIZ": "bilbo"},
1765 "/tmp": {"kind": "tmp"}
1767 "output_path": "/tmp",
1769 "runtime_constraints": {}
1772 extraMounts := []string{}
1774 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1775 rf, _ := os.Create(t.realTemp + "/tmp2/realfile")
1776 rf.Write([]byte("foo"))
1779 os.Mkdir(t.realTemp+"/tmp2/realdir", 0700)
1780 rf, _ = os.Create(t.realTemp + "/tmp2/realdir/subfile")
1781 rf.Write([]byte("bar"))
1784 os.Symlink("/tmp/realfile", t.realTemp+"/tmp2/file1")
1785 os.Symlink("realfile", t.realTemp+"/tmp2/file2")
1786 os.Symlink("/tmp/file1", t.realTemp+"/tmp2/file3")
1787 os.Symlink("file2", t.realTemp+"/tmp2/file4")
1788 os.Symlink("realdir", t.realTemp+"/tmp2/dir1")
1789 os.Symlink("/tmp/realdir", t.realTemp+"/tmp2/dir2")
1793 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1794 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1795 for _, v := range api.Content {
1796 if v["collection"] != nil {
1797 collection := v["collection"].(arvadosclient.Dict)
1798 if strings.Index(collection["name"].(string), "output") == 0 {
1799 manifest := collection["manifest_text"].(string)
1800 c.Check(manifest, Equals,
1801 `. 7a2c86e102dcc231bd232aad99686dfa+15 0:3:file1 3:3:file2 6:3:file3 9:3:file4 12:3:realfile
1802 ./dir1 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1803 ./dir2 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1804 ./realdir 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1811 func (s *TestSuite) TestStdinCollectionMountPoint(c *C) {
1813 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1814 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1816 "environment": {"FROBIZ": "bilbo"},
1818 "/tmp": {"kind": "tmp"},
1819 "stdin": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/file1_in_main.txt"},
1820 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1822 "output_path": "/tmp",
1824 "runtime_constraints": {}
1827 extraMounts := []string{
1828 "b0def87f80dd594d4675809e83bd4f15+367/file1_in_main.txt",
1831 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1832 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1836 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1837 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1838 for _, v := range api.Content {
1839 if v["collection"] != nil {
1840 collection := v["collection"].(arvadosclient.Dict)
1841 if strings.Index(collection["name"].(string), "output") == 0 {
1842 manifest := collection["manifest_text"].(string)
1843 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1850 func (s *TestSuite) TestStdinJsonMountPoint(c *C) {
1852 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1853 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1855 "environment": {"FROBIZ": "bilbo"},
1857 "/tmp": {"kind": "tmp"},
1858 "stdin": {"kind": "json", "content": "foo"},
1859 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1861 "output_path": "/tmp",
1863 "runtime_constraints": {}
1866 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1867 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1871 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1872 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1873 for _, v := range api.Content {
1874 if v["collection"] != nil {
1875 collection := v["collection"].(arvadosclient.Dict)
1876 if strings.Index(collection["name"].(string), "output") == 0 {
1877 manifest := collection["manifest_text"].(string)
1878 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1885 func (s *TestSuite) TestStderrMount(c *C) {
1886 api, _, _ := s.fullRunHelper(c, `{
1887 "command": ["/bin/sh", "-c", "echo hello;exit 1"],
1888 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1891 "mounts": {"/tmp": {"kind": "tmp"},
1892 "stdout": {"kind": "file", "path": "/tmp/a/out.txt"},
1893 "stderr": {"kind": "file", "path": "/tmp/b/err.txt"}},
1894 "output_path": "/tmp",
1896 "runtime_constraints": {}
1897 }`, nil, 1, func(t *TestDockerClient) {
1898 t.logWriter.Write(dockerLog(1, "hello\n"))
1899 t.logWriter.Write(dockerLog(2, "oops\n"))
1903 final := api.CalledWith("container.state", "Complete")
1904 c.Assert(final, NotNil)
1905 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1906 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1908 c.Check(api.CalledWith("collection.manifest_text", "./a b1946ac92492d2347c6235b4d2611184+6 0:6:out.txt\n./b 38af5c54926b620264ab1501150cf189+5 0:5:err.txt\n"), NotNil)
1911 func (s *TestSuite) TestNumberRoundTrip(c *C) {
1912 kc := &KeepTestClient{}
1914 cr := NewContainerRunner(&ArvTestClient{callraw: true}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1915 cr.fetchContainerRecord()
1917 jsondata, err := json.Marshal(cr.Container.Mounts["/json"].Content)
1920 c.Check(string(jsondata), Equals, `{"number":123456789123456789}`)
1923 func (s *TestSuite) TestEvalSymlinks(c *C) {
1924 kc := &KeepTestClient{}
1926 cr := NewContainerRunner(&ArvTestClient{callraw: true}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1928 realTemp, err := ioutil.TempDir("", "crunchrun_test-")
1929 c.Assert(err, IsNil)
1930 defer os.RemoveAll(realTemp)
1932 cr.HostOutputDir = realTemp
1934 // Absolute path outside output dir
1935 os.Symlink("/etc/passwd", realTemp+"/p1")
1937 // Relative outside output dir
1938 os.Symlink("../zip", realTemp+"/p2")
1940 // Circular references
1941 os.Symlink("p4", realTemp+"/p3")
1942 os.Symlink("p5", realTemp+"/p4")
1943 os.Symlink("p3", realTemp+"/p5")
1945 // Target doesn't exist
1946 os.Symlink("p99", realTemp+"/p6")
1948 for _, v := range []string{"p1", "p2", "p3", "p4", "p5"} {
1949 info, err := os.Lstat(realTemp + "/" + v)
1950 c.Assert(err, IsNil)
1951 _, _, _, err = cr.derefOutputSymlink(realTemp+"/"+v, info)
1952 c.Assert(err, NotNil)
1956 func (s *TestSuite) TestEvalSymlinkDir(c *C) {
1957 kc := &KeepTestClient{}
1959 cr := NewContainerRunner(&ArvTestClient{callraw: true}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1961 realTemp, err := ioutil.TempDir("", "crunchrun_test-")
1962 c.Assert(err, IsNil)
1963 defer os.RemoveAll(realTemp)
1965 cr.HostOutputDir = realTemp
1967 // Absolute path outside output dir
1968 os.Symlink(".", realTemp+"/loop")
1971 info, err := os.Lstat(realTemp + "/" + v)
1972 _, err = cr.UploadOutputFile(realTemp+"/"+v, info, err, []string{}, nil, "", "", 0)
1973 c.Assert(err, NotNil)
1976 func (s *TestSuite) TestFullBrokenDocker1(c *C) {
1977 tf, err := ioutil.TempFile("", "brokenNodeHook-")
1978 c.Assert(err, IsNil)
1979 defer os.Remove(tf.Name())
1981 tf.Write([]byte(`#!/bin/sh
1985 os.Chmod(tf.Name(), 0700)
1988 brokenNodeHook = &ech
1990 api, _, _ := s.fullRunHelper(c, `{
1991 "command": ["echo", "hello world"],
1992 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1995 "mounts": {"/tmp": {"kind": "tmp"} },
1996 "output_path": "/tmp",
1998 "runtime_constraints": {}
1999 }`, nil, 2, func(t *TestDockerClient) {
2000 t.logWriter.Write(dockerLog(1, "hello world\n"))
2004 c.Check(api.CalledWith("container.state", "Queued"), NotNil)
2005 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
2006 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Running broken node hook.*")
2007 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*killme.*")
2011 func (s *TestSuite) TestFullBrokenDocker2(c *C) {
2013 brokenNodeHook = &ech
2015 api, _, _ := s.fullRunHelper(c, `{
2016 "command": ["echo", "hello world"],
2017 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2020 "mounts": {"/tmp": {"kind": "tmp"} },
2021 "output_path": "/tmp",
2023 "runtime_constraints": {}
2024 }`, nil, 2, func(t *TestDockerClient) {
2025 t.logWriter.Write(dockerLog(1, "hello world\n"))
2029 c.Check(api.CalledWith("container.state", "Queued"), NotNil)
2030 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
2031 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*No broken node hook.*")
2034 func (s *TestSuite) TestFullBrokenDocker3(c *C) {
2036 brokenNodeHook = &ech
2038 api, _, _ := s.fullRunHelper(c, `{
2039 "command": ["echo", "hello world"],
2040 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2043 "mounts": {"/tmp": {"kind": "tmp"} },
2044 "output_path": "/tmp",
2046 "runtime_constraints": {}
2047 }`, nil, 3, func(t *TestDockerClient) {
2048 t.logWriter.Write(dockerLog(1, "hello world\n"))
2052 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2053 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
2056 func (s *TestSuite) TestBadCommand1(c *C) {
2058 brokenNodeHook = &ech
2060 api, _, _ := s.fullRunHelper(c, `{
2061 "command": ["echo", "hello world"],
2062 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2065 "mounts": {"/tmp": {"kind": "tmp"} },
2066 "output_path": "/tmp",
2068 "runtime_constraints": {}
2069 }`, nil, 4, func(t *TestDockerClient) {
2070 t.logWriter.Write(dockerLog(1, "hello world\n"))
2074 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2075 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2078 func (s *TestSuite) TestBadCommand2(c *C) {
2080 brokenNodeHook = &ech
2082 api, _, _ := s.fullRunHelper(c, `{
2083 "command": ["echo", "hello world"],
2084 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2087 "mounts": {"/tmp": {"kind": "tmp"} },
2088 "output_path": "/tmp",
2090 "runtime_constraints": {}
2091 }`, nil, 5, func(t *TestDockerClient) {
2092 t.logWriter.Write(dockerLog(1, "hello world\n"))
2096 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2097 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2100 func (s *TestSuite) TestBadCommand3(c *C) {
2102 brokenNodeHook = &ech
2104 api, _, _ := s.fullRunHelper(c, `{
2105 "command": ["echo", "hello world"],
2106 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2109 "mounts": {"/tmp": {"kind": "tmp"} },
2110 "output_path": "/tmp",
2112 "runtime_constraints": {}
2113 }`, nil, 6, func(t *TestDockerClient) {
2114 t.logWriter.Write(dockerLog(1, "hello world\n"))
2118 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2119 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2122 func (s *TestSuite) TestSecretTextMountPoint(c *C) {
2123 // under normal mounts, gets captured in output, oops
2125 "command": ["true"],
2126 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2129 "/tmp": {"kind": "tmp"},
2130 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2134 "output_path": "/tmp",
2136 "runtime_constraints": {}
2139 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2140 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2142 c.Check(content, DeepEquals, []byte("mypassword"))
2146 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2147 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2148 c.Check(api.CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), NotNil)
2149 c.Check(api.CalledWith("collection.manifest_text", ""), IsNil)
2151 // under secret mounts, not captured in output
2153 "command": ["true"],
2154 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2157 "/tmp": {"kind": "tmp"}
2160 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2162 "output_path": "/tmp",
2164 "runtime_constraints": {}
2167 api, _, _ = s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2168 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2170 c.Check(content, DeepEquals, []byte("mypassword"))
2174 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2175 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2176 c.Check(api.CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), IsNil)
2177 c.Check(api.CalledWith("collection.manifest_text", ""), NotNil)