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{})
420 _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
423 cr.Container.ContainerImage = hwPDH
425 // (1) Test loading image from keep
426 c.Check(kc.Called, Equals, false)
427 c.Check(cr.ContainerConfig.Image, Equals, "")
433 cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
436 c.Check(kc.Called, Equals, true)
437 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
439 _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
442 // (2) Test using image that's already loaded
444 cr.ContainerConfig.Image = ""
448 c.Check(kc.Called, Equals, false)
449 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
453 type ArvErrorTestClient struct{}
455 func (ArvErrorTestClient) Create(resourceType string,
456 parameters arvadosclient.Dict,
457 output interface{}) error {
461 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
462 return errors.New("ArvError")
465 func (ArvErrorTestClient) CallRaw(method, resourceType, uuid, action string,
466 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
467 return nil, errors.New("ArvError")
470 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
471 return errors.New("ArvError")
474 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
478 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
479 return discoveryMap[key], nil
482 type KeepErrorTestClient struct{}
484 func (KeepErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
485 return "", 0, errors.New("KeepError")
488 func (KeepErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
489 return nil, errors.New("KeepError")
492 func (KeepErrorTestClient) ClearBlockCache() {
495 type KeepReadErrorTestClient struct{}
497 func (KeepReadErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
501 func (KeepReadErrorTestClient) ClearBlockCache() {
504 type ErrorReader struct {
508 func (ErrorReader) Read(p []byte) (n int, err error) {
509 return 0, errors.New("ErrorReader")
512 func (ErrorReader) Seek(int64, int) (int64, error) {
513 return 0, errors.New("ErrorReader")
516 func (KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
517 return ErrorReader{}, nil
520 func (s *TestSuite) TestLoadImageArvError(c *C) {
522 kc := &KeepTestClient{}
524 cr := NewContainerRunner(ArvErrorTestClient{}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
525 cr.Container.ContainerImage = hwPDH
527 err := cr.LoadImage()
528 c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
531 func (s *TestSuite) TestLoadImageKeepError(c *C) {
533 cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
534 cr.Container.ContainerImage = hwPDH
536 err := cr.LoadImage()
537 c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
540 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
541 // (3) Collection doesn't contain image
542 cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
543 cr.Container.ContainerImage = otherPDH
545 err := cr.LoadImage()
546 c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
549 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
550 // (4) Collection doesn't contain image
551 cr := NewContainerRunner(&ArvTestClient{}, KeepReadErrorTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
552 cr.Container.ContainerImage = hwPDH
554 err := cr.LoadImage()
558 type ClosableBuffer struct {
562 func (*ClosableBuffer) Close() error {
566 type TestLogs struct {
567 Stdout ClosableBuffer
568 Stderr ClosableBuffer
571 func (tl *TestLogs) NewTestLoggingWriter(logstr string) io.WriteCloser {
572 if logstr == "stdout" {
575 if logstr == "stderr" {
581 func dockerLog(fd byte, msg string) []byte {
583 header := make([]byte, 8+len(by))
585 header[7] = byte(len(by))
590 func (s *TestSuite) TestRunContainer(c *C) {
591 s.docker.fn = func(t *TestDockerClient) {
592 t.logWriter.Write(dockerLog(1, "Hello world\n"))
595 kc := &KeepTestClient{}
597 cr := NewContainerRunner(&ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
600 cr.NewLogWriter = logs.NewTestLoggingWriter
601 cr.Container.ContainerImage = hwPDH
602 cr.Container.Command = []string{"./hw"}
603 err := cr.LoadImage()
606 err = cr.CreateContainer()
609 err = cr.StartContainer()
612 err = cr.WaitFinish()
615 c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
616 c.Check(logs.Stderr.String(), Equals, "")
619 func (s *TestSuite) TestCommitLogs(c *C) {
620 api := &ArvTestClient{}
621 kc := &KeepTestClient{}
623 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
624 cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
626 cr.CrunchLog.Print("Hello world!")
627 cr.CrunchLog.Print("Goodbye")
628 cr.finalState = "Complete"
630 err := cr.CommitLogs()
633 c.Check(api.Calls, Equals, 2)
634 c.Check(api.Content[1]["ensure_unique_name"], Equals, true)
635 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
636 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
637 c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
640 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
641 api := &ArvTestClient{}
642 kc := &KeepTestClient{}
644 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
646 err := cr.UpdateContainerRunning()
649 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
652 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
653 api := &ArvTestClient{}
654 kc := &KeepTestClient{}
656 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
658 cr.LogsPDH = new(string)
659 *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
661 cr.ExitCode = new(int)
663 cr.finalState = "Complete"
665 err := cr.UpdateContainerFinal()
668 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
669 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
670 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
673 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
674 api := &ArvTestClient{}
675 kc := &KeepTestClient{}
677 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
679 cr.finalState = "Cancelled"
681 err := cr.UpdateContainerFinal()
684 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
685 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
686 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
689 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
690 // dress rehearsal of the Run() function, starting from a JSON container record.
691 func (s *TestSuite) fullRunHelper(c *C, record string, extraMounts []string, exitCode int, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, realTemp string) {
692 rec := arvados.Container{}
693 err := json.Unmarshal([]byte(record), &rec)
697 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
699 err = json.Unmarshal([]byte(record), &sm)
701 secretMounts, err := json.Marshal(sm)
702 log.Printf("%q %q", sm, secretMounts)
705 s.docker.exitCode = exitCode
707 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
709 api = &ArvTestClient{Container: rec}
711 kc := &KeepTestClient{}
713 cr = NewContainerRunner(api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
714 cr.statInterval = 100 * time.Millisecond
715 am := &ArvMountCmdLine{}
716 cr.RunArvMount = am.ArvMountTest
718 realTemp, err = ioutil.TempDir("", "crunchrun_test1-")
720 defer os.RemoveAll(realTemp)
722 s.docker.realTemp = realTemp
725 cr.MkTempDir = func(_ string, prefix string) (string, error) {
727 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, tempcount)
728 err := os.Mkdir(d, os.ModePerm)
729 if err != nil && strings.Contains(err.Error(), ": file exists") {
730 // Test case must have pre-populated the tempdir
735 cr.MkArvClient = func(token string) (IArvadosClient, error) {
736 return &ArvTestClient{secretMounts: secretMounts}, nil
739 if extraMounts != nil && len(extraMounts) > 0 {
740 err := cr.SetupArvMountPoint("keep")
743 for _, m := range extraMounts {
744 os.MkdirAll(cr.ArvMountPoint+"/by_id/"+m, os.ModePerm)
749 if api.CalledWith("container.state", "Complete") != nil {
753 c.Check(api.WasSetRunning, Equals, true)
754 c.Check(api.Content[api.Calls-2]["container"].(arvadosclient.Dict)["log"], NotNil)
758 for k, v := range api.Logs {
767 func (s *TestSuite) TestFullRunHello(c *C) {
768 api, _, _ := s.fullRunHelper(c, `{
769 "command": ["echo", "hello world"],
770 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
773 "mounts": {"/tmp": {"kind": "tmp"} },
774 "output_path": "/tmp",
776 "runtime_constraints": {}
777 }`, nil, 0, func(t *TestDockerClient) {
778 t.logWriter.Write(dockerLog(1, "hello world\n"))
782 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
783 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
784 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
788 func (s *TestSuite) TestCrunchstat(c *C) {
789 api, _, _ := s.fullRunHelper(c, `{
790 "command": ["sleep", "1"],
791 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
794 "mounts": {"/tmp": {"kind": "tmp"} },
795 "output_path": "/tmp",
797 "runtime_constraints": {}
798 }`, nil, 0, func(t *TestDockerClient) {
799 time.Sleep(time.Second)
803 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
804 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
806 // We didn't actually start a container, so crunchstat didn't
807 // find accounting files and therefore didn't log any stats.
808 // It should have logged a "can't find accounting files"
809 // message after one poll interval, though, so we can confirm
811 c.Assert(api.Logs["crunchstat"], NotNil)
812 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
814 // The "files never appeared" log assures us that we called
815 // (*crunchstat.Reporter)Stop(), and that we set it up with
816 // the correct container ID "abcde":
817 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files never appeared for abcde\n`)
820 func (s *TestSuite) TestNodeInfoLog(c *C) {
821 os.Setenv("SLURMD_NODENAME", "compute2")
822 api, _, _ := s.fullRunHelper(c, `{
823 "command": ["sleep", "1"],
824 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
827 "mounts": {"/tmp": {"kind": "tmp"} },
828 "output_path": "/tmp",
830 "runtime_constraints": {}
832 func(t *TestDockerClient) {
833 time.Sleep(time.Second)
837 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
838 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
840 c.Assert(api.Logs["node"], NotNil)
841 json := api.Logs["node"].String()
842 c.Check(json, Matches, `(?ms).*"uuid": *"zzzzz-7ekkf-2z3mc76g2q73aio".*`)
843 c.Check(json, Matches, `(?ms).*"total_cpu_cores": *16.*`)
844 c.Check(json, Not(Matches), `(?ms).*"info":.*`)
846 c.Assert(api.Logs["node-info"], NotNil)
847 json = api.Logs["node-info"].String()
848 c.Check(json, Matches, `(?ms).*Host Information.*`)
849 c.Check(json, Matches, `(?ms).*CPU Information.*`)
850 c.Check(json, Matches, `(?ms).*Memory Information.*`)
851 c.Check(json, Matches, `(?ms).*Disk Space.*`)
852 c.Check(json, Matches, `(?ms).*Disk INodes.*`)
855 func (s *TestSuite) TestContainerRecordLog(c *C) {
856 api, _, _ := s.fullRunHelper(c, `{
857 "command": ["sleep", "1"],
858 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
861 "mounts": {"/tmp": {"kind": "tmp"} },
862 "output_path": "/tmp",
864 "runtime_constraints": {}
866 func(t *TestDockerClient) {
867 time.Sleep(time.Second)
871 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
872 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
874 c.Assert(api.Logs["container"], NotNil)
875 c.Check(api.Logs["container"].String(), Matches, `(?ms).*container_image.*`)
878 func (s *TestSuite) TestFullRunStderr(c *C) {
879 api, _, _ := s.fullRunHelper(c, `{
880 "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
881 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
884 "mounts": {"/tmp": {"kind": "tmp"} },
885 "output_path": "/tmp",
887 "runtime_constraints": {}
888 }`, nil, 1, func(t *TestDockerClient) {
889 t.logWriter.Write(dockerLog(1, "hello\n"))
890 t.logWriter.Write(dockerLog(2, "world\n"))
894 final := api.CalledWith("container.state", "Complete")
895 c.Assert(final, NotNil)
896 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
897 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
899 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
900 c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
903 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
904 api, _, _ := s.fullRunHelper(c, `{
906 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
909 "mounts": {"/tmp": {"kind": "tmp"} },
910 "output_path": "/tmp",
912 "runtime_constraints": {}
913 }`, nil, 0, func(t *TestDockerClient) {
914 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
918 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
919 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
920 c.Log(api.Logs["stdout"])
921 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
924 func (s *TestSuite) TestFullRunSetCwd(c *C) {
925 api, _, _ := s.fullRunHelper(c, `{
927 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
930 "mounts": {"/tmp": {"kind": "tmp"} },
931 "output_path": "/tmp",
933 "runtime_constraints": {}
934 }`, nil, 0, func(t *TestDockerClient) {
935 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
939 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
940 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
941 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
944 func (s *TestSuite) TestStopOnSignal(c *C) {
945 s.testStopContainer(c, func(cr *ContainerRunner) {
947 for !s.docker.calledWait {
948 time.Sleep(time.Millisecond)
950 cr.SigChan <- syscall.SIGINT
955 func (s *TestSuite) TestStopOnArvMountDeath(c *C) {
956 s.testStopContainer(c, func(cr *ContainerRunner) {
957 cr.ArvMountExit = make(chan error)
959 cr.ArvMountExit <- exec.Command("true").Run()
960 close(cr.ArvMountExit)
965 func (s *TestSuite) testStopContainer(c *C, setup func(cr *ContainerRunner)) {
967 "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
968 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
971 "mounts": {"/tmp": {"kind": "tmp"} },
972 "output_path": "/tmp",
974 "runtime_constraints": {}
977 rec := arvados.Container{}
978 err := json.Unmarshal([]byte(record), &rec)
981 s.docker.fn = func(t *TestDockerClient) {
983 t.logWriter.Write(dockerLog(1, "foo\n"))
986 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
988 api := &ArvTestClient{Container: rec}
989 kc := &KeepTestClient{}
991 cr := NewContainerRunner(api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
992 cr.RunArvMount = func([]string, string) (*exec.Cmd, error) { return nil, nil }
993 cr.MkArvClient = func(token string) (IArvadosClient, error) {
994 return &ArvTestClient{}, nil
998 done := make(chan error)
1003 case <-time.After(20 * time.Second):
1004 pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
1005 c.Fatal("timed out")
1009 for k, v := range api.Logs {
1014 c.Check(api.CalledWith("container.log", nil), NotNil)
1015 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1016 c.Check(api.Logs["stdout"].String(), Matches, "(?ms).*foo\n$")
1019 func (s *TestSuite) TestFullRunSetEnv(c *C) {
1020 api, _, _ := s.fullRunHelper(c, `{
1021 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1022 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1024 "environment": {"FROBIZ": "bilbo"},
1025 "mounts": {"/tmp": {"kind": "tmp"} },
1026 "output_path": "/tmp",
1028 "runtime_constraints": {}
1029 }`, nil, 0, func(t *TestDockerClient) {
1030 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1034 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1035 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1036 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)
1039 type ArvMountCmdLine struct {
1044 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
1050 func stubCert(temp string) string {
1051 path := temp + "/ca-certificates.crt"
1052 crt, _ := os.Create(path)
1054 arvadosclient.CertFiles = []string{path}
1058 func (s *TestSuite) TestSetupMounts(c *C) {
1059 api := &ArvTestClient{}
1060 kc := &KeepTestClient{}
1062 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1063 am := &ArvMountCmdLine{}
1064 cr.RunArvMount = am.ArvMountTest
1066 realTemp, err := ioutil.TempDir("", "crunchrun_test1-")
1067 c.Assert(err, IsNil)
1068 certTemp, err := ioutil.TempDir("", "crunchrun_test2-")
1069 c.Assert(err, IsNil)
1070 stubCertPath := stubCert(certTemp)
1072 cr.parentTemp = realTemp
1074 defer os.RemoveAll(realTemp)
1075 defer os.RemoveAll(certTemp)
1078 cr.MkTempDir = func(_ string, prefix string) (string, error) {
1080 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
1081 err := os.Mkdir(d, os.ModePerm)
1082 if err != nil && strings.Contains(err.Error(), ": file exists") {
1083 // Test case must have pre-populated the tempdir
1089 checkEmpty := func() {
1090 // Should be deleted.
1091 _, err := os.Stat(realTemp)
1092 c.Assert(os.IsNotExist(err), Equals, true)
1094 // Now recreate it for the next test.
1095 c.Assert(os.Mkdir(realTemp, 0777), IsNil)
1100 cr.ArvMountPoint = ""
1101 cr.Container.Mounts = make(map[string]arvados.Mount)
1102 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1103 cr.OutputPath = "/tmp"
1104 cr.statInterval = 5 * time.Second
1105 err := cr.SetupMounts()
1107 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1108 "--read-write", "--crunchstat-interval=5",
1109 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1110 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp"})
1111 os.RemoveAll(cr.ArvMountPoint)
1118 cr.ArvMountPoint = ""
1119 cr.Container.Mounts = make(map[string]arvados.Mount)
1120 cr.Container.Mounts["/out"] = arvados.Mount{Kind: "tmp"}
1121 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1122 cr.OutputPath = "/out"
1124 err := cr.SetupMounts()
1126 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1127 "--read-write", "--crunchstat-interval=5",
1128 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1129 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/out", realTemp + "/tmp3:/tmp"})
1130 os.RemoveAll(cr.ArvMountPoint)
1137 cr.ArvMountPoint = ""
1138 cr.Container.Mounts = make(map[string]arvados.Mount)
1139 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1140 cr.OutputPath = "/tmp"
1143 cr.Container.RuntimeConstraints.API = &apiflag
1145 err := cr.SetupMounts()
1147 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1148 "--read-write", "--crunchstat-interval=5",
1149 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1150 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", stubCertPath + ":/etc/arvados/ca-certificates.crt:ro"})
1151 os.RemoveAll(cr.ArvMountPoint)
1160 cr.ArvMountPoint = ""
1161 cr.Container.Mounts = map[string]arvados.Mount{
1162 "/keeptmp": {Kind: "collection", Writable: true},
1164 cr.OutputPath = "/keeptmp"
1166 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1168 err := cr.SetupMounts()
1170 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1171 "--read-write", "--crunchstat-interval=5",
1172 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1173 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/tmp0:/keeptmp"})
1174 os.RemoveAll(cr.ArvMountPoint)
1181 cr.ArvMountPoint = ""
1182 cr.Container.Mounts = map[string]arvados.Mount{
1183 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1184 "/keepout": {Kind: "collection", Writable: true},
1186 cr.OutputPath = "/keepout"
1188 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1189 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1191 err := cr.SetupMounts()
1193 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1194 "--read-write", "--crunchstat-interval=5",
1195 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1196 sort.StringSlice(cr.Binds).Sort()
1197 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1198 realTemp + "/keep1/tmp0:/keepout"})
1199 os.RemoveAll(cr.ArvMountPoint)
1206 cr.ArvMountPoint = ""
1207 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
1208 cr.Container.Mounts = map[string]arvados.Mount{
1209 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1210 "/keepout": {Kind: "collection", Writable: true},
1212 cr.OutputPath = "/keepout"
1214 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1215 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1217 err := cr.SetupMounts()
1219 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1220 "--read-write", "--crunchstat-interval=5",
1221 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1222 sort.StringSlice(cr.Binds).Sort()
1223 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1224 realTemp + "/keep1/tmp0:/keepout"})
1225 os.RemoveAll(cr.ArvMountPoint)
1230 for _, test := range []struct {
1234 {in: "foo", out: `"foo"`},
1235 {in: nil, out: `null`},
1236 {in: map[string]int64{"foo": 123456789123456789}, out: `{"foo":123456789123456789}`},
1239 cr.ArvMountPoint = ""
1240 cr.Container.Mounts = map[string]arvados.Mount{
1241 "/mnt/test.json": {Kind: "json", Content: test.in},
1243 err := cr.SetupMounts()
1245 sort.StringSlice(cr.Binds).Sort()
1246 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/json2/mountdata.json:/mnt/test.json:ro"})
1247 content, err := ioutil.ReadFile(realTemp + "/json2/mountdata.json")
1249 c.Check(content, DeepEquals, []byte(test.out))
1250 os.RemoveAll(cr.ArvMountPoint)
1255 for _, test := range []struct {
1259 {in: "foo", out: `foo`},
1260 {in: nil, out: "error"},
1261 {in: map[string]int64{"foo": 123456789123456789}, out: "error"},
1264 cr.ArvMountPoint = ""
1265 cr.Container.Mounts = map[string]arvados.Mount{
1266 "/mnt/test.txt": {Kind: "text", Content: test.in},
1268 err := cr.SetupMounts()
1269 if test.out == "error" {
1270 c.Check(err.Error(), Equals, "content for mount \"/mnt/test.txt\" must be a string")
1273 sort.StringSlice(cr.Binds).Sort()
1274 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/text2/mountdata.text:/mnt/test.txt:ro"})
1275 content, err := ioutil.ReadFile(realTemp + "/text2/mountdata.text")
1277 c.Check(content, DeepEquals, []byte(test.out))
1279 os.RemoveAll(cr.ArvMountPoint)
1284 // Read-only mount points are allowed underneath output_dir mount point
1287 cr.ArvMountPoint = ""
1288 cr.Container.Mounts = make(map[string]arvados.Mount)
1289 cr.Container.Mounts = map[string]arvados.Mount{
1290 "/tmp": {Kind: "tmp"},
1291 "/tmp/foo": {Kind: "collection"},
1293 cr.OutputPath = "/tmp"
1295 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1297 err := cr.SetupMounts()
1299 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1300 "--read-write", "--crunchstat-interval=5",
1301 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1302 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", realTemp + "/keep1/tmp0:/tmp/foo:ro"})
1303 os.RemoveAll(cr.ArvMountPoint)
1308 // Writable mount points copied to output_dir mount point
1311 cr.ArvMountPoint = ""
1312 cr.Container.Mounts = make(map[string]arvados.Mount)
1313 cr.Container.Mounts = map[string]arvados.Mount{
1314 "/tmp": {Kind: "tmp"},
1315 "/tmp/foo": {Kind: "collection",
1316 PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53",
1318 "/tmp/bar": {Kind: "collection",
1319 PortableDataHash: "59389a8f9ee9d399be35462a0f92541d+53",
1323 cr.OutputPath = "/tmp"
1325 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1326 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz", os.ModePerm)
1328 rf, _ := os.Create(realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz/quux")
1329 rf.Write([]byte("bar"))
1332 err := cr.SetupMounts()
1334 _, err = os.Stat(cr.HostOutputDir + "/foo")
1336 _, err = os.Stat(cr.HostOutputDir + "/bar/quux")
1338 os.RemoveAll(cr.ArvMountPoint)
1343 // Only mount points of kind 'collection' are allowed underneath output_dir mount point
1346 cr.ArvMountPoint = ""
1347 cr.Container.Mounts = make(map[string]arvados.Mount)
1348 cr.Container.Mounts = map[string]arvados.Mount{
1349 "/tmp": {Kind: "tmp"},
1350 "/tmp/foo": {Kind: "tmp"},
1352 cr.OutputPath = "/tmp"
1354 err := cr.SetupMounts()
1355 c.Check(err, NotNil)
1356 c.Check(err, ErrorMatches, `Only mount points of kind 'collection', 'text' or 'json' are supported underneath the output_path.*`)
1357 os.RemoveAll(cr.ArvMountPoint)
1362 // Only mount point of kind 'collection' is allowed for stdin
1365 cr.ArvMountPoint = ""
1366 cr.Container.Mounts = make(map[string]arvados.Mount)
1367 cr.Container.Mounts = map[string]arvados.Mount{
1368 "stdin": {Kind: "tmp"},
1371 err := cr.SetupMounts()
1372 c.Check(err, NotNil)
1373 c.Check(err, ErrorMatches, `Unsupported mount kind 'tmp' for stdin.*`)
1374 os.RemoveAll(cr.ArvMountPoint)
1382 cr.ArvMountPoint = ""
1383 (*GitMountSuite)(nil).useTestGitServer(c)
1384 cr.token = arvadostest.ActiveToken
1385 cr.Container.Mounts = make(map[string]arvados.Mount)
1386 cr.Container.Mounts = map[string]arvados.Mount{
1389 UUID: arvadostest.Repository2UUID,
1390 Commit: "fd3531f42995344f36c30b79f55f27b502f3d344",
1395 UUID: arvadostest.Repository2UUID,
1396 Commit: "5ebfab0522851df01fec11ec55a6d0f4877b542e",
1400 cr.OutputPath = "/tmp"
1402 err := cr.SetupMounts()
1405 // dirMap[mountpoint] == tmpdir
1406 dirMap := make(map[string]string)
1407 for _, bind := range cr.Binds {
1408 tokens := strings.Split(bind, ":")
1409 dirMap[tokens[1]] = tokens[0]
1411 if cr.Container.Mounts[tokens[1]].Writable {
1412 c.Check(len(tokens), Equals, 2)
1414 c.Check(len(tokens), Equals, 3)
1415 c.Check(tokens[2], Equals, "ro")
1419 data, err := ioutil.ReadFile(dirMap["/tip"] + "/dir1/dir2/file with mode 0644")
1421 c.Check(string(data), Equals, "\000\001\002\003")
1422 _, err = ioutil.ReadFile(dirMap["/tip"] + "/file only on testbranch")
1423 c.Check(err, FitsTypeOf, &os.PathError{})
1424 c.Check(os.IsNotExist(err), Equals, true)
1426 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/dir1/dir2/file with mode 0644")
1428 c.Check(string(data), Equals, "\000\001\002\003")
1429 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/file only on testbranch")
1431 c.Check(string(data), Equals, "testfile\n")
1438 func (s *TestSuite) TestStdout(c *C) {
1440 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1441 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1443 "environment": {"FROBIZ": "bilbo"},
1444 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1445 "output_path": "/tmp",
1447 "runtime_constraints": {}
1450 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1451 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1455 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1456 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1457 c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1460 // Used by the TestStdoutWithWrongPath*()
1461 func (s *TestSuite) stdoutErrorRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, err error) {
1462 rec := arvados.Container{}
1463 err = json.Unmarshal([]byte(record), &rec)
1467 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
1469 api = &ArvTestClient{Container: rec}
1470 kc := &KeepTestClient{}
1472 cr = NewContainerRunner(api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1473 am := &ArvMountCmdLine{}
1474 cr.RunArvMount = am.ArvMountTest
1475 cr.MkArvClient = func(token string) (IArvadosClient, error) {
1476 return &ArvTestClient{}, nil
1483 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1484 _, _, err := s.stdoutErrorRunHelper(c, `{
1485 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1486 "output_path": "/tmp"
1487 }`, func(t *TestDockerClient) {})
1489 c.Check(err, NotNil)
1490 c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
1493 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1494 _, _, err := s.stdoutErrorRunHelper(c, `{
1495 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1496 "output_path": "/tmp"
1497 }`, func(t *TestDockerClient) {})
1499 c.Check(err, NotNil)
1500 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'tmp' for stdout"), Equals, true)
1503 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1504 _, _, err := s.stdoutErrorRunHelper(c, `{
1505 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1506 "output_path": "/tmp"
1507 }`, func(t *TestDockerClient) {})
1509 c.Check(err, NotNil)
1510 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'collection' for stdout"), Equals, true)
1513 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1514 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1515 defer os.Unsetenv("ARVADOS_API_HOST")
1516 api, _, _ := s.fullRunHelper(c, `{
1517 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1518 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1521 "mounts": {"/tmp": {"kind": "tmp"} },
1522 "output_path": "/tmp",
1524 "runtime_constraints": {"API": true}
1525 }`, nil, 0, func(t *TestDockerClient) {
1526 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
1530 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1531 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1532 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "test.arvados.org\n"), Equals, true)
1533 c.Check(api.CalledWith("container.output", "d41d8cd98f00b204e9800998ecf8427e+0"), NotNil)
1536 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1537 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1538 defer os.Unsetenv("ARVADOS_API_HOST")
1539 api, _, _ := s.fullRunHelper(c, `{
1540 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1541 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1544 "mounts": {"/tmp": {"kind": "tmp"} },
1545 "output_path": "/tmp",
1547 "runtime_constraints": {"API": true}
1548 }`, nil, 0, func(t *TestDockerClient) {
1549 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
1553 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1554 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1555 c.Check(api.CalledWith("container.output", "d4ab34d3d4f8a72f5c4973051ae69fab+122"), NotNil)
1558 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1560 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1561 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1563 "environment": {"FROBIZ": "bilbo"},
1565 "/tmp": {"kind": "tmp"},
1566 "/tmp/foo": {"kind": "collection",
1567 "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1568 "exclude_from_output": true
1570 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1572 "output_path": "/tmp",
1574 "runtime_constraints": {}
1577 extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1579 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1580 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1584 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1585 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1586 c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1589 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1591 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1592 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1594 "environment": {"FROBIZ": "bilbo"},
1596 "/tmp": {"kind": "tmp"},
1597 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1598 "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1599 "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1600 "/tmp/foo/baz/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1601 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1603 "output_path": "/tmp",
1605 "runtime_constraints": {}
1608 extraMounts := []string{
1609 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1610 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1611 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1614 api, runner, realtemp := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1615 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1619 c.Check(runner.Binds, DeepEquals, []string{realtemp + "/tmp2:/tmp",
1620 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt:/tmp/foo/bar:ro",
1621 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt:/tmp/foo/baz/sub2file2:ro",
1622 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1:/tmp/foo/sub1:ro",
1623 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt:/tmp/foo/sub1file2:ro",
1626 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1627 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1628 for _, v := range api.Content {
1629 if v["collection"] != nil {
1630 c.Check(v["ensure_unique_name"], Equals, true)
1631 collection := v["collection"].(arvadosclient.Dict)
1632 if strings.Index(collection["name"].(string), "output") == 0 {
1633 manifest := collection["manifest_text"].(string)
1635 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1636 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 9:18:bar 9:18:sub1file2
1637 ./foo/baz 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2
1638 ./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1639 ./foo/sub1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1646 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
1648 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1649 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1651 "environment": {"FROBIZ": "bilbo"},
1653 "/tmp": {"kind": "tmp"},
1654 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt"},
1655 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1657 "output_path": "/tmp",
1659 "runtime_constraints": {}
1662 extraMounts := []string{
1663 "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1666 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1667 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1671 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1672 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1673 for _, v := range api.Content {
1674 if v["collection"] != nil {
1675 collection := v["collection"].(arvadosclient.Dict)
1676 if strings.Index(collection["name"].(string), "output") == 0 {
1677 manifest := collection["manifest_text"].(string)
1679 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1680 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 10:17:bar
1687 func (s *TestSuite) TestOutputSymlinkToInput(c *C) {
1689 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1690 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1692 "environment": {"FROBIZ": "bilbo"},
1694 "/tmp": {"kind": "tmp"},
1695 "/keep/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path": "/subdir1/file2_in_subdir1.txt"},
1696 "/keep/foo2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367"}
1698 "output_path": "/tmp",
1700 "runtime_constraints": {}
1703 extraMounts := []string{
1704 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1707 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1708 os.Symlink("/keep/foo/sub1file2", t.realTemp+"/tmp2/baz")
1709 os.Symlink("/keep/foo2/subdir1/file2_in_subdir1.txt", t.realTemp+"/tmp2/baz2")
1710 os.Symlink("/keep/foo2/subdir1", t.realTemp+"/tmp2/baz3")
1711 os.Mkdir(t.realTemp+"/tmp2/baz4", 0700)
1712 os.Symlink("/keep/foo2/subdir1/file2_in_subdir1.txt", t.realTemp+"/tmp2/baz4/baz5")
1716 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1717 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1718 for _, v := range api.Content {
1719 if v["collection"] != nil {
1720 collection := v["collection"].(arvadosclient.Dict)
1721 if strings.Index(collection["name"].(string), "output") == 0 {
1722 manifest := collection["manifest_text"].(string)
1723 c.Check(manifest, Equals, `. 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:baz 9:18:baz2
1724 ./baz3 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1725 ./baz3/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1726 ./baz4 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:baz5
1733 func (s *TestSuite) TestOutputError(c *C) {
1735 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1736 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1738 "environment": {"FROBIZ": "bilbo"},
1740 "/tmp": {"kind": "tmp"}
1742 "output_path": "/tmp",
1744 "runtime_constraints": {}
1747 extraMounts := []string{}
1749 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1750 os.Symlink("/etc/hosts", t.realTemp+"/tmp2/baz")
1754 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1757 func (s *TestSuite) TestOutputSymlinkToOutput(c *C) {
1759 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1760 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1762 "environment": {"FROBIZ": "bilbo"},
1764 "/tmp": {"kind": "tmp"}
1766 "output_path": "/tmp",
1768 "runtime_constraints": {}
1771 extraMounts := []string{}
1773 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1774 rf, _ := os.Create(t.realTemp + "/tmp2/realfile")
1775 rf.Write([]byte("foo"))
1778 os.Mkdir(t.realTemp+"/tmp2/realdir", 0700)
1779 rf, _ = os.Create(t.realTemp + "/tmp2/realdir/subfile")
1780 rf.Write([]byte("bar"))
1783 os.Symlink("/tmp/realfile", t.realTemp+"/tmp2/file1")
1784 os.Symlink("realfile", t.realTemp+"/tmp2/file2")
1785 os.Symlink("/tmp/file1", t.realTemp+"/tmp2/file3")
1786 os.Symlink("file2", t.realTemp+"/tmp2/file4")
1787 os.Symlink("realdir", t.realTemp+"/tmp2/dir1")
1788 os.Symlink("/tmp/realdir", t.realTemp+"/tmp2/dir2")
1792 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1793 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1794 for _, v := range api.Content {
1795 if v["collection"] != nil {
1796 collection := v["collection"].(arvadosclient.Dict)
1797 if strings.Index(collection["name"].(string), "output") == 0 {
1798 manifest := collection["manifest_text"].(string)
1799 c.Check(manifest, Equals,
1800 `. 7a2c86e102dcc231bd232aad99686dfa+15 0:3:file1 3:3:file2 6:3:file3 9:3:file4 12:3:realfile
1801 ./dir1 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1802 ./dir2 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1803 ./realdir 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1810 func (s *TestSuite) TestStdinCollectionMountPoint(c *C) {
1812 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1813 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1815 "environment": {"FROBIZ": "bilbo"},
1817 "/tmp": {"kind": "tmp"},
1818 "stdin": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/file1_in_main.txt"},
1819 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1821 "output_path": "/tmp",
1823 "runtime_constraints": {}
1826 extraMounts := []string{
1827 "b0def87f80dd594d4675809e83bd4f15+367/file1_in_main.txt",
1830 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1831 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1835 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1836 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1837 for _, v := range api.Content {
1838 if v["collection"] != nil {
1839 collection := v["collection"].(arvadosclient.Dict)
1840 if strings.Index(collection["name"].(string), "output") == 0 {
1841 manifest := collection["manifest_text"].(string)
1842 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1849 func (s *TestSuite) TestStdinJsonMountPoint(c *C) {
1851 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1852 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1854 "environment": {"FROBIZ": "bilbo"},
1856 "/tmp": {"kind": "tmp"},
1857 "stdin": {"kind": "json", "content": "foo"},
1858 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1860 "output_path": "/tmp",
1862 "runtime_constraints": {}
1865 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1866 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1870 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1871 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1872 for _, v := range api.Content {
1873 if v["collection"] != nil {
1874 collection := v["collection"].(arvadosclient.Dict)
1875 if strings.Index(collection["name"].(string), "output") == 0 {
1876 manifest := collection["manifest_text"].(string)
1877 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1884 func (s *TestSuite) TestStderrMount(c *C) {
1885 api, _, _ := s.fullRunHelper(c, `{
1886 "command": ["/bin/sh", "-c", "echo hello;exit 1"],
1887 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1890 "mounts": {"/tmp": {"kind": "tmp"},
1891 "stdout": {"kind": "file", "path": "/tmp/a/out.txt"},
1892 "stderr": {"kind": "file", "path": "/tmp/b/err.txt"}},
1893 "output_path": "/tmp",
1895 "runtime_constraints": {}
1896 }`, nil, 1, func(t *TestDockerClient) {
1897 t.logWriter.Write(dockerLog(1, "hello\n"))
1898 t.logWriter.Write(dockerLog(2, "oops\n"))
1902 final := api.CalledWith("container.state", "Complete")
1903 c.Assert(final, NotNil)
1904 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1905 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1907 c.Check(api.CalledWith("collection.manifest_text", "./a b1946ac92492d2347c6235b4d2611184+6 0:6:out.txt\n./b 38af5c54926b620264ab1501150cf189+5 0:5:err.txt\n"), NotNil)
1910 func (s *TestSuite) TestNumberRoundTrip(c *C) {
1911 kc := &KeepTestClient{}
1913 cr := NewContainerRunner(&ArvTestClient{callraw: true}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1914 cr.fetchContainerRecord()
1916 jsondata, err := json.Marshal(cr.Container.Mounts["/json"].Content)
1919 c.Check(string(jsondata), Equals, `{"number":123456789123456789}`)
1922 func (s *TestSuite) TestEvalSymlinks(c *C) {
1923 kc := &KeepTestClient{}
1925 cr := NewContainerRunner(&ArvTestClient{callraw: true}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1927 realTemp, err := ioutil.TempDir("", "crunchrun_test-")
1928 c.Assert(err, IsNil)
1929 defer os.RemoveAll(realTemp)
1931 cr.HostOutputDir = realTemp
1933 // Absolute path outside output dir
1934 os.Symlink("/etc/passwd", realTemp+"/p1")
1936 // Relative outside output dir
1937 os.Symlink("../zip", realTemp+"/p2")
1939 // Circular references
1940 os.Symlink("p4", realTemp+"/p3")
1941 os.Symlink("p5", realTemp+"/p4")
1942 os.Symlink("p3", realTemp+"/p5")
1944 // Target doesn't exist
1945 os.Symlink("p99", realTemp+"/p6")
1947 for _, v := range []string{"p1", "p2", "p3", "p4", "p5"} {
1948 info, err := os.Lstat(realTemp + "/" + v)
1949 _, _, _, err = cr.derefOutputSymlink(realTemp+"/"+v, info)
1950 c.Assert(err, NotNil)
1954 func (s *TestSuite) TestEvalSymlinkDir(c *C) {
1955 kc := &KeepTestClient{}
1957 cr := NewContainerRunner(&ArvTestClient{callraw: true}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1959 realTemp, err := ioutil.TempDir("", "crunchrun_test-")
1960 c.Assert(err, IsNil)
1961 defer os.RemoveAll(realTemp)
1963 cr.HostOutputDir = realTemp
1965 // Absolute path outside output dir
1966 os.Symlink(".", realTemp+"/loop")
1969 info, err := os.Lstat(realTemp + "/" + v)
1970 _, err = cr.UploadOutputFile(realTemp+"/"+v, info, err, []string{}, nil, "", "", 0)
1971 c.Assert(err, NotNil)
1974 func (s *TestSuite) TestFullBrokenDocker1(c *C) {
1975 tf, err := ioutil.TempFile("", "brokenNodeHook-")
1976 c.Assert(err, IsNil)
1977 defer os.Remove(tf.Name())
1979 tf.Write([]byte(`#!/bin/sh
1983 os.Chmod(tf.Name(), 0700)
1986 brokenNodeHook = &ech
1988 api, _, _ := s.fullRunHelper(c, `{
1989 "command": ["echo", "hello world"],
1990 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1993 "mounts": {"/tmp": {"kind": "tmp"} },
1994 "output_path": "/tmp",
1996 "runtime_constraints": {}
1997 }`, nil, 2, func(t *TestDockerClient) {
1998 t.logWriter.Write(dockerLog(1, "hello world\n"))
2002 c.Check(api.CalledWith("container.state", "Queued"), NotNil)
2003 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
2004 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Running broken node hook.*")
2005 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*killme.*")
2009 func (s *TestSuite) TestFullBrokenDocker2(c *C) {
2011 brokenNodeHook = &ech
2013 api, _, _ := s.fullRunHelper(c, `{
2014 "command": ["echo", "hello world"],
2015 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2018 "mounts": {"/tmp": {"kind": "tmp"} },
2019 "output_path": "/tmp",
2021 "runtime_constraints": {}
2022 }`, nil, 2, func(t *TestDockerClient) {
2023 t.logWriter.Write(dockerLog(1, "hello world\n"))
2027 c.Check(api.CalledWith("container.state", "Queued"), NotNil)
2028 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
2029 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*No broken node hook.*")
2032 func (s *TestSuite) TestFullBrokenDocker3(c *C) {
2034 brokenNodeHook = &ech
2036 api, _, _ := s.fullRunHelper(c, `{
2037 "command": ["echo", "hello world"],
2038 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2041 "mounts": {"/tmp": {"kind": "tmp"} },
2042 "output_path": "/tmp",
2044 "runtime_constraints": {}
2045 }`, nil, 3, func(t *TestDockerClient) {
2046 t.logWriter.Write(dockerLog(1, "hello world\n"))
2050 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2051 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
2054 func (s *TestSuite) TestBadCommand1(c *C) {
2056 brokenNodeHook = &ech
2058 api, _, _ := s.fullRunHelper(c, `{
2059 "command": ["echo", "hello world"],
2060 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2063 "mounts": {"/tmp": {"kind": "tmp"} },
2064 "output_path": "/tmp",
2066 "runtime_constraints": {}
2067 }`, nil, 4, func(t *TestDockerClient) {
2068 t.logWriter.Write(dockerLog(1, "hello world\n"))
2072 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2073 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2076 func (s *TestSuite) TestBadCommand2(c *C) {
2078 brokenNodeHook = &ech
2080 api, _, _ := s.fullRunHelper(c, `{
2081 "command": ["echo", "hello world"],
2082 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2085 "mounts": {"/tmp": {"kind": "tmp"} },
2086 "output_path": "/tmp",
2088 "runtime_constraints": {}
2089 }`, nil, 5, func(t *TestDockerClient) {
2090 t.logWriter.Write(dockerLog(1, "hello world\n"))
2094 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2095 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2098 func (s *TestSuite) TestBadCommand3(c *C) {
2100 brokenNodeHook = &ech
2102 api, _, _ := s.fullRunHelper(c, `{
2103 "command": ["echo", "hello world"],
2104 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2107 "mounts": {"/tmp": {"kind": "tmp"} },
2108 "output_path": "/tmp",
2110 "runtime_constraints": {}
2111 }`, nil, 6, func(t *TestDockerClient) {
2112 t.logWriter.Write(dockerLog(1, "hello world\n"))
2116 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2117 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2120 func (s *TestSuite) TestSecretTextMountPoint(c *C) {
2121 // under normal mounts, gets captured in output, oops
2123 "command": ["true"],
2124 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2127 "/tmp": {"kind": "tmp"},
2128 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2132 "output_path": "/tmp",
2134 "runtime_constraints": {}
2137 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2138 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2140 c.Check(content, DeepEquals, []byte("mypassword"))
2144 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2145 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2146 c.Check(api.CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), NotNil)
2147 c.Check(api.CalledWith("collection.manifest_text", ""), IsNil)
2149 // under secret mounts, not captured in output
2151 "command": ["true"],
2152 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2155 "/tmp": {"kind": "tmp"}
2158 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2160 "output_path": "/tmp",
2162 "runtime_constraints": {}
2165 api, _, _ = s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2166 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2168 c.Check(content, DeepEquals, []byte("mypassword"))
2172 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2173 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2174 c.Check(api.CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), IsNil)
2175 c.Check(api.CalledWith("collection.manifest_text", ""), NotNil)