1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
27 "git.curoverse.com/arvados.git/sdk/go/arvados"
28 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
29 "git.curoverse.com/arvados.git/sdk/go/arvadostest"
30 "git.curoverse.com/arvados.git/sdk/go/manifest"
31 "golang.org/x/net/context"
33 dockertypes "github.com/docker/docker/api/types"
34 dockercontainer "github.com/docker/docker/api/types/container"
35 dockernetwork "github.com/docker/docker/api/types/network"
39 // Gocheck boilerplate
40 func TestCrunchExec(t *testing.T) {
44 // Gocheck boilerplate
45 var _ = Suite(&TestSuite{})
47 type TestSuite struct {
48 docker *TestDockerClient
51 func (s *TestSuite) SetUpTest(c *C) {
52 s.docker = NewTestDockerClient()
55 type ArvTestClient struct {
58 Content []arvadosclient.Dict
60 Logs map[string]*bytes.Buffer
66 type KeepTestClient struct {
71 var hwManifest = ". 82ab40c24fc8df01798e57ba66795bb1+841216+Aa124ac75e5168396c73c0a18eda641a4f41791c0@569fa8c3 0:841216:9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7.tar\n"
72 var hwPDH = "a45557269dcb65a6b78f9ac061c0850b+120"
73 var hwImageId = "9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7"
75 var otherManifest = ". 68a84f561b1d1708c6baff5e019a9ab3+46+Ae5d0af96944a3690becb1decdf60cc1c937f556d@5693216f 0:46:md5sum.txt\n"
76 var otherPDH = "a3e8f74c6f101eae01fa08bfb4e49b3a+54"
78 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
79 ./subdir1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
80 ./subdir1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
83 var normalizedWithSubdirsPDH = "a0def87f80dd594d4675809e83bd4f15+367"
85 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"
86 var denormalizedWithSubdirsPDH = "b0def87f80dd594d4675809e83bd4f15+367"
88 var fakeAuthUUID = "zzzzz-gj3su-55pqoyepgi2glem"
89 var fakeAuthToken = "a3ltuwzqcu2u4sc0q7yhpc2w7s00fdcqecg5d6e0u3pfohmbjt"
91 type TestDockerClient struct {
93 logReader io.ReadCloser
94 logWriter io.WriteCloser
95 fn func(t *TestDockerClient)
105 func NewTestDockerClient() *TestDockerClient {
106 t := &TestDockerClient{}
107 t.logReader, t.logWriter = io.Pipe()
108 t.stop = make(chan bool, 1)
113 type MockConn struct {
117 func (m *MockConn) Write(b []byte) (int, error) {
121 func NewMockConn() *MockConn {
126 func (t *TestDockerClient) ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error) {
127 return dockertypes.HijackedResponse{Conn: NewMockConn(), Reader: bufio.NewReader(t.logReader)}, nil
130 func (t *TestDockerClient) ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig, networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error) {
131 if config.WorkingDir != "" {
132 t.cwd = config.WorkingDir
135 return dockercontainer.ContainerCreateCreatedBody{ID: "abcde"}, nil
138 func (t *TestDockerClient) ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error {
140 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\\\"\""`)
143 return errors.New(`panic: standard_init_linux.go:175: exec user process caused "no such file or directory"`)
146 return errors.New(`Error response from daemon: Cannot start container 41f26cbc43bcc1280f4323efb1830a394ba8660c9d1c2b564ba42bf7f7694845: [8] System error: no such file or directory`)
149 return errors.New(`Error response from daemon: Cannot start container 58099cd76c834f3dc2a4fb76c8028f049ae6d4fdf0ec373e1f2cfea030670c2d: [8] System error: exec: "foobar": executable file not found in $PATH`)
152 if container == "abcde" {
153 // t.fn gets executed in ContainerWait
156 return errors.New("Invalid container id")
160 func (t *TestDockerClient) ContainerRemove(ctx context.Context, container string, options dockertypes.ContainerRemoveOptions) error {
165 func (t *TestDockerClient) ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error) {
167 body := make(chan dockercontainer.ContainerWaitOKBody, 1)
168 err := make(chan error)
171 body <- dockercontainer.ContainerWaitOKBody{StatusCode: int64(t.exitCode)}
176 func (t *TestDockerClient) ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error) {
178 return dockertypes.ImageInspect{}, nil, fmt.Errorf("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?")
181 if t.imageLoaded == image {
182 return dockertypes.ImageInspect{}, nil, nil
184 return dockertypes.ImageInspect{}, nil, errors.New("")
188 func (t *TestDockerClient) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error) {
190 return dockertypes.ImageLoadResponse{}, fmt.Errorf("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?")
192 _, err := io.Copy(ioutil.Discard, input)
194 return dockertypes.ImageLoadResponse{}, err
196 t.imageLoaded = hwImageId
197 return dockertypes.ImageLoadResponse{Body: ioutil.NopCloser(input)}, nil
201 func (*TestDockerClient) ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {
205 func (client *ArvTestClient) Create(resourceType string,
206 parameters arvadosclient.Dict,
207 output interface{}) error {
210 defer client.Mutex.Unlock()
213 client.Content = append(client.Content, parameters)
215 if resourceType == "logs" {
216 et := parameters["log"].(arvadosclient.Dict)["event_type"].(string)
217 if client.Logs == nil {
218 client.Logs = make(map[string]*bytes.Buffer)
220 if client.Logs[et] == nil {
221 client.Logs[et] = &bytes.Buffer{}
223 client.Logs[et].Write([]byte(parameters["log"].(arvadosclient.Dict)["properties"].(map[string]string)["text"]))
226 if resourceType == "collections" && output != nil {
227 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
228 outmap := output.(*arvados.Collection)
229 outmap.PortableDataHash = fmt.Sprintf("%x+%d", md5.Sum([]byte(mt)), len(mt))
235 func (client *ArvTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
237 case method == "GET" && resourceType == "containers" && action == "auth":
238 return json.Unmarshal([]byte(`{
239 "kind": "arvados#api_client_authorization",
240 "uuid": "`+fakeAuthUUID+`",
241 "api_token": "`+fakeAuthToken+`"
244 return fmt.Errorf("Not found")
248 func (client *ArvTestClient) CallRaw(method, resourceType, uuid, action string,
249 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
251 if method == "GET" && resourceType == "nodes" && uuid == "" && action == "" {
253 "kind": "arvados#nodeList",
255 "uuid": "zzzzz-7ekkf-2z3mc76g2q73aio",
256 "hostname": "compute2",
257 "properties": {"total_cpu_cores": 16}
259 } else if method == "GET" && resourceType == "containers" && action == "" && !client.callraw {
261 j, err = json.Marshal(map[string]interface{}{
262 "items": []interface{}{client.Container},
263 "kind": "arvados#nodeList",
266 j, err = json.Marshal(client.Container)
270 "command": ["sleep", "1"],
271 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
274 "mounts": {"/tmp": {"kind": "tmp"}, "/json": {"kind": "json", "content": {"number": 123456789123456789}}},
275 "output_path": "/tmp",
277 "runtime_constraints": {}
280 return ioutil.NopCloser(bytes.NewReader(j)), err
283 func (client *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
284 if resourceType == "collections" {
286 output.(*arvados.Collection).ManifestText = hwManifest
287 } else if uuid == otherPDH {
288 output.(*arvados.Collection).ManifestText = otherManifest
289 } else if uuid == normalizedWithSubdirsPDH {
290 output.(*arvados.Collection).ManifestText = normalizedManifestWithSubdirs
291 } else if uuid == denormalizedWithSubdirsPDH {
292 output.(*arvados.Collection).ManifestText = denormalizedManifestWithSubdirs
295 if resourceType == "containers" {
296 (*output.(*arvados.Container)) = client.Container
301 func (client *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
303 defer client.Mutex.Unlock()
305 client.Content = append(client.Content, parameters)
306 if resourceType == "containers" {
307 if parameters["container"].(arvadosclient.Dict)["state"] == "Running" {
308 client.WasSetRunning = true
314 var discoveryMap = map[string]interface{}{
315 "defaultTrashLifetime": float64(1209600),
316 "crunchLimitLogBytesPerJob": float64(67108864),
317 "crunchLogThrottleBytes": float64(65536),
318 "crunchLogThrottlePeriod": float64(60),
319 "crunchLogThrottleLines": float64(1024),
320 "crunchLogPartialLineThrottlePeriod": float64(5),
321 "crunchLogBytesPerEvent": float64(4096),
322 "crunchLogSecondsBetweenEvents": float64(1),
325 func (client *ArvTestClient) Discovery(key string) (interface{}, error) {
326 return discoveryMap[key], nil
329 // CalledWith returns the parameters from the first API call whose
330 // parameters match jpath/string. E.g., CalledWith(c, "foo.bar",
331 // "baz") returns parameters with parameters["foo"]["bar"]=="baz". If
332 // no call matches, it returns nil.
333 func (client *ArvTestClient) CalledWith(jpath string, expect interface{}) arvadosclient.Dict {
335 for _, content := range client.Content {
336 var v interface{} = content
337 for _, k := range strings.Split(jpath, ".") {
338 if dict, ok := v.(arvadosclient.Dict); !ok {
351 func (client *KeepTestClient) PutHB(hash string, buf []byte) (string, int, error) {
353 return fmt.Sprintf("%s+%d", hash, len(buf)), len(buf), nil
356 func (*KeepTestClient) ClearBlockCache() {
359 type FileWrapper struct {
364 func (fw FileWrapper) Readdir(n int) ([]os.FileInfo, error) {
365 return nil, errors.New("not implemented")
368 func (fw FileWrapper) Seek(int64, int) (int64, error) {
369 return 0, errors.New("not implemented")
372 func (fw FileWrapper) Size() int64 {
376 func (fw FileWrapper) Stat() (os.FileInfo, error) {
377 return nil, errors.New("not implemented")
380 func (fw FileWrapper) Truncate(int64) error {
381 return errors.New("not implemented")
384 func (fw FileWrapper) Write([]byte) (int, error) {
385 return 0, errors.New("not implemented")
388 func (client *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
389 if filename == hwImageId+".tar" {
390 rdr := ioutil.NopCloser(&bytes.Buffer{})
392 return FileWrapper{rdr, 1321984}, nil
393 } else if filename == "/file1_in_main.txt" {
394 rdr := ioutil.NopCloser(strings.NewReader("foo"))
396 return FileWrapper{rdr, 3}, nil
401 func (s *TestSuite) TestLoadImage(c *C) {
402 kc := &KeepTestClient{}
403 cr := NewContainerRunner(&ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
405 _, err := cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
407 _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
410 cr.Container.ContainerImage = hwPDH
412 // (1) Test loading image from keep
413 c.Check(kc.Called, Equals, false)
414 c.Check(cr.ContainerConfig.Image, Equals, "")
420 cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
423 c.Check(kc.Called, Equals, true)
424 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
426 _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
429 // (2) Test using image that's already loaded
431 cr.ContainerConfig.Image = ""
435 c.Check(kc.Called, Equals, false)
436 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
440 type ArvErrorTestClient struct{}
442 func (ArvErrorTestClient) Create(resourceType string,
443 parameters arvadosclient.Dict,
444 output interface{}) error {
448 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
449 return errors.New("ArvError")
452 func (ArvErrorTestClient) CallRaw(method, resourceType, uuid, action string,
453 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
454 return nil, errors.New("ArvError")
457 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
458 return errors.New("ArvError")
461 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
465 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
466 return discoveryMap[key], nil
469 type KeepErrorTestClient struct{}
471 func (KeepErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
472 return "", 0, errors.New("KeepError")
475 func (KeepErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
476 return nil, errors.New("KeepError")
479 func (KeepErrorTestClient) ClearBlockCache() {
482 type KeepReadErrorTestClient struct{}
484 func (KeepReadErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
488 func (KeepReadErrorTestClient) ClearBlockCache() {
491 type ErrorReader struct {
495 func (ErrorReader) Read(p []byte) (n int, err error) {
496 return 0, errors.New("ErrorReader")
499 func (ErrorReader) Seek(int64, int) (int64, error) {
500 return 0, errors.New("ErrorReader")
503 func (KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
504 return ErrorReader{}, nil
507 func (s *TestSuite) TestLoadImageArvError(c *C) {
509 cr := NewContainerRunner(ArvErrorTestClient{}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
510 cr.Container.ContainerImage = hwPDH
512 err := cr.LoadImage()
513 c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
516 func (s *TestSuite) TestLoadImageKeepError(c *C) {
518 cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
519 cr.Container.ContainerImage = hwPDH
521 err := cr.LoadImage()
522 c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
525 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
526 // (3) Collection doesn't contain image
527 cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
528 cr.Container.ContainerImage = otherPDH
530 err := cr.LoadImage()
531 c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
534 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
535 // (4) Collection doesn't contain image
536 cr := NewContainerRunner(&ArvTestClient{}, KeepReadErrorTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
537 cr.Container.ContainerImage = hwPDH
539 err := cr.LoadImage()
543 type ClosableBuffer struct {
547 func (*ClosableBuffer) Close() error {
551 type TestLogs struct {
552 Stdout ClosableBuffer
553 Stderr ClosableBuffer
556 func (tl *TestLogs) NewTestLoggingWriter(logstr string) io.WriteCloser {
557 if logstr == "stdout" {
560 if logstr == "stderr" {
566 func dockerLog(fd byte, msg string) []byte {
568 header := make([]byte, 8+len(by))
570 header[7] = byte(len(by))
575 func (s *TestSuite) TestRunContainer(c *C) {
576 s.docker.fn = func(t *TestDockerClient) {
577 t.logWriter.Write(dockerLog(1, "Hello world\n"))
580 cr := NewContainerRunner(&ArvTestClient{}, &KeepTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
583 cr.NewLogWriter = logs.NewTestLoggingWriter
584 cr.Container.ContainerImage = hwPDH
585 cr.Container.Command = []string{"./hw"}
586 err := cr.LoadImage()
589 err = cr.CreateContainer()
592 err = cr.StartContainer()
595 err = cr.WaitFinish()
598 c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
599 c.Check(logs.Stderr.String(), Equals, "")
602 func (s *TestSuite) TestCommitLogs(c *C) {
603 api := &ArvTestClient{}
604 kc := &KeepTestClient{}
605 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
606 cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
608 cr.CrunchLog.Print("Hello world!")
609 cr.CrunchLog.Print("Goodbye")
610 cr.finalState = "Complete"
612 err := cr.CommitLogs()
615 c.Check(api.Calls, Equals, 2)
616 c.Check(api.Content[1]["ensure_unique_name"], Equals, true)
617 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
618 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
619 c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
622 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
623 api := &ArvTestClient{}
624 kc := &KeepTestClient{}
625 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
627 err := cr.UpdateContainerRunning()
630 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
633 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
634 api := &ArvTestClient{}
635 kc := &KeepTestClient{}
636 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
638 cr.LogsPDH = new(string)
639 *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
641 cr.ExitCode = new(int)
643 cr.finalState = "Complete"
645 err := cr.UpdateContainerFinal()
648 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
649 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
650 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
653 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
654 api := &ArvTestClient{}
655 kc := &KeepTestClient{}
656 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
658 cr.finalState = "Cancelled"
660 err := cr.UpdateContainerFinal()
663 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
664 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
665 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
668 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
669 // dress rehearsal of the Run() function, starting from a JSON container record.
670 func (s *TestSuite) fullRunHelper(c *C, record string, extraMounts []string, exitCode int, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, realTemp string) {
671 rec := arvados.Container{}
672 err := json.Unmarshal([]byte(record), &rec)
675 s.docker.exitCode = exitCode
677 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
679 api = &ArvTestClient{Container: rec}
681 cr = NewContainerRunner(api, &KeepTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
682 cr.statInterval = 100 * time.Millisecond
683 am := &ArvMountCmdLine{}
684 cr.RunArvMount = am.ArvMountTest
686 realTemp, err = ioutil.TempDir("", "crunchrun_test1-")
688 defer os.RemoveAll(realTemp)
690 s.docker.realTemp = realTemp
693 cr.MkTempDir = func(_ string, prefix string) (string, error) {
695 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, tempcount)
696 err := os.Mkdir(d, os.ModePerm)
697 if err != nil && strings.Contains(err.Error(), ": file exists") {
698 // Test case must have pre-populated the tempdir
704 if extraMounts != nil && len(extraMounts) > 0 {
705 err := cr.SetupArvMountPoint("keep")
708 for _, m := range extraMounts {
709 os.MkdirAll(cr.ArvMountPoint+"/by_id/"+m, os.ModePerm)
714 if api.CalledWith("container.state", "Complete") != nil {
718 c.Check(api.WasSetRunning, Equals, true)
719 c.Check(api.Content[api.Calls-2]["container"].(arvadosclient.Dict)["log"], NotNil)
723 for k, v := range api.Logs {
732 func (s *TestSuite) TestFullRunHello(c *C) {
733 api, _, _ := s.fullRunHelper(c, `{
734 "command": ["echo", "hello world"],
735 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
738 "mounts": {"/tmp": {"kind": "tmp"} },
739 "output_path": "/tmp",
741 "runtime_constraints": {}
742 }`, nil, 0, func(t *TestDockerClient) {
743 t.logWriter.Write(dockerLog(1, "hello world\n"))
747 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
748 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
749 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
753 func (s *TestSuite) TestCrunchstat(c *C) {
754 api, _, _ := s.fullRunHelper(c, `{
755 "command": ["sleep", "1"],
756 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
759 "mounts": {"/tmp": {"kind": "tmp"} },
760 "output_path": "/tmp",
762 "runtime_constraints": {}
763 }`, nil, 0, func(t *TestDockerClient) {
764 time.Sleep(time.Second)
768 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
769 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
771 // We didn't actually start a container, so crunchstat didn't
772 // find accounting files and therefore didn't log any stats.
773 // It should have logged a "can't find accounting files"
774 // message after one poll interval, though, so we can confirm
776 c.Assert(api.Logs["crunchstat"], NotNil)
777 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
779 // The "files never appeared" log assures us that we called
780 // (*crunchstat.Reporter)Stop(), and that we set it up with
781 // the correct container ID "abcde":
782 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files never appeared for abcde\n`)
785 func (s *TestSuite) TestNodeInfoLog(c *C) {
786 os.Setenv("SLURMD_NODENAME", "compute2")
787 api, _, _ := s.fullRunHelper(c, `{
788 "command": ["sleep", "1"],
789 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
792 "mounts": {"/tmp": {"kind": "tmp"} },
793 "output_path": "/tmp",
795 "runtime_constraints": {}
797 func(t *TestDockerClient) {
798 time.Sleep(time.Second)
802 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
803 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
805 c.Assert(api.Logs["node"], NotNil)
806 json := api.Logs["node"].String()
807 c.Check(json, Matches, `(?ms).*"uuid": *"zzzzz-7ekkf-2z3mc76g2q73aio".*`)
808 c.Check(json, Matches, `(?ms).*"total_cpu_cores": *16.*`)
809 c.Check(json, Not(Matches), `(?ms).*"info":.*`)
811 c.Assert(api.Logs["node-info"], NotNil)
812 json = api.Logs["node-info"].String()
813 c.Check(json, Matches, `(?ms).*Host Information.*`)
814 c.Check(json, Matches, `(?ms).*CPU Information.*`)
815 c.Check(json, Matches, `(?ms).*Memory Information.*`)
816 c.Check(json, Matches, `(?ms).*Disk Space.*`)
817 c.Check(json, Matches, `(?ms).*Disk INodes.*`)
820 func (s *TestSuite) TestContainerRecordLog(c *C) {
821 api, _, _ := s.fullRunHelper(c, `{
822 "command": ["sleep", "1"],
823 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
826 "mounts": {"/tmp": {"kind": "tmp"} },
827 "output_path": "/tmp",
829 "runtime_constraints": {}
831 func(t *TestDockerClient) {
832 time.Sleep(time.Second)
836 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
837 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
839 c.Assert(api.Logs["container"], NotNil)
840 c.Check(api.Logs["container"].String(), Matches, `(?ms).*container_image.*`)
843 func (s *TestSuite) TestFullRunStderr(c *C) {
844 api, _, _ := s.fullRunHelper(c, `{
845 "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
846 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
849 "mounts": {"/tmp": {"kind": "tmp"} },
850 "output_path": "/tmp",
852 "runtime_constraints": {}
853 }`, nil, 1, func(t *TestDockerClient) {
854 t.logWriter.Write(dockerLog(1, "hello\n"))
855 t.logWriter.Write(dockerLog(2, "world\n"))
859 final := api.CalledWith("container.state", "Complete")
860 c.Assert(final, NotNil)
861 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
862 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
864 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
865 c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
868 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
869 api, _, _ := s.fullRunHelper(c, `{
871 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
874 "mounts": {"/tmp": {"kind": "tmp"} },
875 "output_path": "/tmp",
877 "runtime_constraints": {}
878 }`, nil, 0, func(t *TestDockerClient) {
879 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
883 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
884 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
885 c.Log(api.Logs["stdout"])
886 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
889 func (s *TestSuite) TestFullRunSetCwd(c *C) {
890 api, _, _ := s.fullRunHelper(c, `{
892 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
895 "mounts": {"/tmp": {"kind": "tmp"} },
896 "output_path": "/tmp",
898 "runtime_constraints": {}
899 }`, nil, 0, func(t *TestDockerClient) {
900 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
904 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
905 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
906 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
909 func (s *TestSuite) TestStopOnSignal(c *C) {
910 s.testStopContainer(c, func(cr *ContainerRunner) {
912 for !s.docker.calledWait {
913 time.Sleep(time.Millisecond)
915 cr.SigChan <- syscall.SIGINT
920 func (s *TestSuite) TestStopOnArvMountDeath(c *C) {
921 s.testStopContainer(c, func(cr *ContainerRunner) {
922 cr.ArvMountExit = make(chan error)
924 cr.ArvMountExit <- exec.Command("true").Run()
925 close(cr.ArvMountExit)
930 func (s *TestSuite) testStopContainer(c *C, setup func(cr *ContainerRunner)) {
932 "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
933 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
936 "mounts": {"/tmp": {"kind": "tmp"} },
937 "output_path": "/tmp",
939 "runtime_constraints": {}
942 rec := arvados.Container{}
943 err := json.Unmarshal([]byte(record), &rec)
946 s.docker.fn = func(t *TestDockerClient) {
948 t.logWriter.Write(dockerLog(1, "foo\n"))
951 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
953 api := &ArvTestClient{Container: rec}
954 cr := NewContainerRunner(api, &KeepTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
955 cr.RunArvMount = func([]string, string) (*exec.Cmd, error) { return nil, nil }
958 done := make(chan error)
963 case <-time.After(20 * time.Second):
964 pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
969 for k, v := range api.Logs {
974 c.Check(api.CalledWith("container.log", nil), NotNil)
975 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
976 c.Check(api.Logs["stdout"].String(), Matches, "(?ms).*foo\n$")
979 func (s *TestSuite) TestFullRunSetEnv(c *C) {
980 api, _, _ := s.fullRunHelper(c, `{
981 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
982 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
984 "environment": {"FROBIZ": "bilbo"},
985 "mounts": {"/tmp": {"kind": "tmp"} },
986 "output_path": "/tmp",
988 "runtime_constraints": {}
989 }`, nil, 0, func(t *TestDockerClient) {
990 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
994 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
995 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
996 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)
999 type ArvMountCmdLine struct {
1004 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
1010 func stubCert(temp string) string {
1011 path := temp + "/ca-certificates.crt"
1012 crt, _ := os.Create(path)
1014 arvadosclient.CertFiles = []string{path}
1018 func (s *TestSuite) TestSetupMounts(c *C) {
1019 api := &ArvTestClient{}
1020 kc := &KeepTestClient{}
1021 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1022 am := &ArvMountCmdLine{}
1023 cr.RunArvMount = am.ArvMountTest
1025 realTemp, err := ioutil.TempDir("", "crunchrun_test1-")
1026 c.Assert(err, IsNil)
1027 certTemp, err := ioutil.TempDir("", "crunchrun_test2-")
1028 c.Assert(err, IsNil)
1029 stubCertPath := stubCert(certTemp)
1031 cr.parentTemp = realTemp
1033 defer os.RemoveAll(realTemp)
1034 defer os.RemoveAll(certTemp)
1037 cr.MkTempDir = func(_ string, prefix string) (string, error) {
1039 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
1040 err := os.Mkdir(d, os.ModePerm)
1041 if err != nil && strings.Contains(err.Error(), ": file exists") {
1042 // Test case must have pre-populated the tempdir
1048 checkEmpty := func() {
1049 // Should be deleted.
1050 _, err := os.Stat(realTemp)
1051 c.Assert(os.IsNotExist(err), Equals, true)
1053 // Now recreate it for the next test.
1054 c.Assert(os.Mkdir(realTemp, 0777), IsNil)
1059 cr.ArvMountPoint = ""
1060 cr.Container.Mounts = make(map[string]arvados.Mount)
1061 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1062 cr.OutputPath = "/tmp"
1063 cr.statInterval = 5 * time.Second
1064 err := cr.SetupMounts()
1066 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1067 "--read-write", "--crunchstat-interval=5",
1068 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1069 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp"})
1070 os.RemoveAll(cr.ArvMountPoint)
1077 cr.ArvMountPoint = ""
1078 cr.Container.Mounts = make(map[string]arvados.Mount)
1079 cr.Container.Mounts["/out"] = arvados.Mount{Kind: "tmp"}
1080 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1081 cr.OutputPath = "/out"
1083 err := cr.SetupMounts()
1085 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1086 "--read-write", "--crunchstat-interval=5",
1087 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1088 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/out", realTemp + "/tmp3:/tmp"})
1089 os.RemoveAll(cr.ArvMountPoint)
1096 cr.ArvMountPoint = ""
1097 cr.Container.Mounts = make(map[string]arvados.Mount)
1098 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1099 cr.OutputPath = "/tmp"
1102 cr.Container.RuntimeConstraints.API = &apiflag
1104 err := cr.SetupMounts()
1106 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1107 "--read-write", "--crunchstat-interval=5",
1108 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1109 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", stubCertPath + ":/etc/arvados/ca-certificates.crt:ro"})
1110 os.RemoveAll(cr.ArvMountPoint)
1119 cr.ArvMountPoint = ""
1120 cr.Container.Mounts = map[string]arvados.Mount{
1121 "/keeptmp": {Kind: "collection", Writable: true},
1123 cr.OutputPath = "/keeptmp"
1125 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1127 err := cr.SetupMounts()
1129 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1130 "--read-write", "--crunchstat-interval=5",
1131 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1132 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/tmp0:/keeptmp"})
1133 os.RemoveAll(cr.ArvMountPoint)
1140 cr.ArvMountPoint = ""
1141 cr.Container.Mounts = map[string]arvados.Mount{
1142 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1143 "/keepout": {Kind: "collection", Writable: true},
1145 cr.OutputPath = "/keepout"
1147 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1148 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1150 err := cr.SetupMounts()
1152 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1153 "--read-write", "--crunchstat-interval=5",
1154 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1155 sort.StringSlice(cr.Binds).Sort()
1156 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1157 realTemp + "/keep1/tmp0:/keepout"})
1158 os.RemoveAll(cr.ArvMountPoint)
1165 cr.ArvMountPoint = ""
1166 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
1167 cr.Container.Mounts = map[string]arvados.Mount{
1168 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1169 "/keepout": {Kind: "collection", Writable: true},
1171 cr.OutputPath = "/keepout"
1173 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1174 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1176 err := cr.SetupMounts()
1178 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1179 "--read-write", "--crunchstat-interval=5",
1180 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1181 sort.StringSlice(cr.Binds).Sort()
1182 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1183 realTemp + "/keep1/tmp0:/keepout"})
1184 os.RemoveAll(cr.ArvMountPoint)
1189 for _, test := range []struct {
1193 {in: "foo", out: `"foo"`},
1194 {in: nil, out: `null`},
1195 {in: map[string]int64{"foo": 123456789123456789}, out: `{"foo":123456789123456789}`},
1198 cr.ArvMountPoint = ""
1199 cr.Container.Mounts = map[string]arvados.Mount{
1200 "/mnt/test.json": {Kind: "json", Content: test.in},
1202 err := cr.SetupMounts()
1204 sort.StringSlice(cr.Binds).Sort()
1205 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/json2/mountdata.json:/mnt/test.json:ro"})
1206 content, err := ioutil.ReadFile(realTemp + "/json2/mountdata.json")
1208 c.Check(content, DeepEquals, []byte(test.out))
1209 os.RemoveAll(cr.ArvMountPoint)
1214 for _, test := range []struct {
1218 {in: "foo", out: `foo`},
1219 {in: nil, out: "error"},
1220 {in: map[string]int64{"foo": 123456789123456789}, out: "error"},
1223 cr.ArvMountPoint = ""
1224 cr.Container.Mounts = map[string]arvados.Mount{
1225 "/mnt/test.txt": {Kind: "text", Content: test.in},
1227 err := cr.SetupMounts()
1228 if test.out == "error" {
1229 c.Check(err.Error(), Equals, "content for mount \"/mnt/test.txt\" must be a string")
1232 sort.StringSlice(cr.Binds).Sort()
1233 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/text2/mountdata.text:/mnt/test.txt:ro"})
1234 content, err := ioutil.ReadFile(realTemp + "/text2/mountdata.text")
1236 c.Check(content, DeepEquals, []byte(test.out))
1238 os.RemoveAll(cr.ArvMountPoint)
1243 // Read-only mount points are allowed underneath output_dir mount point
1246 cr.ArvMountPoint = ""
1247 cr.Container.Mounts = make(map[string]arvados.Mount)
1248 cr.Container.Mounts = map[string]arvados.Mount{
1249 "/tmp": {Kind: "tmp"},
1250 "/tmp/foo": {Kind: "collection"},
1252 cr.OutputPath = "/tmp"
1254 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1256 err := cr.SetupMounts()
1258 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1259 "--read-write", "--crunchstat-interval=5",
1260 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1261 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", realTemp + "/keep1/tmp0:/tmp/foo:ro"})
1262 os.RemoveAll(cr.ArvMountPoint)
1267 // Writable mount points copied to output_dir mount point
1270 cr.ArvMountPoint = ""
1271 cr.Container.Mounts = make(map[string]arvados.Mount)
1272 cr.Container.Mounts = map[string]arvados.Mount{
1273 "/tmp": {Kind: "tmp"},
1274 "/tmp/foo": {Kind: "collection",
1275 PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53",
1277 "/tmp/bar": {Kind: "collection",
1278 PortableDataHash: "59389a8f9ee9d399be35462a0f92541d+53",
1282 cr.OutputPath = "/tmp"
1284 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1285 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz", os.ModePerm)
1287 rf, _ := os.Create(realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz/quux")
1288 rf.Write([]byte("bar"))
1291 err := cr.SetupMounts()
1293 _, err = os.Stat(cr.HostOutputDir + "/foo")
1295 _, err = os.Stat(cr.HostOutputDir + "/bar/quux")
1297 os.RemoveAll(cr.ArvMountPoint)
1302 // Only mount points of kind 'collection' are allowed underneath output_dir mount point
1305 cr.ArvMountPoint = ""
1306 cr.Container.Mounts = make(map[string]arvados.Mount)
1307 cr.Container.Mounts = map[string]arvados.Mount{
1308 "/tmp": {Kind: "tmp"},
1309 "/tmp/foo": {Kind: "tmp"},
1311 cr.OutputPath = "/tmp"
1313 err := cr.SetupMounts()
1314 c.Check(err, NotNil)
1315 c.Check(err, ErrorMatches, `Only mount points of kind 'collection', 'text' or 'json' are supported underneath the output_path.*`)
1316 os.RemoveAll(cr.ArvMountPoint)
1321 // Only mount point of kind 'collection' is allowed for stdin
1324 cr.ArvMountPoint = ""
1325 cr.Container.Mounts = make(map[string]arvados.Mount)
1326 cr.Container.Mounts = map[string]arvados.Mount{
1327 "stdin": {Kind: "tmp"},
1330 err := cr.SetupMounts()
1331 c.Check(err, NotNil)
1332 c.Check(err, ErrorMatches, `Unsupported mount kind 'tmp' for stdin.*`)
1333 os.RemoveAll(cr.ArvMountPoint)
1341 cr.ArvMountPoint = ""
1342 (*GitMountSuite)(nil).useTestGitServer(c)
1343 cr.token = arvadostest.ActiveToken
1344 cr.Container.Mounts = make(map[string]arvados.Mount)
1345 cr.Container.Mounts = map[string]arvados.Mount{
1348 UUID: arvadostest.Repository2UUID,
1349 Commit: "fd3531f42995344f36c30b79f55f27b502f3d344",
1354 UUID: arvadostest.Repository2UUID,
1355 Commit: "5ebfab0522851df01fec11ec55a6d0f4877b542e",
1359 cr.OutputPath = "/tmp"
1361 err := cr.SetupMounts()
1364 // dirMap[mountpoint] == tmpdir
1365 dirMap := make(map[string]string)
1366 for _, bind := range cr.Binds {
1367 tokens := strings.Split(bind, ":")
1368 dirMap[tokens[1]] = tokens[0]
1370 if cr.Container.Mounts[tokens[1]].Writable {
1371 c.Check(len(tokens), Equals, 2)
1373 c.Check(len(tokens), Equals, 3)
1374 c.Check(tokens[2], Equals, "ro")
1378 data, err := ioutil.ReadFile(dirMap["/tip"] + "/dir1/dir2/file with mode 0644")
1380 c.Check(string(data), Equals, "\000\001\002\003")
1381 _, err = ioutil.ReadFile(dirMap["/tip"] + "/file only on testbranch")
1382 c.Check(err, FitsTypeOf, &os.PathError{})
1383 c.Check(os.IsNotExist(err), Equals, true)
1385 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/dir1/dir2/file with mode 0644")
1387 c.Check(string(data), Equals, "\000\001\002\003")
1388 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/file only on testbranch")
1390 c.Check(string(data), Equals, "testfile\n")
1397 func (s *TestSuite) TestStdout(c *C) {
1399 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1400 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1402 "environment": {"FROBIZ": "bilbo"},
1403 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1404 "output_path": "/tmp",
1406 "runtime_constraints": {}
1409 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1410 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1414 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1415 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1416 c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1419 // Used by the TestStdoutWithWrongPath*()
1420 func (s *TestSuite) stdoutErrorRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, err error) {
1421 rec := arvados.Container{}
1422 err = json.Unmarshal([]byte(record), &rec)
1426 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
1428 api = &ArvTestClient{Container: rec}
1429 cr = NewContainerRunner(api, &KeepTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1430 am := &ArvMountCmdLine{}
1431 cr.RunArvMount = am.ArvMountTest
1437 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1438 _, _, err := s.stdoutErrorRunHelper(c, `{
1439 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1440 "output_path": "/tmp"
1441 }`, func(t *TestDockerClient) {})
1443 c.Check(err, NotNil)
1444 c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
1447 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1448 _, _, err := s.stdoutErrorRunHelper(c, `{
1449 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1450 "output_path": "/tmp"
1451 }`, func(t *TestDockerClient) {})
1453 c.Check(err, NotNil)
1454 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'tmp' for stdout"), Equals, true)
1457 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1458 _, _, err := s.stdoutErrorRunHelper(c, `{
1459 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1460 "output_path": "/tmp"
1461 }`, func(t *TestDockerClient) {})
1463 c.Check(err, NotNil)
1464 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'collection' for stdout"), Equals, true)
1467 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1468 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1469 defer os.Unsetenv("ARVADOS_API_HOST")
1470 api, _, _ := s.fullRunHelper(c, `{
1471 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1472 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1475 "mounts": {"/tmp": {"kind": "tmp"} },
1476 "output_path": "/tmp",
1478 "runtime_constraints": {"API": true}
1479 }`, nil, 0, func(t *TestDockerClient) {
1480 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
1484 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1485 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1486 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "test.arvados.org\n"), Equals, true)
1487 c.Check(api.CalledWith("container.output", "d41d8cd98f00b204e9800998ecf8427e+0"), NotNil)
1490 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1491 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1492 defer os.Unsetenv("ARVADOS_API_HOST")
1493 api, _, _ := s.fullRunHelper(c, `{
1494 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1495 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1498 "mounts": {"/tmp": {"kind": "tmp"} },
1499 "output_path": "/tmp",
1501 "runtime_constraints": {"API": true}
1502 }`, nil, 0, func(t *TestDockerClient) {
1503 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
1507 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1508 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1509 c.Check(api.CalledWith("container.output", "d4ab34d3d4f8a72f5c4973051ae69fab+122"), NotNil)
1512 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1514 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1515 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1517 "environment": {"FROBIZ": "bilbo"},
1519 "/tmp": {"kind": "tmp"},
1520 "/tmp/foo": {"kind": "collection",
1521 "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1522 "exclude_from_output": true
1524 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1526 "output_path": "/tmp",
1528 "runtime_constraints": {}
1531 extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1533 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1534 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1538 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1539 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1540 c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1543 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1545 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1546 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1548 "environment": {"FROBIZ": "bilbo"},
1550 "/tmp": {"kind": "tmp"},
1551 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1552 "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1553 "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1554 "/tmp/foo/baz/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1555 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1557 "output_path": "/tmp",
1559 "runtime_constraints": {}
1562 extraMounts := []string{
1563 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1564 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1565 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1568 api, runner, realtemp := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1569 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1573 c.Check(runner.Binds, DeepEquals, []string{realtemp + "/tmp2:/tmp",
1574 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt:/tmp/foo/bar:ro",
1575 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt:/tmp/foo/baz/sub2file2:ro",
1576 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1:/tmp/foo/sub1:ro",
1577 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt:/tmp/foo/sub1file2:ro",
1580 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1581 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1582 for _, v := range api.Content {
1583 if v["collection"] != nil {
1584 c.Check(v["ensure_unique_name"], Equals, true)
1585 collection := v["collection"].(arvadosclient.Dict)
1586 if strings.Index(collection["name"].(string), "output") == 0 {
1587 manifest := collection["manifest_text"].(string)
1589 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1590 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 9:18:bar 9:18:sub1file2
1591 ./foo/baz 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2
1592 ./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1593 ./foo/sub1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1600 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
1602 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1603 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1605 "environment": {"FROBIZ": "bilbo"},
1607 "/tmp": {"kind": "tmp"},
1608 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt"},
1609 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1611 "output_path": "/tmp",
1613 "runtime_constraints": {}
1616 extraMounts := []string{
1617 "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1620 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1621 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1625 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1626 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1627 for _, v := range api.Content {
1628 if v["collection"] != nil {
1629 collection := v["collection"].(arvadosclient.Dict)
1630 if strings.Index(collection["name"].(string), "output") == 0 {
1631 manifest := collection["manifest_text"].(string)
1633 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1634 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 10:17:bar
1641 func (s *TestSuite) TestOutputSymlinkToInput(c *C) {
1643 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1644 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1646 "environment": {"FROBIZ": "bilbo"},
1648 "/tmp": {"kind": "tmp"},
1649 "/keep/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path": "/subdir1/file2_in_subdir1.txt"},
1650 "/keep/foo2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367"}
1652 "output_path": "/tmp",
1654 "runtime_constraints": {}
1657 extraMounts := []string{
1658 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1661 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1662 os.Symlink("/keep/foo/sub1file2", t.realTemp+"/tmp2/baz")
1663 os.Symlink("/keep/foo2/subdir1/file2_in_subdir1.txt", t.realTemp+"/tmp2/baz2")
1664 os.Symlink("/keep/foo2/subdir1", t.realTemp+"/tmp2/baz3")
1665 os.Mkdir(t.realTemp+"/tmp2/baz4", 0700)
1666 os.Symlink("/keep/foo2/subdir1/file2_in_subdir1.txt", t.realTemp+"/tmp2/baz4/baz5")
1670 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1671 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1672 for _, v := range api.Content {
1673 if v["collection"] != nil {
1674 collection := v["collection"].(arvadosclient.Dict)
1675 if strings.Index(collection["name"].(string), "output") == 0 {
1676 manifest := collection["manifest_text"].(string)
1677 c.Check(manifest, Equals, `. 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:baz 9:18:baz2
1678 ./baz3 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1679 ./baz3/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1680 ./baz4 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:baz5
1687 func (s *TestSuite) TestOutputError(c *C) {
1689 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1690 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1692 "environment": {"FROBIZ": "bilbo"},
1694 "/tmp": {"kind": "tmp"}
1696 "output_path": "/tmp",
1698 "runtime_constraints": {}
1701 extraMounts := []string{}
1703 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1704 os.Symlink("/etc/hosts", t.realTemp+"/tmp2/baz")
1708 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1711 func (s *TestSuite) TestOutputSymlinkToOutput(c *C) {
1713 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1714 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1716 "environment": {"FROBIZ": "bilbo"},
1718 "/tmp": {"kind": "tmp"}
1720 "output_path": "/tmp",
1722 "runtime_constraints": {}
1725 extraMounts := []string{}
1727 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1728 rf, _ := os.Create(t.realTemp + "/tmp2/realfile")
1729 rf.Write([]byte("foo"))
1732 os.Mkdir(t.realTemp+"/tmp2/realdir", 0700)
1733 rf, _ = os.Create(t.realTemp + "/tmp2/realdir/subfile")
1734 rf.Write([]byte("bar"))
1737 os.Symlink("/tmp/realfile", t.realTemp+"/tmp2/file1")
1738 os.Symlink("realfile", t.realTemp+"/tmp2/file2")
1739 os.Symlink("/tmp/file1", t.realTemp+"/tmp2/file3")
1740 os.Symlink("file2", t.realTemp+"/tmp2/file4")
1741 os.Symlink("realdir", t.realTemp+"/tmp2/dir1")
1742 os.Symlink("/tmp/realdir", t.realTemp+"/tmp2/dir2")
1746 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1747 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1748 for _, v := range api.Content {
1749 if v["collection"] != nil {
1750 collection := v["collection"].(arvadosclient.Dict)
1751 if strings.Index(collection["name"].(string), "output") == 0 {
1752 manifest := collection["manifest_text"].(string)
1753 c.Check(manifest, Equals,
1754 `. 7a2c86e102dcc231bd232aad99686dfa+15 0:3:file1 3:3:file2 6:3:file3 9:3:file4 12:3:realfile
1755 ./dir1 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1756 ./dir2 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1757 ./realdir 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1764 func (s *TestSuite) TestStdinCollectionMountPoint(c *C) {
1766 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1767 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1769 "environment": {"FROBIZ": "bilbo"},
1771 "/tmp": {"kind": "tmp"},
1772 "stdin": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/file1_in_main.txt"},
1773 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1775 "output_path": "/tmp",
1777 "runtime_constraints": {}
1780 extraMounts := []string{
1781 "b0def87f80dd594d4675809e83bd4f15+367/file1_in_main.txt",
1784 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1785 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1789 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1790 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1791 for _, v := range api.Content {
1792 if v["collection"] != nil {
1793 collection := v["collection"].(arvadosclient.Dict)
1794 if strings.Index(collection["name"].(string), "output") == 0 {
1795 manifest := collection["manifest_text"].(string)
1796 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1803 func (s *TestSuite) TestStdinJsonMountPoint(c *C) {
1805 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1806 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1808 "environment": {"FROBIZ": "bilbo"},
1810 "/tmp": {"kind": "tmp"},
1811 "stdin": {"kind": "json", "content": "foo"},
1812 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1814 "output_path": "/tmp",
1816 "runtime_constraints": {}
1819 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1820 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1824 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1825 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1826 for _, v := range api.Content {
1827 if v["collection"] != nil {
1828 collection := v["collection"].(arvadosclient.Dict)
1829 if strings.Index(collection["name"].(string), "output") == 0 {
1830 manifest := collection["manifest_text"].(string)
1831 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1838 func (s *TestSuite) TestStderrMount(c *C) {
1839 api, _, _ := s.fullRunHelper(c, `{
1840 "command": ["/bin/sh", "-c", "echo hello;exit 1"],
1841 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1844 "mounts": {"/tmp": {"kind": "tmp"},
1845 "stdout": {"kind": "file", "path": "/tmp/a/out.txt"},
1846 "stderr": {"kind": "file", "path": "/tmp/b/err.txt"}},
1847 "output_path": "/tmp",
1849 "runtime_constraints": {}
1850 }`, nil, 1, func(t *TestDockerClient) {
1851 t.logWriter.Write(dockerLog(1, "hello\n"))
1852 t.logWriter.Write(dockerLog(2, "oops\n"))
1856 final := api.CalledWith("container.state", "Complete")
1857 c.Assert(final, NotNil)
1858 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1859 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1861 c.Check(api.CalledWith("collection.manifest_text", "./a b1946ac92492d2347c6235b4d2611184+6 0:6:out.txt\n./b 38af5c54926b620264ab1501150cf189+5 0:5:err.txt\n"), NotNil)
1864 func (s *TestSuite) TestNumberRoundTrip(c *C) {
1865 cr := NewContainerRunner(&ArvTestClient{callraw: true}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1866 cr.fetchContainerRecord()
1868 jsondata, err := json.Marshal(cr.Container.Mounts["/json"].Content)
1871 c.Check(string(jsondata), Equals, `{"number":123456789123456789}`)
1874 func (s *TestSuite) TestEvalSymlinks(c *C) {
1875 cr := NewContainerRunner(&ArvTestClient{callraw: true}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1877 realTemp, err := ioutil.TempDir("", "crunchrun_test-")
1878 c.Assert(err, IsNil)
1879 defer os.RemoveAll(realTemp)
1881 cr.HostOutputDir = realTemp
1883 // Absolute path outside output dir
1884 os.Symlink("/etc/passwd", realTemp+"/p1")
1886 // Relative outside output dir
1887 os.Symlink("../zip", realTemp+"/p2")
1889 // Circular references
1890 os.Symlink("p4", realTemp+"/p3")
1891 os.Symlink("p5", realTemp+"/p4")
1892 os.Symlink("p3", realTemp+"/p5")
1894 // Target doesn't exist
1895 os.Symlink("p99", realTemp+"/p6")
1897 for _, v := range []string{"p1", "p2", "p3", "p4", "p5"} {
1898 info, err := os.Lstat(realTemp + "/" + v)
1899 _, _, _, err = cr.derefOutputSymlink(realTemp+"/"+v, info)
1900 c.Assert(err, NotNil)
1904 func (s *TestSuite) TestEvalSymlinkDir(c *C) {
1905 cr := NewContainerRunner(&ArvTestClient{callraw: true}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1907 realTemp, err := ioutil.TempDir("", "crunchrun_test-")
1908 c.Assert(err, IsNil)
1909 defer os.RemoveAll(realTemp)
1911 cr.HostOutputDir = realTemp
1913 // Absolute path outside output dir
1914 os.Symlink(".", realTemp+"/loop")
1917 info, err := os.Lstat(realTemp + "/" + v)
1918 _, err = cr.UploadOutputFile(realTemp+"/"+v, info, err, []string{}, nil, "", "", 0)
1919 c.Assert(err, NotNil)
1922 func (s *TestSuite) TestFullBrokenDocker1(c *C) {
1923 tf, err := ioutil.TempFile("", "brokenNodeHook-")
1924 c.Assert(err, IsNil)
1925 defer os.Remove(tf.Name())
1927 tf.Write([]byte(`#!/bin/sh
1931 os.Chmod(tf.Name(), 0700)
1934 brokenNodeHook = &ech
1936 api, _, _ := s.fullRunHelper(c, `{
1937 "command": ["echo", "hello world"],
1938 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1941 "mounts": {"/tmp": {"kind": "tmp"} },
1942 "output_path": "/tmp",
1944 "runtime_constraints": {}
1945 }`, nil, 2, func(t *TestDockerClient) {
1946 t.logWriter.Write(dockerLog(1, "hello world\n"))
1950 c.Check(api.CalledWith("container.state", "Queued"), NotNil)
1951 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1952 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Running broken node hook.*")
1953 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*killme.*")
1957 func (s *TestSuite) TestFullBrokenDocker2(c *C) {
1959 brokenNodeHook = &ech
1961 api, _, _ := s.fullRunHelper(c, `{
1962 "command": ["echo", "hello world"],
1963 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1966 "mounts": {"/tmp": {"kind": "tmp"} },
1967 "output_path": "/tmp",
1969 "runtime_constraints": {}
1970 }`, nil, 2, func(t *TestDockerClient) {
1971 t.logWriter.Write(dockerLog(1, "hello world\n"))
1975 c.Check(api.CalledWith("container.state", "Queued"), NotNil)
1976 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1977 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*No broken node hook.*")
1980 func (s *TestSuite) TestFullBrokenDocker3(c *C) {
1982 brokenNodeHook = &ech
1984 api, _, _ := s.fullRunHelper(c, `{
1985 "command": ["echo", "hello world"],
1986 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1989 "mounts": {"/tmp": {"kind": "tmp"} },
1990 "output_path": "/tmp",
1992 "runtime_constraints": {}
1993 }`, nil, 3, func(t *TestDockerClient) {
1994 t.logWriter.Write(dockerLog(1, "hello world\n"))
1998 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1999 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
2002 func (s *TestSuite) TestBadCommand1(c *C) {
2004 brokenNodeHook = &ech
2006 api, _, _ := s.fullRunHelper(c, `{
2007 "command": ["echo", "hello world"],
2008 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2011 "mounts": {"/tmp": {"kind": "tmp"} },
2012 "output_path": "/tmp",
2014 "runtime_constraints": {}
2015 }`, nil, 4, func(t *TestDockerClient) {
2016 t.logWriter.Write(dockerLog(1, "hello world\n"))
2020 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2021 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2024 func (s *TestSuite) TestBadCommand2(c *C) {
2026 brokenNodeHook = &ech
2028 api, _, _ := s.fullRunHelper(c, `{
2029 "command": ["echo", "hello world"],
2030 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2033 "mounts": {"/tmp": {"kind": "tmp"} },
2034 "output_path": "/tmp",
2036 "runtime_constraints": {}
2037 }`, nil, 5, func(t *TestDockerClient) {
2038 t.logWriter.Write(dockerLog(1, "hello world\n"))
2042 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2043 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2046 func (s *TestSuite) TestBadCommand3(c *C) {
2048 brokenNodeHook = &ech
2050 api, _, _ := s.fullRunHelper(c, `{
2051 "command": ["echo", "hello world"],
2052 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2055 "mounts": {"/tmp": {"kind": "tmp"} },
2056 "output_path": "/tmp",
2058 "runtime_constraints": {}
2059 }`, nil, 6, func(t *TestDockerClient) {
2060 t.logWriter.Write(dockerLog(1, "hello world\n"))
2064 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2065 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2068 func (s *TestSuite) TestSecretTextMountPoint(c *C) {
2069 // under normal mounts, gets captured in output, oops
2071 "command": ["true"],
2072 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2075 "/tmp": {"kind": "tmp"},
2076 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2080 "output_path": "/tmp",
2082 "runtime_constraints": {}
2085 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2089 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2090 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2091 c.Check(api.CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), NotNil)
2092 c.Check(api.CalledWith("collection.manifest_text", ""), IsNil)
2094 // under secret mounts, not captured in output
2096 "command": ["true"],
2097 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2100 "/tmp": {"kind": "tmp"}
2103 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2105 "output_path": "/tmp",
2107 "runtime_constraints": {}
2110 api, _, _ = s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2114 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2115 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2116 c.Check(api.CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), IsNil)
2117 c.Check(api.CalledWith("collection.manifest_text", ""), NotNil)