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 client *arvados.Client
49 docker *TestDockerClient
50 runner *ContainerRunner
53 func (s *TestSuite) SetUpTest(c *C) {
54 s.client = arvados.NewClientFromEnv()
55 s.docker = NewTestDockerClient()
58 type ArvTestClient struct {
61 Content []arvadosclient.Dict
64 Logs map[string]*bytes.Buffer
70 type KeepTestClient struct {
75 var hwManifest = ". 82ab40c24fc8df01798e57ba66795bb1+841216+Aa124ac75e5168396c73c0a18eda641a4f41791c0@569fa8c3 0:841216:9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7.tar\n"
76 var hwPDH = "a45557269dcb65a6b78f9ac061c0850b+120"
77 var hwImageId = "9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7"
79 var otherManifest = ". 68a84f561b1d1708c6baff5e019a9ab3+46+Ae5d0af96944a3690becb1decdf60cc1c937f556d@5693216f 0:46:md5sum.txt\n"
80 var otherPDH = "a3e8f74c6f101eae01fa08bfb4e49b3a+54"
82 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
83 ./subdir1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
84 ./subdir1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
87 var normalizedWithSubdirsPDH = "a0def87f80dd594d4675809e83bd4f15+367"
89 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"
90 var denormalizedWithSubdirsPDH = "b0def87f80dd594d4675809e83bd4f15+367"
92 var fakeAuthUUID = "zzzzz-gj3su-55pqoyepgi2glem"
93 var fakeAuthToken = "a3ltuwzqcu2u4sc0q7yhpc2w7s00fdcqecg5d6e0u3pfohmbjt"
95 type TestDockerClient struct {
97 logReader io.ReadCloser
98 logWriter io.WriteCloser
99 fn func(t *TestDockerClient)
110 func NewTestDockerClient() *TestDockerClient {
111 t := &TestDockerClient{}
112 t.logReader, t.logWriter = io.Pipe()
113 t.stop = make(chan bool, 1)
118 type MockConn struct {
122 func (m *MockConn) Write(b []byte) (int, error) {
126 func NewMockConn() *MockConn {
131 func (t *TestDockerClient) ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error) {
132 return dockertypes.HijackedResponse{Conn: NewMockConn(), Reader: bufio.NewReader(t.logReader)}, nil
135 func (t *TestDockerClient) ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig, networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error) {
136 if config.WorkingDir != "" {
137 t.cwd = config.WorkingDir
140 return dockercontainer.ContainerCreateCreatedBody{ID: "abcde"}, nil
143 func (t *TestDockerClient) ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error {
145 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\\\"\""`)
148 return errors.New(`panic: standard_init_linux.go:175: exec user process caused "no such file or directory"`)
151 return errors.New(`Error response from daemon: Cannot start container 41f26cbc43bcc1280f4323efb1830a394ba8660c9d1c2b564ba42bf7f7694845: [8] System error: no such file or directory`)
154 return errors.New(`Error response from daemon: Cannot start container 58099cd76c834f3dc2a4fb76c8028f049ae6d4fdf0ec373e1f2cfea030670c2d: [8] System error: exec: "foobar": executable file not found in $PATH`)
157 if container == "abcde" {
158 // t.fn gets executed in ContainerWait
161 return errors.New("Invalid container id")
165 func (t *TestDockerClient) ContainerRemove(ctx context.Context, container string, options dockertypes.ContainerRemoveOptions) error {
170 func (t *TestDockerClient) ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error) {
172 body := make(chan dockercontainer.ContainerWaitOKBody, 1)
173 err := make(chan error)
176 body <- dockercontainer.ContainerWaitOKBody{StatusCode: int64(t.exitCode)}
181 func (t *TestDockerClient) ContainerInspect(ctx context.Context, id string) (c dockertypes.ContainerJSON, err error) {
182 c.ContainerJSONBase = &dockertypes.ContainerJSONBase{}
185 c.State = &dockertypes.ContainerState{Status: "exited", Dead: true}
187 c.State = &dockertypes.ContainerState{Status: "running", Pid: 1234, Running: true}
192 func (t *TestDockerClient) ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error) {
194 return dockertypes.ImageInspect{}, nil, fmt.Errorf("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?")
197 if t.imageLoaded == image {
198 return dockertypes.ImageInspect{}, nil, nil
200 return dockertypes.ImageInspect{}, nil, errors.New("")
204 func (t *TestDockerClient) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error) {
206 return dockertypes.ImageLoadResponse{}, fmt.Errorf("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?")
208 _, err := io.Copy(ioutil.Discard, input)
210 return dockertypes.ImageLoadResponse{}, err
212 t.imageLoaded = hwImageId
213 return dockertypes.ImageLoadResponse{Body: ioutil.NopCloser(input)}, nil
217 func (*TestDockerClient) ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {
221 func (client *ArvTestClient) Create(resourceType string,
222 parameters arvadosclient.Dict,
223 output interface{}) error {
226 defer client.Mutex.Unlock()
229 client.Content = append(client.Content, parameters)
231 if resourceType == "logs" {
232 et := parameters["log"].(arvadosclient.Dict)["event_type"].(string)
233 if client.Logs == nil {
234 client.Logs = make(map[string]*bytes.Buffer)
236 if client.Logs[et] == nil {
237 client.Logs[et] = &bytes.Buffer{}
239 client.Logs[et].Write([]byte(parameters["log"].(arvadosclient.Dict)["properties"].(map[string]string)["text"]))
242 if resourceType == "collections" && output != nil {
243 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
244 outmap := output.(*arvados.Collection)
245 outmap.PortableDataHash = fmt.Sprintf("%x+%d", md5.Sum([]byte(mt)), len(mt))
246 outmap.UUID = fmt.Sprintf("zzzzz-4zz18-%15.15x", md5.Sum([]byte(mt)))
252 func (client *ArvTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
254 case method == "GET" && resourceType == "containers" && action == "auth":
255 return json.Unmarshal([]byte(`{
256 "kind": "arvados#api_client_authorization",
257 "uuid": "`+fakeAuthUUID+`",
258 "api_token": "`+fakeAuthToken+`"
260 case method == "GET" && resourceType == "containers" && action == "secret_mounts":
261 if client.secretMounts != nil {
262 return json.Unmarshal(client.secretMounts, output)
264 return json.Unmarshal([]byte(`{"secret_mounts":{}}`), output)
267 return fmt.Errorf("Not found")
271 func (client *ArvTestClient) CallRaw(method, resourceType, uuid, action string,
272 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
274 if method == "GET" && resourceType == "nodes" && uuid == "" && action == "" {
276 "kind": "arvados#nodeList",
278 "uuid": "zzzzz-7ekkf-2z3mc76g2q73aio",
279 "hostname": "compute2",
280 "properties": {"total_cpu_cores": 16}
282 } else if method == "GET" && resourceType == "containers" && action == "" && !client.callraw {
284 j, err = json.Marshal(map[string]interface{}{
285 "items": []interface{}{client.Container},
286 "kind": "arvados#nodeList",
289 j, err = json.Marshal(client.Container)
293 "command": ["sleep", "1"],
294 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
297 "mounts": {"/tmp": {"kind": "tmp"}, "/json": {"kind": "json", "content": {"number": 123456789123456789}}},
298 "output_path": "/tmp",
300 "runtime_constraints": {}
303 return ioutil.NopCloser(bytes.NewReader(j)), err
306 func (client *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
307 if resourceType == "collections" {
309 output.(*arvados.Collection).ManifestText = hwManifest
310 } else if uuid == otherPDH {
311 output.(*arvados.Collection).ManifestText = otherManifest
312 } else if uuid == normalizedWithSubdirsPDH {
313 output.(*arvados.Collection).ManifestText = normalizedManifestWithSubdirs
314 } else if uuid == denormalizedWithSubdirsPDH {
315 output.(*arvados.Collection).ManifestText = denormalizedManifestWithSubdirs
318 if resourceType == "containers" {
319 (*output.(*arvados.Container)) = client.Container
324 func (client *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
326 defer client.Mutex.Unlock()
328 client.Content = append(client.Content, parameters)
329 if resourceType == "containers" {
330 if parameters["container"].(arvadosclient.Dict)["state"] == "Running" {
331 client.WasSetRunning = true
333 } else if resourceType == "collections" {
334 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
335 output.(*arvados.Collection).UUID = uuid
336 output.(*arvados.Collection).PortableDataHash = fmt.Sprintf("%x", md5.Sum([]byte(mt)))
341 var discoveryMap = map[string]interface{}{
342 "defaultTrashLifetime": float64(1209600),
343 "crunchLimitLogBytesPerJob": float64(67108864),
344 "crunchLogThrottleBytes": float64(65536),
345 "crunchLogThrottlePeriod": float64(60),
346 "crunchLogThrottleLines": float64(1024),
347 "crunchLogPartialLineThrottlePeriod": float64(5),
348 "crunchLogBytesPerEvent": float64(4096),
349 "crunchLogSecondsBetweenEvents": float64(1),
352 func (client *ArvTestClient) Discovery(key string) (interface{}, error) {
353 return discoveryMap[key], nil
356 // CalledWith returns the parameters from the first API call whose
357 // parameters match jpath/string. E.g., CalledWith(c, "foo.bar",
358 // "baz") returns parameters with parameters["foo"]["bar"]=="baz". If
359 // no call matches, it returns nil.
360 func (client *ArvTestClient) CalledWith(jpath string, expect interface{}) arvadosclient.Dict {
362 for _, content := range client.Content {
363 var v interface{} = content
364 for _, k := range strings.Split(jpath, ".") {
365 if dict, ok := v.(arvadosclient.Dict); !ok {
378 func (client *KeepTestClient) LocalLocator(locator string) (string, error) {
382 func (client *KeepTestClient) PutB(buf []byte) (string, int, error) {
384 return fmt.Sprintf("%x+%d", md5.Sum(buf), len(buf)), len(buf), nil
387 func (client *KeepTestClient) ReadAt(string, []byte, int) (int, error) {
388 return 0, errors.New("not implemented")
391 func (client *KeepTestClient) ClearBlockCache() {
394 func (client *KeepTestClient) Close() {
398 type FileWrapper struct {
403 func (fw FileWrapper) Readdir(n int) ([]os.FileInfo, error) {
404 return nil, errors.New("not implemented")
407 func (fw FileWrapper) Seek(int64, int) (int64, error) {
408 return 0, errors.New("not implemented")
411 func (fw FileWrapper) Size() int64 {
415 func (fw FileWrapper) Stat() (os.FileInfo, error) {
416 return nil, errors.New("not implemented")
419 func (fw FileWrapper) Truncate(int64) error {
420 return errors.New("not implemented")
423 func (fw FileWrapper) Write([]byte) (int, error) {
424 return 0, errors.New("not implemented")
427 func (fw FileWrapper) Sync() error {
428 return errors.New("not implemented")
431 func (client *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
432 if filename == hwImageId+".tar" {
433 rdr := ioutil.NopCloser(&bytes.Buffer{})
435 return FileWrapper{rdr, 1321984}, nil
436 } else if filename == "/file1_in_main.txt" {
437 rdr := ioutil.NopCloser(strings.NewReader("foo"))
439 return FileWrapper{rdr, 3}, nil
444 func (s *TestSuite) TestLoadImage(c *C) {
445 cr, err := NewContainerRunner(s.client, &ArvTestClient{},
446 &KeepTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
449 kc := &KeepTestClient{}
451 cr.ContainerArvClient = &ArvTestClient{}
452 cr.ContainerKeepClient = kc
454 _, err = cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
457 _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
460 cr.Container.ContainerImage = hwPDH
462 // (1) Test loading image from keep
463 c.Check(kc.Called, Equals, false)
464 c.Check(cr.ContainerConfig.Image, Equals, "")
470 cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
473 c.Check(kc.Called, Equals, true)
474 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
476 _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
479 // (2) Test using image that's already loaded
481 cr.ContainerConfig.Image = ""
485 c.Check(kc.Called, Equals, false)
486 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
490 type ArvErrorTestClient struct{}
492 func (ArvErrorTestClient) Create(resourceType string,
493 parameters arvadosclient.Dict,
494 output interface{}) error {
498 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
499 if method == "GET" && resourceType == "containers" && action == "auth" {
502 return errors.New("ArvError")
505 func (ArvErrorTestClient) CallRaw(method, resourceType, uuid, action string,
506 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
507 return nil, errors.New("ArvError")
510 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
511 return errors.New("ArvError")
514 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
518 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
519 return discoveryMap[key], nil
522 type KeepErrorTestClient struct {
526 func (*KeepErrorTestClient) ManifestFileReader(manifest.Manifest, string) (arvados.File, error) {
527 return nil, errors.New("KeepError")
530 func (*KeepErrorTestClient) PutB(buf []byte) (string, int, error) {
531 return "", 0, errors.New("KeepError")
534 func (*KeepErrorTestClient) LocalLocator(string) (string, error) {
535 return "", errors.New("KeepError")
538 type KeepReadErrorTestClient struct {
542 func (*KeepReadErrorTestClient) ReadAt(string, []byte, int) (int, error) {
543 return 0, errors.New("KeepError")
546 type ErrorReader struct {
550 func (ErrorReader) Read(p []byte) (n int, err error) {
551 return 0, errors.New("ErrorReader")
554 func (ErrorReader) Seek(int64, int) (int64, error) {
555 return 0, errors.New("ErrorReader")
558 func (KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
559 return ErrorReader{}, nil
562 func (s *TestSuite) TestLoadImageArvError(c *C) {
564 kc := &KeepTestClient{}
566 cr, err := NewContainerRunner(s.client, &ArvErrorTestClient{}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
569 cr.ContainerArvClient = &ArvErrorTestClient{}
570 cr.ContainerKeepClient = &KeepTestClient{}
572 cr.Container.ContainerImage = hwPDH
575 c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
578 func (s *TestSuite) TestLoadImageKeepError(c *C) {
580 kc := &KeepErrorTestClient{}
581 cr, err := NewContainerRunner(s.client, &ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
584 cr.ContainerArvClient = &ArvTestClient{}
585 cr.ContainerKeepClient = &KeepErrorTestClient{}
587 cr.Container.ContainerImage = hwPDH
590 c.Assert(err, NotNil)
591 c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
594 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
595 // (3) Collection doesn't contain image
596 kc := &KeepReadErrorTestClient{}
597 cr, err := NewContainerRunner(s.client, &ArvTestClient{}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
599 cr.Container.ContainerImage = otherPDH
601 cr.ContainerArvClient = &ArvTestClient{}
602 cr.ContainerKeepClient = &KeepReadErrorTestClient{}
605 c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
608 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
609 // (4) Collection doesn't contain image
610 kc := &KeepReadErrorTestClient{}
611 cr, err := NewContainerRunner(s.client, &ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
613 cr.Container.ContainerImage = hwPDH
614 cr.ContainerArvClient = &ArvTestClient{}
615 cr.ContainerKeepClient = &KeepReadErrorTestClient{}
621 type ClosableBuffer struct {
625 func (*ClosableBuffer) Close() error {
629 type TestLogs struct {
630 Stdout ClosableBuffer
631 Stderr ClosableBuffer
634 func (tl *TestLogs) NewTestLoggingWriter(logstr string) (io.WriteCloser, error) {
635 if logstr == "stdout" {
636 return &tl.Stdout, nil
638 if logstr == "stderr" {
639 return &tl.Stderr, nil
641 return nil, errors.New("???")
644 func dockerLog(fd byte, msg string) []byte {
646 header := make([]byte, 8+len(by))
648 header[7] = byte(len(by))
653 func (s *TestSuite) TestRunContainer(c *C) {
654 s.docker.fn = func(t *TestDockerClient) {
655 t.logWriter.Write(dockerLog(1, "Hello world\n"))
658 kc := &KeepTestClient{}
660 cr, err := NewContainerRunner(s.client, &ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
663 cr.ContainerArvClient = &ArvTestClient{}
664 cr.ContainerKeepClient = &KeepTestClient{}
667 cr.NewLogWriter = logs.NewTestLoggingWriter
668 cr.Container.ContainerImage = hwPDH
669 cr.Container.Command = []string{"./hw"}
673 err = cr.CreateContainer()
676 err = cr.StartContainer()
679 err = cr.WaitFinish()
682 c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
683 c.Check(logs.Stderr.String(), Equals, "")
686 func (s *TestSuite) TestCommitLogs(c *C) {
687 api := &ArvTestClient{}
688 kc := &KeepTestClient{}
690 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
692 cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
694 cr.CrunchLog.Print("Hello world!")
695 cr.CrunchLog.Print("Goodbye")
696 cr.finalState = "Complete"
698 err = cr.CommitLogs()
701 c.Check(api.Calls, Equals, 2)
702 c.Check(api.Content[1]["ensure_unique_name"], Equals, true)
703 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
704 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
705 c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
708 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
709 api := &ArvTestClient{}
710 kc := &KeepTestClient{}
712 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
715 err = cr.UpdateContainerRunning()
718 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
721 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
722 api := &ArvTestClient{}
723 kc := &KeepTestClient{}
725 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
728 cr.LogsPDH = new(string)
729 *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
731 cr.ExitCode = new(int)
733 cr.finalState = "Complete"
735 err = cr.UpdateContainerFinal()
738 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
739 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
740 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
743 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
744 api := &ArvTestClient{}
745 kc := &KeepTestClient{}
747 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
750 cr.finalState = "Cancelled"
752 err = cr.UpdateContainerFinal()
755 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
756 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
757 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
760 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
761 // dress rehearsal of the Run() function, starting from a JSON container record.
762 func (s *TestSuite) fullRunHelper(c *C, record string, extraMounts []string, exitCode int, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, realTemp string) {
763 rec := arvados.Container{}
764 err := json.Unmarshal([]byte(record), &rec)
768 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
770 err = json.Unmarshal([]byte(record), &sm)
772 secretMounts, err := json.Marshal(sm)
773 c.Logf("%s %q", sm, secretMounts)
776 s.docker.exitCode = exitCode
778 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
780 api = &ArvTestClient{Container: rec}
782 kc := &KeepTestClient{}
784 cr, err = NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
787 cr.statInterval = 100 * time.Millisecond
788 cr.containerWatchdogInterval = time.Second
789 am := &ArvMountCmdLine{}
790 cr.RunArvMount = am.ArvMountTest
792 realTemp, err = ioutil.TempDir("", "crunchrun_test1-")
794 defer os.RemoveAll(realTemp)
796 s.docker.realTemp = realTemp
799 cr.MkTempDir = func(_ string, prefix string) (string, error) {
801 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, tempcount)
802 err := os.Mkdir(d, os.ModePerm)
803 if err != nil && strings.Contains(err.Error(), ": file exists") {
804 // Test case must have pre-populated the tempdir
809 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
810 return &ArvTestClient{secretMounts: secretMounts}, &KeepTestClient{}, nil, nil
813 if extraMounts != nil && len(extraMounts) > 0 {
814 err := cr.SetupArvMountPoint("keep")
817 for _, m := range extraMounts {
818 os.MkdirAll(cr.ArvMountPoint+"/by_id/"+m, os.ModePerm)
823 if api.CalledWith("container.state", "Complete") != nil {
827 c.Check(api.WasSetRunning, Equals, true)
828 var lastupdate arvadosclient.Dict
829 for _, content := range api.Content {
830 if content["container"] != nil {
831 lastupdate = content["container"].(arvadosclient.Dict)
834 if lastupdate["log"] == nil {
835 c.Errorf("no container update with non-nil log -- updates were: %v", api.Content)
840 for k, v := range api.Logs {
849 func (s *TestSuite) TestFullRunHello(c *C) {
850 api, _, _ := s.fullRunHelper(c, `{
851 "command": ["echo", "hello world"],
852 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
855 "mounts": {"/tmp": {"kind": "tmp"} },
856 "output_path": "/tmp",
858 "runtime_constraints": {}
859 }`, nil, 0, func(t *TestDockerClient) {
860 t.logWriter.Write(dockerLog(1, "hello world\n"))
864 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
865 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
866 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
870 func (s *TestSuite) TestRunTimeExceeded(c *C) {
871 api, _, _ := s.fullRunHelper(c, `{
872 "command": ["sleep", "3"],
873 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
876 "mounts": {"/tmp": {"kind": "tmp"} },
877 "output_path": "/tmp",
879 "runtime_constraints": {},
880 "scheduling_parameters":{"max_run_time": 1}
881 }`, nil, 0, func(t *TestDockerClient) {
882 time.Sleep(3 * time.Second)
886 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
887 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*maximum run time exceeded.*")
890 func (s *TestSuite) TestContainerWaitFails(c *C) {
891 api, _, _ := s.fullRunHelper(c, `{
892 "command": ["sleep", "3"],
893 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
895 "mounts": {"/tmp": {"kind": "tmp"} },
896 "output_path": "/tmp",
898 }`, nil, 0, func(t *TestDockerClient) {
900 time.Sleep(10 * time.Second)
904 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
905 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Container is not running.*")
908 func (s *TestSuite) TestCrunchstat(c *C) {
909 api, _, _ := s.fullRunHelper(c, `{
910 "command": ["sleep", "1"],
911 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
914 "mounts": {"/tmp": {"kind": "tmp"} },
915 "output_path": "/tmp",
917 "runtime_constraints": {}
918 }`, nil, 0, func(t *TestDockerClient) {
919 time.Sleep(time.Second)
923 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
924 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
926 // We didn't actually start a container, so crunchstat didn't
927 // find accounting files and therefore didn't log any stats.
928 // It should have logged a "can't find accounting files"
929 // message after one poll interval, though, so we can confirm
931 c.Assert(api.Logs["crunchstat"], NotNil)
932 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
934 // The "files never appeared" log assures us that we called
935 // (*crunchstat.Reporter)Stop(), and that we set it up with
936 // the correct container ID "abcde":
937 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files never appeared for abcde\n`)
940 func (s *TestSuite) TestNodeInfoLog(c *C) {
941 os.Setenv("SLURMD_NODENAME", "compute2")
942 api, _, _ := s.fullRunHelper(c, `{
943 "command": ["sleep", "1"],
944 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
947 "mounts": {"/tmp": {"kind": "tmp"} },
948 "output_path": "/tmp",
950 "runtime_constraints": {}
952 func(t *TestDockerClient) {
953 time.Sleep(time.Second)
957 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
958 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
960 c.Assert(api.Logs["node"], NotNil)
961 json := api.Logs["node"].String()
962 c.Check(json, Matches, `(?ms).*"uuid": *"zzzzz-7ekkf-2z3mc76g2q73aio".*`)
963 c.Check(json, Matches, `(?ms).*"total_cpu_cores": *16.*`)
964 c.Check(json, Not(Matches), `(?ms).*"info":.*`)
966 c.Assert(api.Logs["node-info"], NotNil)
967 json = api.Logs["node-info"].String()
968 c.Check(json, Matches, `(?ms).*Host Information.*`)
969 c.Check(json, Matches, `(?ms).*CPU Information.*`)
970 c.Check(json, Matches, `(?ms).*Memory Information.*`)
971 c.Check(json, Matches, `(?ms).*Disk Space.*`)
972 c.Check(json, Matches, `(?ms).*Disk INodes.*`)
975 func (s *TestSuite) TestContainerRecordLog(c *C) {
976 api, _, _ := s.fullRunHelper(c, `{
977 "command": ["sleep", "1"],
978 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
981 "mounts": {"/tmp": {"kind": "tmp"} },
982 "output_path": "/tmp",
984 "runtime_constraints": {}
986 func(t *TestDockerClient) {
987 time.Sleep(time.Second)
991 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
992 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
994 c.Assert(api.Logs["container"], NotNil)
995 c.Check(api.Logs["container"].String(), Matches, `(?ms).*container_image.*`)
998 func (s *TestSuite) TestFullRunStderr(c *C) {
999 api, _, _ := s.fullRunHelper(c, `{
1000 "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
1001 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1004 "mounts": {"/tmp": {"kind": "tmp"} },
1005 "output_path": "/tmp",
1007 "runtime_constraints": {}
1008 }`, nil, 1, func(t *TestDockerClient) {
1009 t.logWriter.Write(dockerLog(1, "hello\n"))
1010 t.logWriter.Write(dockerLog(2, "world\n"))
1014 final := api.CalledWith("container.state", "Complete")
1015 c.Assert(final, NotNil)
1016 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1017 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1019 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
1020 c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
1023 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
1024 api, _, _ := s.fullRunHelper(c, `{
1026 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1029 "mounts": {"/tmp": {"kind": "tmp"} },
1030 "output_path": "/tmp",
1032 "runtime_constraints": {}
1033 }`, nil, 0, func(t *TestDockerClient) {
1034 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
1038 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1039 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1040 c.Log(api.Logs["stdout"])
1041 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
1044 func (s *TestSuite) TestFullRunSetCwd(c *C) {
1045 api, _, _ := s.fullRunHelper(c, `{
1047 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1050 "mounts": {"/tmp": {"kind": "tmp"} },
1051 "output_path": "/tmp",
1053 "runtime_constraints": {}
1054 }`, nil, 0, func(t *TestDockerClient) {
1055 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
1059 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1060 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1061 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
1064 func (s *TestSuite) TestStopOnSignal(c *C) {
1065 s.testStopContainer(c, func(cr *ContainerRunner) {
1067 for !s.docker.calledWait {
1068 time.Sleep(time.Millisecond)
1070 cr.SigChan <- syscall.SIGINT
1075 func (s *TestSuite) TestStopOnArvMountDeath(c *C) {
1076 s.testStopContainer(c, func(cr *ContainerRunner) {
1077 cr.ArvMountExit = make(chan error)
1079 cr.ArvMountExit <- exec.Command("true").Run()
1080 close(cr.ArvMountExit)
1085 func (s *TestSuite) testStopContainer(c *C, setup func(cr *ContainerRunner)) {
1087 "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
1088 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1091 "mounts": {"/tmp": {"kind": "tmp"} },
1092 "output_path": "/tmp",
1094 "runtime_constraints": {}
1097 rec := arvados.Container{}
1098 err := json.Unmarshal([]byte(record), &rec)
1101 s.docker.fn = func(t *TestDockerClient) {
1103 t.logWriter.Write(dockerLog(1, "foo\n"))
1106 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
1108 api := &ArvTestClient{Container: rec}
1109 kc := &KeepTestClient{}
1111 cr, err := NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1112 c.Assert(err, IsNil)
1113 cr.RunArvMount = func([]string, string) (*exec.Cmd, error) { return nil, nil }
1114 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1115 return &ArvTestClient{}, &KeepTestClient{}, nil, nil
1119 done := make(chan error)
1124 case <-time.After(20 * time.Second):
1125 pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
1126 c.Fatal("timed out")
1130 for k, v := range api.Logs {
1135 c.Check(api.CalledWith("container.log", nil), NotNil)
1136 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1137 c.Check(api.Logs["stdout"].String(), Matches, "(?ms).*foo\n$")
1140 func (s *TestSuite) TestFullRunSetEnv(c *C) {
1141 api, _, _ := s.fullRunHelper(c, `{
1142 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1143 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1145 "environment": {"FROBIZ": "bilbo"},
1146 "mounts": {"/tmp": {"kind": "tmp"} },
1147 "output_path": "/tmp",
1149 "runtime_constraints": {}
1150 }`, nil, 0, func(t *TestDockerClient) {
1151 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1155 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1156 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1157 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)
1160 type ArvMountCmdLine struct {
1165 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
1171 func stubCert(temp string) string {
1172 path := temp + "/ca-certificates.crt"
1173 crt, _ := os.Create(path)
1175 arvadosclient.CertFiles = []string{path}
1179 func (s *TestSuite) TestSetupMounts(c *C) {
1180 api := &ArvTestClient{}
1181 kc := &KeepTestClient{}
1183 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1184 c.Assert(err, IsNil)
1185 am := &ArvMountCmdLine{}
1186 cr.RunArvMount = am.ArvMountTest
1187 cr.ContainerArvClient = &ArvTestClient{}
1188 cr.ContainerKeepClient = &KeepTestClient{}
1190 realTemp, err := ioutil.TempDir("", "crunchrun_test1-")
1191 c.Assert(err, IsNil)
1192 certTemp, err := ioutil.TempDir("", "crunchrun_test2-")
1193 c.Assert(err, IsNil)
1194 stubCertPath := stubCert(certTemp)
1196 cr.parentTemp = realTemp
1198 defer os.RemoveAll(realTemp)
1199 defer os.RemoveAll(certTemp)
1202 cr.MkTempDir = func(_ string, prefix string) (string, error) {
1204 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
1205 err := os.Mkdir(d, os.ModePerm)
1206 if err != nil && strings.Contains(err.Error(), ": file exists") {
1207 // Test case must have pre-populated the tempdir
1213 checkEmpty := func() {
1214 // Should be deleted.
1215 _, err := os.Stat(realTemp)
1216 c.Assert(os.IsNotExist(err), Equals, true)
1218 // Now recreate it for the next test.
1219 c.Assert(os.Mkdir(realTemp, 0777), IsNil)
1224 cr.ArvMountPoint = ""
1225 cr.Container.Mounts = make(map[string]arvados.Mount)
1226 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1227 cr.Container.OutputPath = "/tmp"
1228 cr.statInterval = 5 * time.Second
1229 err := cr.SetupMounts()
1231 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1232 "--read-write", "--crunchstat-interval=5",
1233 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1234 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp"})
1235 os.RemoveAll(cr.ArvMountPoint)
1242 cr.ArvMountPoint = ""
1243 cr.Container.Mounts = make(map[string]arvados.Mount)
1244 cr.Container.Mounts["/out"] = arvados.Mount{Kind: "tmp"}
1245 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1246 cr.Container.OutputPath = "/out"
1248 err := cr.SetupMounts()
1250 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1251 "--read-write", "--crunchstat-interval=5",
1252 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1253 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/out", realTemp + "/tmp3:/tmp"})
1254 os.RemoveAll(cr.ArvMountPoint)
1261 cr.ArvMountPoint = ""
1262 cr.Container.Mounts = make(map[string]arvados.Mount)
1263 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1264 cr.Container.OutputPath = "/tmp"
1267 cr.Container.RuntimeConstraints.API = &apiflag
1269 err := cr.SetupMounts()
1271 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1272 "--read-write", "--crunchstat-interval=5",
1273 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1274 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", stubCertPath + ":/etc/arvados/ca-certificates.crt:ro"})
1275 os.RemoveAll(cr.ArvMountPoint)
1284 cr.ArvMountPoint = ""
1285 cr.Container.Mounts = map[string]arvados.Mount{
1286 "/keeptmp": {Kind: "collection", Writable: true},
1288 cr.Container.OutputPath = "/keeptmp"
1290 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1292 err := cr.SetupMounts()
1294 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1295 "--read-write", "--crunchstat-interval=5",
1296 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1297 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/tmp0:/keeptmp"})
1298 os.RemoveAll(cr.ArvMountPoint)
1305 cr.ArvMountPoint = ""
1306 cr.Container.Mounts = map[string]arvados.Mount{
1307 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1308 "/keepout": {Kind: "collection", Writable: true},
1310 cr.Container.OutputPath = "/keepout"
1312 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1313 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1315 err := cr.SetupMounts()
1317 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1318 "--read-write", "--crunchstat-interval=5",
1319 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1320 sort.StringSlice(cr.Binds).Sort()
1321 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1322 realTemp + "/keep1/tmp0:/keepout"})
1323 os.RemoveAll(cr.ArvMountPoint)
1330 cr.ArvMountPoint = ""
1331 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
1332 cr.Container.Mounts = map[string]arvados.Mount{
1333 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1334 "/keepout": {Kind: "collection", Writable: true},
1336 cr.Container.OutputPath = "/keepout"
1338 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1339 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1341 err := cr.SetupMounts()
1343 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1344 "--read-write", "--crunchstat-interval=5",
1345 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1346 sort.StringSlice(cr.Binds).Sort()
1347 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1348 realTemp + "/keep1/tmp0:/keepout"})
1349 os.RemoveAll(cr.ArvMountPoint)
1354 for _, test := range []struct {
1358 {in: "foo", out: `"foo"`},
1359 {in: nil, out: `null`},
1360 {in: map[string]int64{"foo": 123456789123456789}, out: `{"foo":123456789123456789}`},
1363 cr.ArvMountPoint = ""
1364 cr.Container.Mounts = map[string]arvados.Mount{
1365 "/mnt/test.json": {Kind: "json", Content: test.in},
1367 err := cr.SetupMounts()
1369 sort.StringSlice(cr.Binds).Sort()
1370 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/json2/mountdata.json:/mnt/test.json:ro"})
1371 content, err := ioutil.ReadFile(realTemp + "/json2/mountdata.json")
1373 c.Check(content, DeepEquals, []byte(test.out))
1374 os.RemoveAll(cr.ArvMountPoint)
1379 for _, test := range []struct {
1383 {in: "foo", out: `foo`},
1384 {in: nil, out: "error"},
1385 {in: map[string]int64{"foo": 123456789123456789}, out: "error"},
1388 cr.ArvMountPoint = ""
1389 cr.Container.Mounts = map[string]arvados.Mount{
1390 "/mnt/test.txt": {Kind: "text", Content: test.in},
1392 err := cr.SetupMounts()
1393 if test.out == "error" {
1394 c.Check(err.Error(), Equals, "content for mount \"/mnt/test.txt\" must be a string")
1397 sort.StringSlice(cr.Binds).Sort()
1398 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/text2/mountdata.text:/mnt/test.txt:ro"})
1399 content, err := ioutil.ReadFile(realTemp + "/text2/mountdata.text")
1401 c.Check(content, DeepEquals, []byte(test.out))
1403 os.RemoveAll(cr.ArvMountPoint)
1408 // Read-only mount points are allowed underneath output_dir mount point
1411 cr.ArvMountPoint = ""
1412 cr.Container.Mounts = make(map[string]arvados.Mount)
1413 cr.Container.Mounts = map[string]arvados.Mount{
1414 "/tmp": {Kind: "tmp"},
1415 "/tmp/foo": {Kind: "collection"},
1417 cr.Container.OutputPath = "/tmp"
1419 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1421 err := cr.SetupMounts()
1423 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1424 "--read-write", "--crunchstat-interval=5",
1425 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1426 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", realTemp + "/keep1/tmp0:/tmp/foo:ro"})
1427 os.RemoveAll(cr.ArvMountPoint)
1432 // Writable mount points copied to output_dir mount point
1435 cr.ArvMountPoint = ""
1436 cr.Container.Mounts = make(map[string]arvados.Mount)
1437 cr.Container.Mounts = map[string]arvados.Mount{
1438 "/tmp": {Kind: "tmp"},
1439 "/tmp/foo": {Kind: "collection",
1440 PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53",
1442 "/tmp/bar": {Kind: "collection",
1443 PortableDataHash: "59389a8f9ee9d399be35462a0f92541d+53",
1447 cr.Container.OutputPath = "/tmp"
1449 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1450 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz", os.ModePerm)
1452 rf, _ := os.Create(realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz/quux")
1453 rf.Write([]byte("bar"))
1456 err := cr.SetupMounts()
1458 _, err = os.Stat(cr.HostOutputDir + "/foo")
1460 _, err = os.Stat(cr.HostOutputDir + "/bar/quux")
1462 os.RemoveAll(cr.ArvMountPoint)
1467 // Only mount points of kind 'collection' are allowed underneath output_dir mount point
1470 cr.ArvMountPoint = ""
1471 cr.Container.Mounts = make(map[string]arvados.Mount)
1472 cr.Container.Mounts = map[string]arvados.Mount{
1473 "/tmp": {Kind: "tmp"},
1474 "/tmp/foo": {Kind: "tmp"},
1476 cr.Container.OutputPath = "/tmp"
1478 err := cr.SetupMounts()
1479 c.Check(err, NotNil)
1480 c.Check(err, ErrorMatches, `Only mount points of kind 'collection', 'text' or 'json' are supported underneath the output_path.*`)
1481 os.RemoveAll(cr.ArvMountPoint)
1486 // Only mount point of kind 'collection' is allowed for stdin
1489 cr.ArvMountPoint = ""
1490 cr.Container.Mounts = make(map[string]arvados.Mount)
1491 cr.Container.Mounts = map[string]arvados.Mount{
1492 "stdin": {Kind: "tmp"},
1495 err := cr.SetupMounts()
1496 c.Check(err, NotNil)
1497 c.Check(err, ErrorMatches, `Unsupported mount kind 'tmp' for stdin.*`)
1498 os.RemoveAll(cr.ArvMountPoint)
1506 cr.ArvMountPoint = ""
1507 (*GitMountSuite)(nil).useTestGitServer(c)
1508 cr.token = arvadostest.ActiveToken
1509 cr.Container.Mounts = make(map[string]arvados.Mount)
1510 cr.Container.Mounts = map[string]arvados.Mount{
1513 UUID: arvadostest.Repository2UUID,
1514 Commit: "fd3531f42995344f36c30b79f55f27b502f3d344",
1519 UUID: arvadostest.Repository2UUID,
1520 Commit: "5ebfab0522851df01fec11ec55a6d0f4877b542e",
1524 cr.Container.OutputPath = "/tmp"
1526 err := cr.SetupMounts()
1529 // dirMap[mountpoint] == tmpdir
1530 dirMap := make(map[string]string)
1531 for _, bind := range cr.Binds {
1532 tokens := strings.Split(bind, ":")
1533 dirMap[tokens[1]] = tokens[0]
1535 if cr.Container.Mounts[tokens[1]].Writable {
1536 c.Check(len(tokens), Equals, 2)
1538 c.Check(len(tokens), Equals, 3)
1539 c.Check(tokens[2], Equals, "ro")
1543 data, err := ioutil.ReadFile(dirMap["/tip"] + "/dir1/dir2/file with mode 0644")
1545 c.Check(string(data), Equals, "\000\001\002\003")
1546 _, err = ioutil.ReadFile(dirMap["/tip"] + "/file only on testbranch")
1547 c.Check(err, FitsTypeOf, &os.PathError{})
1548 c.Check(os.IsNotExist(err), Equals, true)
1550 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/dir1/dir2/file with mode 0644")
1552 c.Check(string(data), Equals, "\000\001\002\003")
1553 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/file only on testbranch")
1555 c.Check(string(data), Equals, "testfile\n")
1562 func (s *TestSuite) TestStdout(c *C) {
1564 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1565 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1567 "environment": {"FROBIZ": "bilbo"},
1568 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1569 "output_path": "/tmp",
1571 "runtime_constraints": {}
1574 api, cr, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1575 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1579 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1580 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1581 c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1584 // Used by the TestStdoutWithWrongPath*()
1585 func (s *TestSuite) stdoutErrorRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, err error) {
1586 rec := arvados.Container{}
1587 err = json.Unmarshal([]byte(record), &rec)
1591 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
1593 api = &ArvTestClient{Container: rec}
1594 kc := &KeepTestClient{}
1596 cr, err = NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1597 c.Assert(err, IsNil)
1598 am := &ArvMountCmdLine{}
1599 cr.RunArvMount = am.ArvMountTest
1600 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1601 return &ArvTestClient{}, &KeepTestClient{}, nil, nil
1608 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1609 _, _, err := s.stdoutErrorRunHelper(c, `{
1610 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1611 "output_path": "/tmp"
1612 }`, func(t *TestDockerClient) {})
1614 c.Check(err, NotNil)
1615 c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
1618 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1619 _, _, err := s.stdoutErrorRunHelper(c, `{
1620 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1621 "output_path": "/tmp"
1622 }`, func(t *TestDockerClient) {})
1624 c.Check(err, NotNil)
1625 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'tmp' for stdout"), Equals, true)
1628 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1629 _, _, err := s.stdoutErrorRunHelper(c, `{
1630 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1631 "output_path": "/tmp"
1632 }`, func(t *TestDockerClient) {})
1634 c.Check(err, NotNil)
1635 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'collection' for stdout"), Equals, true)
1638 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1639 defer os.Setenv("ARVADOS_API_HOST", os.Getenv("ARVADOS_API_HOST"))
1640 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1641 api, _, _ := s.fullRunHelper(c, `{
1642 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1643 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1646 "mounts": {"/tmp": {"kind": "tmp"} },
1647 "output_path": "/tmp",
1649 "runtime_constraints": {"API": true}
1650 }`, nil, 0, func(t *TestDockerClient) {
1651 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
1655 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1656 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1657 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "test.arvados.org\n"), Equals, true)
1658 c.Check(api.CalledWith("container.output", "d41d8cd98f00b204e9800998ecf8427e+0"), NotNil)
1661 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1662 defer os.Setenv("ARVADOS_API_HOST", os.Getenv("ARVADOS_API_HOST"))
1663 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1664 api, _, _ := s.fullRunHelper(c, `{
1665 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1666 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1669 "mounts": {"/tmp": {"kind": "tmp"} },
1670 "output_path": "/tmp",
1672 "runtime_constraints": {"API": true}
1673 }`, nil, 0, func(t *TestDockerClient) {
1674 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
1678 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1679 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1680 c.Check(api.CalledWith("container.output", "d4ab34d3d4f8a72f5c4973051ae69fab+122"), NotNil)
1683 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1685 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1686 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1688 "environment": {"FROBIZ": "bilbo"},
1690 "/tmp": {"kind": "tmp"},
1691 "/tmp/foo": {"kind": "collection",
1692 "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1693 "exclude_from_output": true
1695 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1697 "output_path": "/tmp",
1699 "runtime_constraints": {}
1702 extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1704 api, cr, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1705 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1709 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1710 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1711 c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1714 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1716 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1717 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1719 "environment": {"FROBIZ": "bilbo"},
1721 "/tmp": {"kind": "tmp"},
1722 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1723 "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1724 "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1725 "/tmp/foo/baz/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1726 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1728 "output_path": "/tmp",
1730 "runtime_constraints": {}
1733 extraMounts := []string{
1734 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1735 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1736 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1739 api, runner, realtemp := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1740 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1744 c.Check(runner.Binds, DeepEquals, []string{realtemp + "/tmp2:/tmp",
1745 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt:/tmp/foo/bar:ro",
1746 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt:/tmp/foo/baz/sub2file2:ro",
1747 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1:/tmp/foo/sub1:ro",
1748 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt:/tmp/foo/sub1file2:ro",
1751 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1752 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1753 for _, v := range api.Content {
1754 if v["collection"] != nil {
1755 c.Check(v["ensure_unique_name"], Equals, true)
1756 collection := v["collection"].(arvadosclient.Dict)
1757 if strings.Index(collection["name"].(string), "output") == 0 {
1758 manifest := collection["manifest_text"].(string)
1760 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1761 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:bar 36:18:sub1file2
1762 ./foo/baz 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2
1763 ./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1764 ./foo/sub1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1771 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
1773 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1774 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1776 "environment": {"FROBIZ": "bilbo"},
1778 "/tmp": {"kind": "tmp"},
1779 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/subdir1/file2_in_subdir1.txt"},
1780 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1782 "output_path": "/tmp",
1784 "runtime_constraints": {}
1787 extraMounts := []string{
1788 "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1791 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1792 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1796 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1797 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1798 for _, v := range api.Content {
1799 if v["collection"] != nil {
1800 collection := v["collection"].(arvadosclient.Dict)
1801 if strings.Index(collection["name"].(string), "output") == 0 {
1802 manifest := collection["manifest_text"].(string)
1804 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1805 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 10:17:bar
1812 func (s *TestSuite) TestOutputError(c *C) {
1814 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1815 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1817 "environment": {"FROBIZ": "bilbo"},
1819 "/tmp": {"kind": "tmp"}
1821 "output_path": "/tmp",
1823 "runtime_constraints": {}
1826 extraMounts := []string{}
1828 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1829 os.Symlink("/etc/hosts", t.realTemp+"/tmp2/baz")
1833 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1836 func (s *TestSuite) TestStdinCollectionMountPoint(c *C) {
1838 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1839 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1841 "environment": {"FROBIZ": "bilbo"},
1843 "/tmp": {"kind": "tmp"},
1844 "stdin": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/file1_in_main.txt"},
1845 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1847 "output_path": "/tmp",
1849 "runtime_constraints": {}
1852 extraMounts := []string{
1853 "b0def87f80dd594d4675809e83bd4f15+367/file1_in_main.txt",
1856 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1857 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1861 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1862 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1863 for _, v := range api.Content {
1864 if v["collection"] != nil {
1865 collection := v["collection"].(arvadosclient.Dict)
1866 if strings.Index(collection["name"].(string), "output") == 0 {
1867 manifest := collection["manifest_text"].(string)
1868 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1875 func (s *TestSuite) TestStdinJsonMountPoint(c *C) {
1877 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1878 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1880 "environment": {"FROBIZ": "bilbo"},
1882 "/tmp": {"kind": "tmp"},
1883 "stdin": {"kind": "json", "content": "foo"},
1884 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1886 "output_path": "/tmp",
1888 "runtime_constraints": {}
1891 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1892 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1896 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1897 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1898 for _, v := range api.Content {
1899 if v["collection"] != nil {
1900 collection := v["collection"].(arvadosclient.Dict)
1901 if strings.Index(collection["name"].(string), "output") == 0 {
1902 manifest := collection["manifest_text"].(string)
1903 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1910 func (s *TestSuite) TestStderrMount(c *C) {
1911 api, cr, _ := s.fullRunHelper(c, `{
1912 "command": ["/bin/sh", "-c", "echo hello;exit 1"],
1913 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1916 "mounts": {"/tmp": {"kind": "tmp"},
1917 "stdout": {"kind": "file", "path": "/tmp/a/out.txt"},
1918 "stderr": {"kind": "file", "path": "/tmp/b/err.txt"}},
1919 "output_path": "/tmp",
1921 "runtime_constraints": {}
1922 }`, nil, 1, func(t *TestDockerClient) {
1923 t.logWriter.Write(dockerLog(1, "hello\n"))
1924 t.logWriter.Write(dockerLog(2, "oops\n"))
1928 final := api.CalledWith("container.state", "Complete")
1929 c.Assert(final, NotNil)
1930 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1931 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1933 c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", "./a b1946ac92492d2347c6235b4d2611184+6 0:6:out.txt\n./b 38af5c54926b620264ab1501150cf189+5 0:5:err.txt\n"), NotNil)
1936 func (s *TestSuite) TestNumberRoundTrip(c *C) {
1937 kc := &KeepTestClient{}
1939 cr, err := NewContainerRunner(s.client, &ArvTestClient{callraw: true}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1940 c.Assert(err, IsNil)
1941 cr.fetchContainerRecord()
1943 jsondata, err := json.Marshal(cr.Container.Mounts["/json"].Content)
1946 c.Check(string(jsondata), Equals, `{"number":123456789123456789}`)
1949 func (s *TestSuite) TestFullBrokenDocker1(c *C) {
1950 tf, err := ioutil.TempFile("", "brokenNodeHook-")
1951 c.Assert(err, IsNil)
1952 defer os.Remove(tf.Name())
1954 tf.Write([]byte(`#!/bin/sh
1958 os.Chmod(tf.Name(), 0700)
1961 brokenNodeHook = &ech
1963 api, _, _ := s.fullRunHelper(c, `{
1964 "command": ["echo", "hello world"],
1965 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1968 "mounts": {"/tmp": {"kind": "tmp"} },
1969 "output_path": "/tmp",
1971 "runtime_constraints": {}
1972 }`, nil, 2, func(t *TestDockerClient) {
1973 t.logWriter.Write(dockerLog(1, "hello world\n"))
1977 c.Check(api.CalledWith("container.state", "Queued"), NotNil)
1978 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1979 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Running broken node hook.*")
1980 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*killme.*")
1984 func (s *TestSuite) TestFullBrokenDocker2(c *C) {
1986 brokenNodeHook = &ech
1988 api, _, _ := s.fullRunHelper(c, `{
1989 "command": ["echo", "hello world"],
1990 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1993 "mounts": {"/tmp": {"kind": "tmp"} },
1994 "output_path": "/tmp",
1996 "runtime_constraints": {}
1997 }`, nil, 2, func(t *TestDockerClient) {
1998 t.logWriter.Write(dockerLog(1, "hello world\n"))
2002 c.Check(api.CalledWith("container.state", "Queued"), NotNil)
2003 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
2004 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*No broken node hook.*")
2007 func (s *TestSuite) TestFullBrokenDocker3(c *C) {
2009 brokenNodeHook = &ech
2011 api, _, _ := s.fullRunHelper(c, `{
2012 "command": ["echo", "hello world"],
2013 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2016 "mounts": {"/tmp": {"kind": "tmp"} },
2017 "output_path": "/tmp",
2019 "runtime_constraints": {}
2020 }`, nil, 3, func(t *TestDockerClient) {
2021 t.logWriter.Write(dockerLog(1, "hello world\n"))
2025 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2026 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
2029 func (s *TestSuite) TestBadCommand1(c *C) {
2031 brokenNodeHook = &ech
2033 api, _, _ := s.fullRunHelper(c, `{
2034 "command": ["echo", "hello world"],
2035 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2038 "mounts": {"/tmp": {"kind": "tmp"} },
2039 "output_path": "/tmp",
2041 "runtime_constraints": {}
2042 }`, nil, 4, func(t *TestDockerClient) {
2043 t.logWriter.Write(dockerLog(1, "hello world\n"))
2047 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2048 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2051 func (s *TestSuite) TestBadCommand2(c *C) {
2053 brokenNodeHook = &ech
2055 api, _, _ := s.fullRunHelper(c, `{
2056 "command": ["echo", "hello world"],
2057 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2060 "mounts": {"/tmp": {"kind": "tmp"} },
2061 "output_path": "/tmp",
2063 "runtime_constraints": {}
2064 }`, nil, 5, func(t *TestDockerClient) {
2065 t.logWriter.Write(dockerLog(1, "hello world\n"))
2069 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2070 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2073 func (s *TestSuite) TestBadCommand3(c *C) {
2075 brokenNodeHook = &ech
2077 api, _, _ := s.fullRunHelper(c, `{
2078 "command": ["echo", "hello world"],
2079 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2082 "mounts": {"/tmp": {"kind": "tmp"} },
2083 "output_path": "/tmp",
2085 "runtime_constraints": {}
2086 }`, nil, 6, func(t *TestDockerClient) {
2087 t.logWriter.Write(dockerLog(1, "hello world\n"))
2091 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2092 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2095 func (s *TestSuite) TestSecretTextMountPoint(c *C) {
2096 // under normal mounts, gets captured in output, oops
2098 "command": ["true"],
2099 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2102 "/tmp": {"kind": "tmp"},
2103 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2107 "output_path": "/tmp",
2109 "runtime_constraints": {}
2112 api, cr, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2113 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2115 c.Check(content, DeepEquals, []byte("mypassword"))
2119 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2120 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2121 c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), NotNil)
2122 c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ""), IsNil)
2124 // under secret mounts, not captured in output
2126 "command": ["true"],
2127 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2130 "/tmp": {"kind": "tmp"}
2133 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2135 "output_path": "/tmp",
2137 "runtime_constraints": {}
2140 api, cr, _ = s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2141 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2143 c.Check(content, DeepEquals, []byte("mypassword"))
2147 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2148 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2149 c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), IsNil)
2150 c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ""), NotNil)
2153 type FakeProcess struct {
2157 func (fp FakeProcess) CmdlineSlice() ([]string, error) {
2158 return fp.cmdLine, nil