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 type FileWrapper struct {
372 func (fw FileWrapper) Readdir(n int) ([]os.FileInfo, error) {
373 return nil, errors.New("not implemented")
376 func (fw FileWrapper) Seek(int64, int) (int64, error) {
377 return 0, errors.New("not implemented")
380 func (fw FileWrapper) Size() int64 {
384 func (fw FileWrapper) Stat() (os.FileInfo, error) {
385 return nil, errors.New("not implemented")
388 func (fw FileWrapper) Truncate(int64) error {
389 return errors.New("not implemented")
392 func (fw FileWrapper) Write([]byte) (int, error) {
393 return 0, errors.New("not implemented")
396 func (client *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
397 if filename == hwImageId+".tar" {
398 rdr := ioutil.NopCloser(&bytes.Buffer{})
400 return FileWrapper{rdr, 1321984}, nil
401 } else if filename == "/file1_in_main.txt" {
402 rdr := ioutil.NopCloser(strings.NewReader("foo"))
404 return FileWrapper{rdr, 3}, nil
409 func (s *TestSuite) TestLoadImage(c *C) {
410 kc := &KeepTestClient{}
411 cr := NewContainerRunner(&ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
413 _, err := cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
415 _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
418 cr.Container.ContainerImage = hwPDH
420 // (1) Test loading image from keep
421 c.Check(kc.Called, Equals, false)
422 c.Check(cr.ContainerConfig.Image, Equals, "")
428 cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
431 c.Check(kc.Called, Equals, true)
432 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
434 _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
437 // (2) Test using image that's already loaded
439 cr.ContainerConfig.Image = ""
443 c.Check(kc.Called, Equals, false)
444 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
448 type ArvErrorTestClient struct{}
450 func (ArvErrorTestClient) Create(resourceType string,
451 parameters arvadosclient.Dict,
452 output interface{}) error {
456 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
457 return errors.New("ArvError")
460 func (ArvErrorTestClient) CallRaw(method, resourceType, uuid, action string,
461 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
462 return nil, errors.New("ArvError")
465 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
466 return errors.New("ArvError")
469 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
473 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
474 return discoveryMap[key], nil
477 type KeepErrorTestClient struct{}
479 func (KeepErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
480 return "", 0, errors.New("KeepError")
483 func (KeepErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
484 return nil, errors.New("KeepError")
487 func (KeepErrorTestClient) ClearBlockCache() {
490 type KeepReadErrorTestClient struct{}
492 func (KeepReadErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
496 func (KeepReadErrorTestClient) ClearBlockCache() {
499 type ErrorReader struct {
503 func (ErrorReader) Read(p []byte) (n int, err error) {
504 return 0, errors.New("ErrorReader")
507 func (ErrorReader) Seek(int64, int) (int64, error) {
508 return 0, errors.New("ErrorReader")
511 func (KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
512 return ErrorReader{}, nil
515 func (s *TestSuite) TestLoadImageArvError(c *C) {
517 cr := NewContainerRunner(ArvErrorTestClient{}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
518 cr.Container.ContainerImage = hwPDH
520 err := cr.LoadImage()
521 c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
524 func (s *TestSuite) TestLoadImageKeepError(c *C) {
526 cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
527 cr.Container.ContainerImage = hwPDH
529 err := cr.LoadImage()
530 c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
533 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
534 // (3) Collection doesn't contain image
535 cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
536 cr.Container.ContainerImage = otherPDH
538 err := cr.LoadImage()
539 c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
542 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
543 // (4) Collection doesn't contain image
544 cr := NewContainerRunner(&ArvTestClient{}, KeepReadErrorTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
545 cr.Container.ContainerImage = hwPDH
547 err := cr.LoadImage()
551 type ClosableBuffer struct {
555 func (*ClosableBuffer) Close() error {
559 type TestLogs struct {
560 Stdout ClosableBuffer
561 Stderr ClosableBuffer
564 func (tl *TestLogs) NewTestLoggingWriter(logstr string) io.WriteCloser {
565 if logstr == "stdout" {
568 if logstr == "stderr" {
574 func dockerLog(fd byte, msg string) []byte {
576 header := make([]byte, 8+len(by))
578 header[7] = byte(len(by))
583 func (s *TestSuite) TestRunContainer(c *C) {
584 s.docker.fn = func(t *TestDockerClient) {
585 t.logWriter.Write(dockerLog(1, "Hello world\n"))
588 cr := NewContainerRunner(&ArvTestClient{}, &KeepTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
591 cr.NewLogWriter = logs.NewTestLoggingWriter
592 cr.Container.ContainerImage = hwPDH
593 cr.Container.Command = []string{"./hw"}
594 err := cr.LoadImage()
597 err = cr.CreateContainer()
600 err = cr.StartContainer()
603 err = cr.WaitFinish()
606 c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
607 c.Check(logs.Stderr.String(), Equals, "")
610 func (s *TestSuite) TestCommitLogs(c *C) {
611 api := &ArvTestClient{}
612 kc := &KeepTestClient{}
613 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
614 cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
616 cr.CrunchLog.Print("Hello world!")
617 cr.CrunchLog.Print("Goodbye")
618 cr.finalState = "Complete"
620 err := cr.CommitLogs()
623 c.Check(api.Calls, Equals, 2)
624 c.Check(api.Content[1]["ensure_unique_name"], Equals, true)
625 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
626 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
627 c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
630 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
631 api := &ArvTestClient{}
632 kc := &KeepTestClient{}
633 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
635 err := cr.UpdateContainerRunning()
638 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
641 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
642 api := &ArvTestClient{}
643 kc := &KeepTestClient{}
644 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
646 cr.LogsPDH = new(string)
647 *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
649 cr.ExitCode = new(int)
651 cr.finalState = "Complete"
653 err := cr.UpdateContainerFinal()
656 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
657 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
658 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
661 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
662 api := &ArvTestClient{}
663 kc := &KeepTestClient{}
664 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
666 cr.finalState = "Cancelled"
668 err := cr.UpdateContainerFinal()
671 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
672 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
673 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
676 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
677 // dress rehearsal of the Run() function, starting from a JSON container record.
678 func (s *TestSuite) fullRunHelper(c *C, record string, extraMounts []string, exitCode int, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, realTemp string) {
679 rec := arvados.Container{}
680 err := json.Unmarshal([]byte(record), &rec)
684 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
686 err = json.Unmarshal([]byte(record), &sm)
688 secretMounts, err := json.Marshal(sm)
689 log.Printf("%q %q", sm, secretMounts)
692 s.docker.exitCode = exitCode
694 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
696 api = &ArvTestClient{Container: rec}
698 cr = NewContainerRunner(api, &KeepTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
699 cr.statInterval = 100 * time.Millisecond
700 am := &ArvMountCmdLine{}
701 cr.RunArvMount = am.ArvMountTest
703 realTemp, err = ioutil.TempDir("", "crunchrun_test1-")
705 defer os.RemoveAll(realTemp)
707 s.docker.realTemp = realTemp
710 cr.MkTempDir = func(_ string, prefix string) (string, error) {
712 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, tempcount)
713 err := os.Mkdir(d, os.ModePerm)
714 if err != nil && strings.Contains(err.Error(), ": file exists") {
715 // Test case must have pre-populated the tempdir
720 cr.MkArvClient = func(token string) (IArvadosClient, error) {
721 return &ArvTestClient{secretMounts: secretMounts}, nil
724 if extraMounts != nil && len(extraMounts) > 0 {
725 err := cr.SetupArvMountPoint("keep")
728 for _, m := range extraMounts {
729 os.MkdirAll(cr.ArvMountPoint+"/by_id/"+m, os.ModePerm)
734 if api.CalledWith("container.state", "Complete") != nil {
738 c.Check(api.WasSetRunning, Equals, true)
739 c.Check(api.Content[api.Calls-2]["container"].(arvadosclient.Dict)["log"], NotNil)
743 for k, v := range api.Logs {
752 func (s *TestSuite) TestFullRunHello(c *C) {
753 api, _, _ := s.fullRunHelper(c, `{
754 "command": ["echo", "hello world"],
755 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
758 "mounts": {"/tmp": {"kind": "tmp"} },
759 "output_path": "/tmp",
761 "runtime_constraints": {}
762 }`, nil, 0, func(t *TestDockerClient) {
763 t.logWriter.Write(dockerLog(1, "hello world\n"))
767 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
768 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
769 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
773 func (s *TestSuite) TestCrunchstat(c *C) {
774 api, _, _ := s.fullRunHelper(c, `{
775 "command": ["sleep", "1"],
776 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
779 "mounts": {"/tmp": {"kind": "tmp"} },
780 "output_path": "/tmp",
782 "runtime_constraints": {}
783 }`, nil, 0, func(t *TestDockerClient) {
784 time.Sleep(time.Second)
788 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
789 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
791 // We didn't actually start a container, so crunchstat didn't
792 // find accounting files and therefore didn't log any stats.
793 // It should have logged a "can't find accounting files"
794 // message after one poll interval, though, so we can confirm
796 c.Assert(api.Logs["crunchstat"], NotNil)
797 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
799 // The "files never appeared" log assures us that we called
800 // (*crunchstat.Reporter)Stop(), and that we set it up with
801 // the correct container ID "abcde":
802 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files never appeared for abcde\n`)
805 func (s *TestSuite) TestNodeInfoLog(c *C) {
806 os.Setenv("SLURMD_NODENAME", "compute2")
807 api, _, _ := s.fullRunHelper(c, `{
808 "command": ["sleep", "1"],
809 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
812 "mounts": {"/tmp": {"kind": "tmp"} },
813 "output_path": "/tmp",
815 "runtime_constraints": {}
817 func(t *TestDockerClient) {
818 time.Sleep(time.Second)
822 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
823 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
825 c.Assert(api.Logs["node"], NotNil)
826 json := api.Logs["node"].String()
827 c.Check(json, Matches, `(?ms).*"uuid": *"zzzzz-7ekkf-2z3mc76g2q73aio".*`)
828 c.Check(json, Matches, `(?ms).*"total_cpu_cores": *16.*`)
829 c.Check(json, Not(Matches), `(?ms).*"info":.*`)
831 c.Assert(api.Logs["node-info"], NotNil)
832 json = api.Logs["node-info"].String()
833 c.Check(json, Matches, `(?ms).*Host Information.*`)
834 c.Check(json, Matches, `(?ms).*CPU Information.*`)
835 c.Check(json, Matches, `(?ms).*Memory Information.*`)
836 c.Check(json, Matches, `(?ms).*Disk Space.*`)
837 c.Check(json, Matches, `(?ms).*Disk INodes.*`)
840 func (s *TestSuite) TestContainerRecordLog(c *C) {
841 api, _, _ := s.fullRunHelper(c, `{
842 "command": ["sleep", "1"],
843 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
846 "mounts": {"/tmp": {"kind": "tmp"} },
847 "output_path": "/tmp",
849 "runtime_constraints": {}
851 func(t *TestDockerClient) {
852 time.Sleep(time.Second)
856 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
857 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
859 c.Assert(api.Logs["container"], NotNil)
860 c.Check(api.Logs["container"].String(), Matches, `(?ms).*container_image.*`)
863 func (s *TestSuite) TestFullRunStderr(c *C) {
864 api, _, _ := s.fullRunHelper(c, `{
865 "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
866 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
869 "mounts": {"/tmp": {"kind": "tmp"} },
870 "output_path": "/tmp",
872 "runtime_constraints": {}
873 }`, nil, 1, func(t *TestDockerClient) {
874 t.logWriter.Write(dockerLog(1, "hello\n"))
875 t.logWriter.Write(dockerLog(2, "world\n"))
879 final := api.CalledWith("container.state", "Complete")
880 c.Assert(final, NotNil)
881 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
882 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
884 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
885 c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
888 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
889 api, _, _ := s.fullRunHelper(c, `{
891 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
894 "mounts": {"/tmp": {"kind": "tmp"} },
895 "output_path": "/tmp",
897 "runtime_constraints": {}
898 }`, nil, 0, func(t *TestDockerClient) {
899 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
903 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
904 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
905 c.Log(api.Logs["stdout"])
906 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
909 func (s *TestSuite) TestFullRunSetCwd(c *C) {
910 api, _, _ := s.fullRunHelper(c, `{
912 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
915 "mounts": {"/tmp": {"kind": "tmp"} },
916 "output_path": "/tmp",
918 "runtime_constraints": {}
919 }`, nil, 0, func(t *TestDockerClient) {
920 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
924 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
925 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
926 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
929 func (s *TestSuite) TestStopOnSignal(c *C) {
930 s.testStopContainer(c, func(cr *ContainerRunner) {
932 for !s.docker.calledWait {
933 time.Sleep(time.Millisecond)
935 cr.SigChan <- syscall.SIGINT
940 func (s *TestSuite) TestStopOnArvMountDeath(c *C) {
941 s.testStopContainer(c, func(cr *ContainerRunner) {
942 cr.ArvMountExit = make(chan error)
944 cr.ArvMountExit <- exec.Command("true").Run()
945 close(cr.ArvMountExit)
950 func (s *TestSuite) testStopContainer(c *C, setup func(cr *ContainerRunner)) {
952 "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
953 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
956 "mounts": {"/tmp": {"kind": "tmp"} },
957 "output_path": "/tmp",
959 "runtime_constraints": {}
962 rec := arvados.Container{}
963 err := json.Unmarshal([]byte(record), &rec)
966 s.docker.fn = func(t *TestDockerClient) {
968 t.logWriter.Write(dockerLog(1, "foo\n"))
971 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
973 api := &ArvTestClient{Container: rec}
974 cr := NewContainerRunner(api, &KeepTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
975 cr.RunArvMount = func([]string, string) (*exec.Cmd, error) { return nil, nil }
976 cr.MkArvClient = func(token string) (IArvadosClient, error) {
977 return &ArvTestClient{}, nil
981 done := make(chan error)
986 case <-time.After(20 * time.Second):
987 pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
992 for k, v := range api.Logs {
997 c.Check(api.CalledWith("container.log", nil), NotNil)
998 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
999 c.Check(api.Logs["stdout"].String(), Matches, "(?ms).*foo\n$")
1002 func (s *TestSuite) TestFullRunSetEnv(c *C) {
1003 api, _, _ := s.fullRunHelper(c, `{
1004 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1005 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1007 "environment": {"FROBIZ": "bilbo"},
1008 "mounts": {"/tmp": {"kind": "tmp"} },
1009 "output_path": "/tmp",
1011 "runtime_constraints": {}
1012 }`, nil, 0, func(t *TestDockerClient) {
1013 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1017 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1018 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1019 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)
1022 type ArvMountCmdLine struct {
1027 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
1033 func stubCert(temp string) string {
1034 path := temp + "/ca-certificates.crt"
1035 crt, _ := os.Create(path)
1037 arvadosclient.CertFiles = []string{path}
1041 func (s *TestSuite) TestSetupMounts(c *C) {
1042 api := &ArvTestClient{}
1043 kc := &KeepTestClient{}
1044 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1045 am := &ArvMountCmdLine{}
1046 cr.RunArvMount = am.ArvMountTest
1048 realTemp, err := ioutil.TempDir("", "crunchrun_test1-")
1049 c.Assert(err, IsNil)
1050 certTemp, err := ioutil.TempDir("", "crunchrun_test2-")
1051 c.Assert(err, IsNil)
1052 stubCertPath := stubCert(certTemp)
1054 cr.parentTemp = realTemp
1056 defer os.RemoveAll(realTemp)
1057 defer os.RemoveAll(certTemp)
1060 cr.MkTempDir = func(_ string, prefix string) (string, error) {
1062 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
1063 err := os.Mkdir(d, os.ModePerm)
1064 if err != nil && strings.Contains(err.Error(), ": file exists") {
1065 // Test case must have pre-populated the tempdir
1071 checkEmpty := func() {
1072 // Should be deleted.
1073 _, err := os.Stat(realTemp)
1074 c.Assert(os.IsNotExist(err), Equals, true)
1076 // Now recreate it for the next test.
1077 c.Assert(os.Mkdir(realTemp, 0777), IsNil)
1082 cr.ArvMountPoint = ""
1083 cr.Container.Mounts = make(map[string]arvados.Mount)
1084 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1085 cr.OutputPath = "/tmp"
1086 cr.statInterval = 5 * time.Second
1087 err := cr.SetupMounts()
1089 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1090 "--read-write", "--crunchstat-interval=5",
1091 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1092 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp"})
1093 os.RemoveAll(cr.ArvMountPoint)
1100 cr.ArvMountPoint = ""
1101 cr.Container.Mounts = make(map[string]arvados.Mount)
1102 cr.Container.Mounts["/out"] = arvados.Mount{Kind: "tmp"}
1103 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1104 cr.OutputPath = "/out"
1106 err := cr.SetupMounts()
1108 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1109 "--read-write", "--crunchstat-interval=5",
1110 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1111 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/out", realTemp + "/tmp3:/tmp"})
1112 os.RemoveAll(cr.ArvMountPoint)
1119 cr.ArvMountPoint = ""
1120 cr.Container.Mounts = make(map[string]arvados.Mount)
1121 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1122 cr.OutputPath = "/tmp"
1125 cr.Container.RuntimeConstraints.API = &apiflag
1127 err := cr.SetupMounts()
1129 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1130 "--read-write", "--crunchstat-interval=5",
1131 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1132 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", stubCertPath + ":/etc/arvados/ca-certificates.crt:ro"})
1133 os.RemoveAll(cr.ArvMountPoint)
1142 cr.ArvMountPoint = ""
1143 cr.Container.Mounts = map[string]arvados.Mount{
1144 "/keeptmp": {Kind: "collection", Writable: true},
1146 cr.OutputPath = "/keeptmp"
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 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/tmp0:/keeptmp"})
1156 os.RemoveAll(cr.ArvMountPoint)
1163 cr.ArvMountPoint = ""
1164 cr.Container.Mounts = map[string]arvados.Mount{
1165 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1166 "/keepout": {Kind: "collection", Writable: true},
1168 cr.OutputPath = "/keepout"
1170 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1171 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1173 err := cr.SetupMounts()
1175 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1176 "--read-write", "--crunchstat-interval=5",
1177 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1178 sort.StringSlice(cr.Binds).Sort()
1179 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1180 realTemp + "/keep1/tmp0:/keepout"})
1181 os.RemoveAll(cr.ArvMountPoint)
1188 cr.ArvMountPoint = ""
1189 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
1190 cr.Container.Mounts = map[string]arvados.Mount{
1191 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1192 "/keepout": {Kind: "collection", Writable: true},
1194 cr.OutputPath = "/keepout"
1196 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1197 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1199 err := cr.SetupMounts()
1201 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1202 "--read-write", "--crunchstat-interval=5",
1203 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1204 sort.StringSlice(cr.Binds).Sort()
1205 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1206 realTemp + "/keep1/tmp0:/keepout"})
1207 os.RemoveAll(cr.ArvMountPoint)
1212 for _, test := range []struct {
1216 {in: "foo", out: `"foo"`},
1217 {in: nil, out: `null`},
1218 {in: map[string]int64{"foo": 123456789123456789}, out: `{"foo":123456789123456789}`},
1221 cr.ArvMountPoint = ""
1222 cr.Container.Mounts = map[string]arvados.Mount{
1223 "/mnt/test.json": {Kind: "json", Content: test.in},
1225 err := cr.SetupMounts()
1227 sort.StringSlice(cr.Binds).Sort()
1228 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/json2/mountdata.json:/mnt/test.json:ro"})
1229 content, err := ioutil.ReadFile(realTemp + "/json2/mountdata.json")
1231 c.Check(content, DeepEquals, []byte(test.out))
1232 os.RemoveAll(cr.ArvMountPoint)
1237 for _, test := range []struct {
1241 {in: "foo", out: `foo`},
1242 {in: nil, out: "error"},
1243 {in: map[string]int64{"foo": 123456789123456789}, out: "error"},
1246 cr.ArvMountPoint = ""
1247 cr.Container.Mounts = map[string]arvados.Mount{
1248 "/mnt/test.txt": {Kind: "text", Content: test.in},
1250 err := cr.SetupMounts()
1251 if test.out == "error" {
1252 c.Check(err.Error(), Equals, "content for mount \"/mnt/test.txt\" must be a string")
1255 sort.StringSlice(cr.Binds).Sort()
1256 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/text2/mountdata.text:/mnt/test.txt:ro"})
1257 content, err := ioutil.ReadFile(realTemp + "/text2/mountdata.text")
1259 c.Check(content, DeepEquals, []byte(test.out))
1261 os.RemoveAll(cr.ArvMountPoint)
1266 // Read-only mount points are allowed underneath output_dir mount point
1269 cr.ArvMountPoint = ""
1270 cr.Container.Mounts = make(map[string]arvados.Mount)
1271 cr.Container.Mounts = map[string]arvados.Mount{
1272 "/tmp": {Kind: "tmp"},
1273 "/tmp/foo": {Kind: "collection"},
1275 cr.OutputPath = "/tmp"
1277 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1279 err := cr.SetupMounts()
1281 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1282 "--read-write", "--crunchstat-interval=5",
1283 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1284 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", realTemp + "/keep1/tmp0:/tmp/foo:ro"})
1285 os.RemoveAll(cr.ArvMountPoint)
1290 // Writable mount points copied to output_dir mount point
1293 cr.ArvMountPoint = ""
1294 cr.Container.Mounts = make(map[string]arvados.Mount)
1295 cr.Container.Mounts = map[string]arvados.Mount{
1296 "/tmp": {Kind: "tmp"},
1297 "/tmp/foo": {Kind: "collection",
1298 PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53",
1300 "/tmp/bar": {Kind: "collection",
1301 PortableDataHash: "59389a8f9ee9d399be35462a0f92541d+53",
1305 cr.OutputPath = "/tmp"
1307 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1308 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz", os.ModePerm)
1310 rf, _ := os.Create(realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz/quux")
1311 rf.Write([]byte("bar"))
1314 err := cr.SetupMounts()
1316 _, err = os.Stat(cr.HostOutputDir + "/foo")
1318 _, err = os.Stat(cr.HostOutputDir + "/bar/quux")
1320 os.RemoveAll(cr.ArvMountPoint)
1325 // Only mount points of kind 'collection' are allowed underneath output_dir mount point
1328 cr.ArvMountPoint = ""
1329 cr.Container.Mounts = make(map[string]arvados.Mount)
1330 cr.Container.Mounts = map[string]arvados.Mount{
1331 "/tmp": {Kind: "tmp"},
1332 "/tmp/foo": {Kind: "tmp"},
1334 cr.OutputPath = "/tmp"
1336 err := cr.SetupMounts()
1337 c.Check(err, NotNil)
1338 c.Check(err, ErrorMatches, `Only mount points of kind 'collection', 'text' or 'json' are supported underneath the output_path.*`)
1339 os.RemoveAll(cr.ArvMountPoint)
1344 // Only mount point of kind 'collection' is allowed for stdin
1347 cr.ArvMountPoint = ""
1348 cr.Container.Mounts = make(map[string]arvados.Mount)
1349 cr.Container.Mounts = map[string]arvados.Mount{
1350 "stdin": {Kind: "tmp"},
1353 err := cr.SetupMounts()
1354 c.Check(err, NotNil)
1355 c.Check(err, ErrorMatches, `Unsupported mount kind 'tmp' for stdin.*`)
1356 os.RemoveAll(cr.ArvMountPoint)
1364 cr.ArvMountPoint = ""
1365 (*GitMountSuite)(nil).useTestGitServer(c)
1366 cr.token = arvadostest.ActiveToken
1367 cr.Container.Mounts = make(map[string]arvados.Mount)
1368 cr.Container.Mounts = map[string]arvados.Mount{
1371 UUID: arvadostest.Repository2UUID,
1372 Commit: "fd3531f42995344f36c30b79f55f27b502f3d344",
1377 UUID: arvadostest.Repository2UUID,
1378 Commit: "5ebfab0522851df01fec11ec55a6d0f4877b542e",
1382 cr.OutputPath = "/tmp"
1384 err := cr.SetupMounts()
1387 // dirMap[mountpoint] == tmpdir
1388 dirMap := make(map[string]string)
1389 for _, bind := range cr.Binds {
1390 tokens := strings.Split(bind, ":")
1391 dirMap[tokens[1]] = tokens[0]
1393 if cr.Container.Mounts[tokens[1]].Writable {
1394 c.Check(len(tokens), Equals, 2)
1396 c.Check(len(tokens), Equals, 3)
1397 c.Check(tokens[2], Equals, "ro")
1401 data, err := ioutil.ReadFile(dirMap["/tip"] + "/dir1/dir2/file with mode 0644")
1403 c.Check(string(data), Equals, "\000\001\002\003")
1404 _, err = ioutil.ReadFile(dirMap["/tip"] + "/file only on testbranch")
1405 c.Check(err, FitsTypeOf, &os.PathError{})
1406 c.Check(os.IsNotExist(err), Equals, true)
1408 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/dir1/dir2/file with mode 0644")
1410 c.Check(string(data), Equals, "\000\001\002\003")
1411 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/file only on testbranch")
1413 c.Check(string(data), Equals, "testfile\n")
1420 func (s *TestSuite) TestStdout(c *C) {
1422 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1423 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1425 "environment": {"FROBIZ": "bilbo"},
1426 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1427 "output_path": "/tmp",
1429 "runtime_constraints": {}
1432 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1433 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1437 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1438 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1439 c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1442 // Used by the TestStdoutWithWrongPath*()
1443 func (s *TestSuite) stdoutErrorRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, err error) {
1444 rec := arvados.Container{}
1445 err = json.Unmarshal([]byte(record), &rec)
1449 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
1451 api = &ArvTestClient{Container: rec}
1452 cr = NewContainerRunner(api, &KeepTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1453 am := &ArvMountCmdLine{}
1454 cr.RunArvMount = am.ArvMountTest
1455 cr.MkArvClient = func(token string) (IArvadosClient, error) {
1456 return &ArvTestClient{}, nil
1463 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1464 _, _, err := s.stdoutErrorRunHelper(c, `{
1465 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1466 "output_path": "/tmp"
1467 }`, func(t *TestDockerClient) {})
1469 c.Check(err, NotNil)
1470 c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
1473 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1474 _, _, err := s.stdoutErrorRunHelper(c, `{
1475 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1476 "output_path": "/tmp"
1477 }`, func(t *TestDockerClient) {})
1479 c.Check(err, NotNil)
1480 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'tmp' for stdout"), Equals, true)
1483 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1484 _, _, err := s.stdoutErrorRunHelper(c, `{
1485 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1486 "output_path": "/tmp"
1487 }`, func(t *TestDockerClient) {})
1489 c.Check(err, NotNil)
1490 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'collection' for stdout"), Equals, true)
1493 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1494 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1495 defer os.Unsetenv("ARVADOS_API_HOST")
1496 api, _, _ := s.fullRunHelper(c, `{
1497 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1498 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1501 "mounts": {"/tmp": {"kind": "tmp"} },
1502 "output_path": "/tmp",
1504 "runtime_constraints": {"API": true}
1505 }`, nil, 0, func(t *TestDockerClient) {
1506 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
1510 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1511 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1512 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "test.arvados.org\n"), Equals, true)
1513 c.Check(api.CalledWith("container.output", "d41d8cd98f00b204e9800998ecf8427e+0"), NotNil)
1516 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1517 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1518 defer os.Unsetenv("ARVADOS_API_HOST")
1519 api, _, _ := s.fullRunHelper(c, `{
1520 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1521 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1524 "mounts": {"/tmp": {"kind": "tmp"} },
1525 "output_path": "/tmp",
1527 "runtime_constraints": {"API": true}
1528 }`, nil, 0, func(t *TestDockerClient) {
1529 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
1533 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1534 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1535 c.Check(api.CalledWith("container.output", "d4ab34d3d4f8a72f5c4973051ae69fab+122"), NotNil)
1538 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1540 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1541 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1543 "environment": {"FROBIZ": "bilbo"},
1545 "/tmp": {"kind": "tmp"},
1546 "/tmp/foo": {"kind": "collection",
1547 "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1548 "exclude_from_output": true
1550 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1552 "output_path": "/tmp",
1554 "runtime_constraints": {}
1557 extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1559 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1560 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1564 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1565 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1566 c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1569 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1571 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1572 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1574 "environment": {"FROBIZ": "bilbo"},
1576 "/tmp": {"kind": "tmp"},
1577 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1578 "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1579 "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1580 "/tmp/foo/baz/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1581 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1583 "output_path": "/tmp",
1585 "runtime_constraints": {}
1588 extraMounts := []string{
1589 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1590 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1591 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1594 api, runner, realtemp := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1595 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1599 c.Check(runner.Binds, DeepEquals, []string{realtemp + "/tmp2:/tmp",
1600 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt:/tmp/foo/bar:ro",
1601 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt:/tmp/foo/baz/sub2file2:ro",
1602 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1:/tmp/foo/sub1:ro",
1603 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt:/tmp/foo/sub1file2:ro",
1606 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1607 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1608 for _, v := range api.Content {
1609 if v["collection"] != nil {
1610 c.Check(v["ensure_unique_name"], Equals, true)
1611 collection := v["collection"].(arvadosclient.Dict)
1612 if strings.Index(collection["name"].(string), "output") == 0 {
1613 manifest := collection["manifest_text"].(string)
1615 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1616 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 9:18:bar 9:18:sub1file2
1617 ./foo/baz 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2
1618 ./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1619 ./foo/sub1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1626 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
1628 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1629 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1631 "environment": {"FROBIZ": "bilbo"},
1633 "/tmp": {"kind": "tmp"},
1634 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt"},
1635 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1637 "output_path": "/tmp",
1639 "runtime_constraints": {}
1642 extraMounts := []string{
1643 "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1646 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1647 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1651 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1652 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1653 for _, v := range api.Content {
1654 if v["collection"] != nil {
1655 collection := v["collection"].(arvadosclient.Dict)
1656 if strings.Index(collection["name"].(string), "output") == 0 {
1657 manifest := collection["manifest_text"].(string)
1659 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1660 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 10:17:bar
1667 func (s *TestSuite) TestOutputSymlinkToInput(c *C) {
1669 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1670 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1672 "environment": {"FROBIZ": "bilbo"},
1674 "/tmp": {"kind": "tmp"},
1675 "/keep/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path": "/subdir1/file2_in_subdir1.txt"},
1676 "/keep/foo2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367"}
1678 "output_path": "/tmp",
1680 "runtime_constraints": {}
1683 extraMounts := []string{
1684 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1687 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1688 os.Symlink("/keep/foo/sub1file2", t.realTemp+"/tmp2/baz")
1689 os.Symlink("/keep/foo2/subdir1/file2_in_subdir1.txt", t.realTemp+"/tmp2/baz2")
1690 os.Symlink("/keep/foo2/subdir1", t.realTemp+"/tmp2/baz3")
1691 os.Mkdir(t.realTemp+"/tmp2/baz4", 0700)
1692 os.Symlink("/keep/foo2/subdir1/file2_in_subdir1.txt", t.realTemp+"/tmp2/baz4/baz5")
1696 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1697 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1698 for _, v := range api.Content {
1699 if v["collection"] != nil {
1700 collection := v["collection"].(arvadosclient.Dict)
1701 if strings.Index(collection["name"].(string), "output") == 0 {
1702 manifest := collection["manifest_text"].(string)
1703 c.Check(manifest, Equals, `. 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:baz 9:18:baz2
1704 ./baz3 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1705 ./baz3/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1706 ./baz4 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:baz5
1713 func (s *TestSuite) TestOutputError(c *C) {
1715 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1716 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1718 "environment": {"FROBIZ": "bilbo"},
1720 "/tmp": {"kind": "tmp"}
1722 "output_path": "/tmp",
1724 "runtime_constraints": {}
1727 extraMounts := []string{}
1729 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1730 os.Symlink("/etc/hosts", t.realTemp+"/tmp2/baz")
1734 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1737 func (s *TestSuite) TestOutputSymlinkToOutput(c *C) {
1739 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1740 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1742 "environment": {"FROBIZ": "bilbo"},
1744 "/tmp": {"kind": "tmp"}
1746 "output_path": "/tmp",
1748 "runtime_constraints": {}
1751 extraMounts := []string{}
1753 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1754 rf, _ := os.Create(t.realTemp + "/tmp2/realfile")
1755 rf.Write([]byte("foo"))
1758 os.Mkdir(t.realTemp+"/tmp2/realdir", 0700)
1759 rf, _ = os.Create(t.realTemp + "/tmp2/realdir/subfile")
1760 rf.Write([]byte("bar"))
1763 os.Symlink("/tmp/realfile", t.realTemp+"/tmp2/file1")
1764 os.Symlink("realfile", t.realTemp+"/tmp2/file2")
1765 os.Symlink("/tmp/file1", t.realTemp+"/tmp2/file3")
1766 os.Symlink("file2", t.realTemp+"/tmp2/file4")
1767 os.Symlink("realdir", t.realTemp+"/tmp2/dir1")
1768 os.Symlink("/tmp/realdir", t.realTemp+"/tmp2/dir2")
1772 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1773 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1774 for _, v := range api.Content {
1775 if v["collection"] != nil {
1776 collection := v["collection"].(arvadosclient.Dict)
1777 if strings.Index(collection["name"].(string), "output") == 0 {
1778 manifest := collection["manifest_text"].(string)
1779 c.Check(manifest, Equals,
1780 `. 7a2c86e102dcc231bd232aad99686dfa+15 0:3:file1 3:3:file2 6:3:file3 9:3:file4 12:3:realfile
1781 ./dir1 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1782 ./dir2 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1783 ./realdir 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1790 func (s *TestSuite) TestStdinCollectionMountPoint(c *C) {
1792 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1793 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1795 "environment": {"FROBIZ": "bilbo"},
1797 "/tmp": {"kind": "tmp"},
1798 "stdin": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/file1_in_main.txt"},
1799 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1801 "output_path": "/tmp",
1803 "runtime_constraints": {}
1806 extraMounts := []string{
1807 "b0def87f80dd594d4675809e83bd4f15+367/file1_in_main.txt",
1810 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1811 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1815 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1816 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1817 for _, v := range api.Content {
1818 if v["collection"] != nil {
1819 collection := v["collection"].(arvadosclient.Dict)
1820 if strings.Index(collection["name"].(string), "output") == 0 {
1821 manifest := collection["manifest_text"].(string)
1822 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1829 func (s *TestSuite) TestStdinJsonMountPoint(c *C) {
1831 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1832 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1834 "environment": {"FROBIZ": "bilbo"},
1836 "/tmp": {"kind": "tmp"},
1837 "stdin": {"kind": "json", "content": "foo"},
1838 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1840 "output_path": "/tmp",
1842 "runtime_constraints": {}
1845 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1846 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1850 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1851 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1852 for _, v := range api.Content {
1853 if v["collection"] != nil {
1854 collection := v["collection"].(arvadosclient.Dict)
1855 if strings.Index(collection["name"].(string), "output") == 0 {
1856 manifest := collection["manifest_text"].(string)
1857 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1864 func (s *TestSuite) TestStderrMount(c *C) {
1865 api, _, _ := s.fullRunHelper(c, `{
1866 "command": ["/bin/sh", "-c", "echo hello;exit 1"],
1867 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1870 "mounts": {"/tmp": {"kind": "tmp"},
1871 "stdout": {"kind": "file", "path": "/tmp/a/out.txt"},
1872 "stderr": {"kind": "file", "path": "/tmp/b/err.txt"}},
1873 "output_path": "/tmp",
1875 "runtime_constraints": {}
1876 }`, nil, 1, func(t *TestDockerClient) {
1877 t.logWriter.Write(dockerLog(1, "hello\n"))
1878 t.logWriter.Write(dockerLog(2, "oops\n"))
1882 final := api.CalledWith("container.state", "Complete")
1883 c.Assert(final, NotNil)
1884 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1885 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1887 c.Check(api.CalledWith("collection.manifest_text", "./a b1946ac92492d2347c6235b4d2611184+6 0:6:out.txt\n./b 38af5c54926b620264ab1501150cf189+5 0:5:err.txt\n"), NotNil)
1890 func (s *TestSuite) TestNumberRoundTrip(c *C) {
1891 cr := NewContainerRunner(&ArvTestClient{callraw: true}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1892 cr.fetchContainerRecord()
1894 jsondata, err := json.Marshal(cr.Container.Mounts["/json"].Content)
1897 c.Check(string(jsondata), Equals, `{"number":123456789123456789}`)
1900 func (s *TestSuite) TestEvalSymlinks(c *C) {
1901 cr := NewContainerRunner(&ArvTestClient{callraw: true}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1903 realTemp, err := ioutil.TempDir("", "crunchrun_test-")
1904 c.Assert(err, IsNil)
1905 defer os.RemoveAll(realTemp)
1907 cr.HostOutputDir = realTemp
1909 // Absolute path outside output dir
1910 os.Symlink("/etc/passwd", realTemp+"/p1")
1912 // Relative outside output dir
1913 os.Symlink("../zip", realTemp+"/p2")
1915 // Circular references
1916 os.Symlink("p4", realTemp+"/p3")
1917 os.Symlink("p5", realTemp+"/p4")
1918 os.Symlink("p3", realTemp+"/p5")
1920 // Target doesn't exist
1921 os.Symlink("p99", realTemp+"/p6")
1923 for _, v := range []string{"p1", "p2", "p3", "p4", "p5"} {
1924 info, err := os.Lstat(realTemp + "/" + v)
1925 _, _, _, err = cr.derefOutputSymlink(realTemp+"/"+v, info)
1926 c.Assert(err, NotNil)
1930 func (s *TestSuite) TestEvalSymlinkDir(c *C) {
1931 cr := NewContainerRunner(&ArvTestClient{callraw: true}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1933 realTemp, err := ioutil.TempDir("", "crunchrun_test-")
1934 c.Assert(err, IsNil)
1935 defer os.RemoveAll(realTemp)
1937 cr.HostOutputDir = realTemp
1939 // Absolute path outside output dir
1940 os.Symlink(".", realTemp+"/loop")
1943 info, err := os.Lstat(realTemp + "/" + v)
1944 _, err = cr.UploadOutputFile(realTemp+"/"+v, info, err, []string{}, nil, "", "", 0)
1945 c.Assert(err, NotNil)
1948 func (s *TestSuite) TestFullBrokenDocker1(c *C) {
1949 tf, err := ioutil.TempFile("", "brokenNodeHook-")
1950 c.Assert(err, IsNil)
1951 defer os.Remove(tf.Name())
1953 tf.Write([]byte(`#!/bin/sh
1957 os.Chmod(tf.Name(), 0700)
1960 brokenNodeHook = &ech
1962 api, _, _ := s.fullRunHelper(c, `{
1963 "command": ["echo", "hello world"],
1964 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1967 "mounts": {"/tmp": {"kind": "tmp"} },
1968 "output_path": "/tmp",
1970 "runtime_constraints": {}
1971 }`, nil, 2, func(t *TestDockerClient) {
1972 t.logWriter.Write(dockerLog(1, "hello world\n"))
1976 c.Check(api.CalledWith("container.state", "Queued"), NotNil)
1977 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1978 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Running broken node hook.*")
1979 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*killme.*")
1983 func (s *TestSuite) TestFullBrokenDocker2(c *C) {
1985 brokenNodeHook = &ech
1987 api, _, _ := s.fullRunHelper(c, `{
1988 "command": ["echo", "hello world"],
1989 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1992 "mounts": {"/tmp": {"kind": "tmp"} },
1993 "output_path": "/tmp",
1995 "runtime_constraints": {}
1996 }`, nil, 2, func(t *TestDockerClient) {
1997 t.logWriter.Write(dockerLog(1, "hello world\n"))
2001 c.Check(api.CalledWith("container.state", "Queued"), NotNil)
2002 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
2003 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*No broken node hook.*")
2006 func (s *TestSuite) TestFullBrokenDocker3(c *C) {
2008 brokenNodeHook = &ech
2010 api, _, _ := s.fullRunHelper(c, `{
2011 "command": ["echo", "hello world"],
2012 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2015 "mounts": {"/tmp": {"kind": "tmp"} },
2016 "output_path": "/tmp",
2018 "runtime_constraints": {}
2019 }`, nil, 3, func(t *TestDockerClient) {
2020 t.logWriter.Write(dockerLog(1, "hello world\n"))
2024 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2025 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
2028 func (s *TestSuite) TestBadCommand1(c *C) {
2030 brokenNodeHook = &ech
2032 api, _, _ := s.fullRunHelper(c, `{
2033 "command": ["echo", "hello world"],
2034 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2037 "mounts": {"/tmp": {"kind": "tmp"} },
2038 "output_path": "/tmp",
2040 "runtime_constraints": {}
2041 }`, nil, 4, func(t *TestDockerClient) {
2042 t.logWriter.Write(dockerLog(1, "hello world\n"))
2046 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2047 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2050 func (s *TestSuite) TestBadCommand2(c *C) {
2052 brokenNodeHook = &ech
2054 api, _, _ := s.fullRunHelper(c, `{
2055 "command": ["echo", "hello world"],
2056 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2059 "mounts": {"/tmp": {"kind": "tmp"} },
2060 "output_path": "/tmp",
2062 "runtime_constraints": {}
2063 }`, nil, 5, func(t *TestDockerClient) {
2064 t.logWriter.Write(dockerLog(1, "hello world\n"))
2068 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2069 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2072 func (s *TestSuite) TestBadCommand3(c *C) {
2074 brokenNodeHook = &ech
2076 api, _, _ := s.fullRunHelper(c, `{
2077 "command": ["echo", "hello world"],
2078 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2081 "mounts": {"/tmp": {"kind": "tmp"} },
2082 "output_path": "/tmp",
2084 "runtime_constraints": {}
2085 }`, nil, 6, func(t *TestDockerClient) {
2086 t.logWriter.Write(dockerLog(1, "hello world\n"))
2090 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2091 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2094 func (s *TestSuite) TestSecretTextMountPoint(c *C) {
2095 // under normal mounts, gets captured in output, oops
2097 "command": ["true"],
2098 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2101 "/tmp": {"kind": "tmp"},
2102 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2106 "output_path": "/tmp",
2108 "runtime_constraints": {}
2111 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2112 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2114 c.Check(content, DeepEquals, []byte("mypassword"))
2118 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2119 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2120 c.Check(api.CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), NotNil)
2121 c.Check(api.CalledWith("collection.manifest_text", ""), IsNil)
2123 // under secret mounts, not captured in output
2125 "command": ["true"],
2126 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2129 "/tmp": {"kind": "tmp"}
2132 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2134 "output_path": "/tmp",
2136 "runtime_constraints": {}
2139 api, _, _ = s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2140 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2142 c.Check(content, DeepEquals, []byte("mypassword"))
2146 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2147 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2148 c.Check(api.CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), IsNil)
2149 c.Check(api.CalledWith("collection.manifest_text", ""), NotNil)