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 kc := &KeepTestClient{}
447 cr, err := NewContainerRunner(s.client, &ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
450 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, error) {
451 return &ArvTestClient{}, kc, nil
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.Container.ContainerImage = hwPDH
570 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, error) {
571 return &ArvErrorTestClient{}, &KeepTestClient{}, nil
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")
583 cr.Container.ContainerImage = hwPDH
584 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, error) {
585 return &ArvTestClient{}, kc, nil
589 c.Assert(err, NotNil)
590 c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
593 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
594 // (3) Collection doesn't contain image
595 kc := &KeepReadErrorTestClient{}
596 cr, err := NewContainerRunner(s.client, &ArvTestClient{}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
598 cr.Container.ContainerImage = otherPDH
599 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, error) {
600 return &ArvTestClient{}, kc, nil
604 c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
607 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
608 // (4) Collection doesn't contain image
609 kc := &KeepReadErrorTestClient{}
610 cr, err := NewContainerRunner(s.client, &ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
612 cr.Container.ContainerImage = hwPDH
613 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, error) {
614 return &ArvTestClient{}, kc, nil
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.MkArvClient = func(token string) (IArvadosClient, IKeepClient, error) {
664 return &ArvTestClient{}, kc, nil
668 cr.NewLogWriter = logs.NewTestLoggingWriter
669 cr.Container.ContainerImage = hwPDH
670 cr.Container.Command = []string{"./hw"}
674 err = cr.CreateContainer()
677 err = cr.StartContainer()
680 err = cr.WaitFinish()
683 c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
684 c.Check(logs.Stderr.String(), Equals, "")
687 func (s *TestSuite) TestCommitLogs(c *C) {
688 api := &ArvTestClient{}
689 kc := &KeepTestClient{}
691 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
693 cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
695 cr.CrunchLog.Print("Hello world!")
696 cr.CrunchLog.Print("Goodbye")
697 cr.finalState = "Complete"
699 err = cr.CommitLogs()
702 c.Check(api.Calls, Equals, 2)
703 c.Check(api.Content[1]["ensure_unique_name"], Equals, true)
704 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
705 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
706 c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
709 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
710 api := &ArvTestClient{}
711 kc := &KeepTestClient{}
713 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
716 err = cr.UpdateContainerRunning()
719 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
722 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
723 api := &ArvTestClient{}
724 kc := &KeepTestClient{}
726 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
729 cr.LogsPDH = new(string)
730 *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
732 cr.ExitCode = new(int)
734 cr.finalState = "Complete"
736 err = cr.UpdateContainerFinal()
739 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
740 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
741 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
744 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
745 api := &ArvTestClient{}
746 kc := &KeepTestClient{}
748 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
751 cr.finalState = "Cancelled"
753 err = cr.UpdateContainerFinal()
756 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
757 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
758 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
761 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
762 // dress rehearsal of the Run() function, starting from a JSON container record.
763 func (s *TestSuite) fullRunHelper(c *C, record string, extraMounts []string, exitCode int, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, realTemp string) {
764 rec := arvados.Container{}
765 err := json.Unmarshal([]byte(record), &rec)
769 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
771 err = json.Unmarshal([]byte(record), &sm)
773 secretMounts, err := json.Marshal(sm)
774 c.Logf("%s %q", sm, secretMounts)
777 s.docker.exitCode = exitCode
779 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
781 api = &ArvTestClient{Container: rec}
783 kc := &KeepTestClient{}
785 cr, err = NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
788 cr.statInterval = 100 * time.Millisecond
789 cr.containerWatchdogInterval = time.Second
790 am := &ArvMountCmdLine{}
791 cr.RunArvMount = am.ArvMountTest
793 realTemp, err = ioutil.TempDir("", "crunchrun_test1-")
795 defer os.RemoveAll(realTemp)
797 s.docker.realTemp = realTemp
800 cr.MkTempDir = func(_ string, prefix string) (string, error) {
802 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, tempcount)
803 err := os.Mkdir(d, os.ModePerm)
804 if err != nil && strings.Contains(err.Error(), ": file exists") {
805 // Test case must have pre-populated the tempdir
810 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, error) {
811 return &ArvTestClient{secretMounts: secretMounts}, &KeepTestClient{}, nil
814 if extraMounts != nil && len(extraMounts) > 0 {
815 err := cr.SetupArvMountPoint("keep")
818 for _, m := range extraMounts {
819 os.MkdirAll(cr.ArvMountPoint+"/by_id/"+m, os.ModePerm)
824 if api.CalledWith("container.state", "Complete") != nil {
828 c.Check(api.WasSetRunning, Equals, true)
829 c.Check(api.Content[api.Calls-2]["container"].(arvadosclient.Dict)["log"], NotNil)
833 for k, v := range api.Logs {
842 func (s *TestSuite) TestFullRunHello(c *C) {
843 api, _, _ := s.fullRunHelper(c, `{
844 "command": ["echo", "hello world"],
845 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
848 "mounts": {"/tmp": {"kind": "tmp"} },
849 "output_path": "/tmp",
851 "runtime_constraints": {}
852 }`, nil, 0, func(t *TestDockerClient) {
853 t.logWriter.Write(dockerLog(1, "hello world\n"))
857 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
858 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
859 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
863 func (s *TestSuite) TestRunTimeExceeded(c *C) {
864 api, _, _ := s.fullRunHelper(c, `{
865 "command": ["sleep", "3"],
866 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
869 "mounts": {"/tmp": {"kind": "tmp"} },
870 "output_path": "/tmp",
872 "runtime_constraints": {},
873 "scheduling_parameters":{"max_run_time": 1}
874 }`, nil, 0, func(t *TestDockerClient) {
875 time.Sleep(3 * time.Second)
879 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
880 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*maximum run time exceeded.*")
883 func (s *TestSuite) TestContainerWaitFails(c *C) {
884 api, _, _ := s.fullRunHelper(c, `{
885 "command": ["sleep", "3"],
886 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
888 "mounts": {"/tmp": {"kind": "tmp"} },
889 "output_path": "/tmp",
891 }`, nil, 0, func(t *TestDockerClient) {
893 time.Sleep(10 * time.Second)
897 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
898 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Container is not running.*")
901 func (s *TestSuite) TestCrunchstat(c *C) {
902 api, _, _ := s.fullRunHelper(c, `{
903 "command": ["sleep", "1"],
904 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
907 "mounts": {"/tmp": {"kind": "tmp"} },
908 "output_path": "/tmp",
910 "runtime_constraints": {}
911 }`, nil, 0, func(t *TestDockerClient) {
912 time.Sleep(time.Second)
916 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
917 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
919 // We didn't actually start a container, so crunchstat didn't
920 // find accounting files and therefore didn't log any stats.
921 // It should have logged a "can't find accounting files"
922 // message after one poll interval, though, so we can confirm
924 c.Assert(api.Logs["crunchstat"], NotNil)
925 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
927 // The "files never appeared" log assures us that we called
928 // (*crunchstat.Reporter)Stop(), and that we set it up with
929 // the correct container ID "abcde":
930 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files never appeared for abcde\n`)
933 func (s *TestSuite) TestNodeInfoLog(c *C) {
934 os.Setenv("SLURMD_NODENAME", "compute2")
935 api, _, _ := s.fullRunHelper(c, `{
936 "command": ["sleep", "1"],
937 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
940 "mounts": {"/tmp": {"kind": "tmp"} },
941 "output_path": "/tmp",
943 "runtime_constraints": {}
945 func(t *TestDockerClient) {
946 time.Sleep(time.Second)
950 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
951 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
953 c.Assert(api.Logs["node"], NotNil)
954 json := api.Logs["node"].String()
955 c.Check(json, Matches, `(?ms).*"uuid": *"zzzzz-7ekkf-2z3mc76g2q73aio".*`)
956 c.Check(json, Matches, `(?ms).*"total_cpu_cores": *16.*`)
957 c.Check(json, Not(Matches), `(?ms).*"info":.*`)
959 c.Assert(api.Logs["node-info"], NotNil)
960 json = api.Logs["node-info"].String()
961 c.Check(json, Matches, `(?ms).*Host Information.*`)
962 c.Check(json, Matches, `(?ms).*CPU Information.*`)
963 c.Check(json, Matches, `(?ms).*Memory Information.*`)
964 c.Check(json, Matches, `(?ms).*Disk Space.*`)
965 c.Check(json, Matches, `(?ms).*Disk INodes.*`)
968 func (s *TestSuite) TestContainerRecordLog(c *C) {
969 api, _, _ := s.fullRunHelper(c, `{
970 "command": ["sleep", "1"],
971 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
974 "mounts": {"/tmp": {"kind": "tmp"} },
975 "output_path": "/tmp",
977 "runtime_constraints": {}
979 func(t *TestDockerClient) {
980 time.Sleep(time.Second)
984 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
985 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
987 c.Assert(api.Logs["container"], NotNil)
988 c.Check(api.Logs["container"].String(), Matches, `(?ms).*container_image.*`)
991 func (s *TestSuite) TestFullRunStderr(c *C) {
992 api, _, _ := s.fullRunHelper(c, `{
993 "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
994 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
997 "mounts": {"/tmp": {"kind": "tmp"} },
998 "output_path": "/tmp",
1000 "runtime_constraints": {}
1001 }`, nil, 1, func(t *TestDockerClient) {
1002 t.logWriter.Write(dockerLog(1, "hello\n"))
1003 t.logWriter.Write(dockerLog(2, "world\n"))
1007 final := api.CalledWith("container.state", "Complete")
1008 c.Assert(final, NotNil)
1009 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1010 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1012 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
1013 c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
1016 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
1017 api, _, _ := s.fullRunHelper(c, `{
1019 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1022 "mounts": {"/tmp": {"kind": "tmp"} },
1023 "output_path": "/tmp",
1025 "runtime_constraints": {}
1026 }`, nil, 0, func(t *TestDockerClient) {
1027 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
1031 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1032 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1033 c.Log(api.Logs["stdout"])
1034 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
1037 func (s *TestSuite) TestFullRunSetCwd(c *C) {
1038 api, _, _ := s.fullRunHelper(c, `{
1040 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1043 "mounts": {"/tmp": {"kind": "tmp"} },
1044 "output_path": "/tmp",
1046 "runtime_constraints": {}
1047 }`, nil, 0, func(t *TestDockerClient) {
1048 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
1052 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1053 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1054 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
1057 func (s *TestSuite) TestStopOnSignal(c *C) {
1058 s.testStopContainer(c, func(cr *ContainerRunner) {
1060 for !s.docker.calledWait {
1061 time.Sleep(time.Millisecond)
1063 cr.SigChan <- syscall.SIGINT
1068 func (s *TestSuite) TestStopOnArvMountDeath(c *C) {
1069 s.testStopContainer(c, func(cr *ContainerRunner) {
1070 cr.ArvMountExit = make(chan error)
1072 cr.ArvMountExit <- exec.Command("true").Run()
1073 close(cr.ArvMountExit)
1078 func (s *TestSuite) testStopContainer(c *C, setup func(cr *ContainerRunner)) {
1080 "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
1081 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1084 "mounts": {"/tmp": {"kind": "tmp"} },
1085 "output_path": "/tmp",
1087 "runtime_constraints": {}
1090 rec := arvados.Container{}
1091 err := json.Unmarshal([]byte(record), &rec)
1094 s.docker.fn = func(t *TestDockerClient) {
1096 t.logWriter.Write(dockerLog(1, "foo\n"))
1099 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
1101 api := &ArvTestClient{Container: rec}
1102 kc := &KeepTestClient{}
1104 cr, err := NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1105 c.Assert(err, IsNil)
1106 cr.RunArvMount = func([]string, string) (*exec.Cmd, error) { return nil, nil }
1107 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, error) {
1108 return &ArvTestClient{}, &KeepTestClient{}, nil
1112 done := make(chan error)
1117 case <-time.After(20 * time.Second):
1118 pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
1119 c.Fatal("timed out")
1123 for k, v := range api.Logs {
1128 c.Check(api.CalledWith("container.log", nil), NotNil)
1129 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1130 c.Check(api.Logs["stdout"].String(), Matches, "(?ms).*foo\n$")
1133 func (s *TestSuite) TestFullRunSetEnv(c *C) {
1134 api, _, _ := s.fullRunHelper(c, `{
1135 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1136 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1138 "environment": {"FROBIZ": "bilbo"},
1139 "mounts": {"/tmp": {"kind": "tmp"} },
1140 "output_path": "/tmp",
1142 "runtime_constraints": {}
1143 }`, nil, 0, func(t *TestDockerClient) {
1144 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1148 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1149 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1150 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)
1153 type ArvMountCmdLine struct {
1158 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
1164 func stubCert(temp string) string {
1165 path := temp + "/ca-certificates.crt"
1166 crt, _ := os.Create(path)
1168 arvadosclient.CertFiles = []string{path}
1172 func (s *TestSuite) TestSetupMounts(c *C) {
1173 api := &ArvTestClient{}
1174 kc := &KeepTestClient{}
1176 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1177 c.Assert(err, IsNil)
1178 am := &ArvMountCmdLine{}
1179 cr.RunArvMount = am.ArvMountTest
1181 realTemp, err := ioutil.TempDir("", "crunchrun_test1-")
1182 c.Assert(err, IsNil)
1183 certTemp, err := ioutil.TempDir("", "crunchrun_test2-")
1184 c.Assert(err, IsNil)
1185 stubCertPath := stubCert(certTemp)
1187 cr.parentTemp = realTemp
1189 defer os.RemoveAll(realTemp)
1190 defer os.RemoveAll(certTemp)
1193 cr.MkTempDir = func(_ string, prefix string) (string, error) {
1195 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
1196 err := os.Mkdir(d, os.ModePerm)
1197 if err != nil && strings.Contains(err.Error(), ": file exists") {
1198 // Test case must have pre-populated the tempdir
1204 checkEmpty := func() {
1205 // Should be deleted.
1206 _, err := os.Stat(realTemp)
1207 c.Assert(os.IsNotExist(err), Equals, true)
1209 // Now recreate it for the next test.
1210 c.Assert(os.Mkdir(realTemp, 0777), IsNil)
1215 cr.ArvMountPoint = ""
1216 cr.Container.Mounts = make(map[string]arvados.Mount)
1217 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1218 cr.Container.OutputPath = "/tmp"
1219 cr.statInterval = 5 * time.Second
1220 err := cr.SetupMounts()
1222 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1223 "--read-write", "--crunchstat-interval=5",
1224 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1225 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp"})
1226 os.RemoveAll(cr.ArvMountPoint)
1233 cr.ArvMountPoint = ""
1234 cr.Container.Mounts = make(map[string]arvados.Mount)
1235 cr.Container.Mounts["/out"] = arvados.Mount{Kind: "tmp"}
1236 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1237 cr.Container.OutputPath = "/out"
1239 err := cr.SetupMounts()
1241 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1242 "--read-write", "--crunchstat-interval=5",
1243 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1244 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/out", realTemp + "/tmp3:/tmp"})
1245 os.RemoveAll(cr.ArvMountPoint)
1252 cr.ArvMountPoint = ""
1253 cr.Container.Mounts = make(map[string]arvados.Mount)
1254 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1255 cr.Container.OutputPath = "/tmp"
1258 cr.Container.RuntimeConstraints.API = &apiflag
1260 err := cr.SetupMounts()
1262 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1263 "--read-write", "--crunchstat-interval=5",
1264 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1265 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", stubCertPath + ":/etc/arvados/ca-certificates.crt:ro"})
1266 os.RemoveAll(cr.ArvMountPoint)
1275 cr.ArvMountPoint = ""
1276 cr.Container.Mounts = map[string]arvados.Mount{
1277 "/keeptmp": {Kind: "collection", Writable: true},
1279 cr.Container.OutputPath = "/keeptmp"
1281 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1283 err := cr.SetupMounts()
1285 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1286 "--read-write", "--crunchstat-interval=5",
1287 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1288 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/tmp0:/keeptmp"})
1289 os.RemoveAll(cr.ArvMountPoint)
1296 cr.ArvMountPoint = ""
1297 cr.Container.Mounts = map[string]arvados.Mount{
1298 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1299 "/keepout": {Kind: "collection", Writable: true},
1301 cr.Container.OutputPath = "/keepout"
1303 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1304 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1306 err := cr.SetupMounts()
1308 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1309 "--read-write", "--crunchstat-interval=5",
1310 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1311 sort.StringSlice(cr.Binds).Sort()
1312 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1313 realTemp + "/keep1/tmp0:/keepout"})
1314 os.RemoveAll(cr.ArvMountPoint)
1321 cr.ArvMountPoint = ""
1322 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
1323 cr.Container.Mounts = map[string]arvados.Mount{
1324 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1325 "/keepout": {Kind: "collection", Writable: true},
1327 cr.Container.OutputPath = "/keepout"
1329 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1330 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1332 err := cr.SetupMounts()
1334 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1335 "--read-write", "--crunchstat-interval=5",
1336 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1337 sort.StringSlice(cr.Binds).Sort()
1338 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1339 realTemp + "/keep1/tmp0:/keepout"})
1340 os.RemoveAll(cr.ArvMountPoint)
1345 for _, test := range []struct {
1349 {in: "foo", out: `"foo"`},
1350 {in: nil, out: `null`},
1351 {in: map[string]int64{"foo": 123456789123456789}, out: `{"foo":123456789123456789}`},
1354 cr.ArvMountPoint = ""
1355 cr.Container.Mounts = map[string]arvados.Mount{
1356 "/mnt/test.json": {Kind: "json", Content: test.in},
1358 err := cr.SetupMounts()
1360 sort.StringSlice(cr.Binds).Sort()
1361 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/json2/mountdata.json:/mnt/test.json:ro"})
1362 content, err := ioutil.ReadFile(realTemp + "/json2/mountdata.json")
1364 c.Check(content, DeepEquals, []byte(test.out))
1365 os.RemoveAll(cr.ArvMountPoint)
1370 for _, test := range []struct {
1374 {in: "foo", out: `foo`},
1375 {in: nil, out: "error"},
1376 {in: map[string]int64{"foo": 123456789123456789}, out: "error"},
1379 cr.ArvMountPoint = ""
1380 cr.Container.Mounts = map[string]arvados.Mount{
1381 "/mnt/test.txt": {Kind: "text", Content: test.in},
1383 err := cr.SetupMounts()
1384 if test.out == "error" {
1385 c.Check(err.Error(), Equals, "content for mount \"/mnt/test.txt\" must be a string")
1388 sort.StringSlice(cr.Binds).Sort()
1389 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/text2/mountdata.text:/mnt/test.txt:ro"})
1390 content, err := ioutil.ReadFile(realTemp + "/text2/mountdata.text")
1392 c.Check(content, DeepEquals, []byte(test.out))
1394 os.RemoveAll(cr.ArvMountPoint)
1399 // Read-only mount points are allowed underneath output_dir mount point
1402 cr.ArvMountPoint = ""
1403 cr.Container.Mounts = make(map[string]arvados.Mount)
1404 cr.Container.Mounts = map[string]arvados.Mount{
1405 "/tmp": {Kind: "tmp"},
1406 "/tmp/foo": {Kind: "collection"},
1408 cr.Container.OutputPath = "/tmp"
1410 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1412 err := cr.SetupMounts()
1414 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1415 "--read-write", "--crunchstat-interval=5",
1416 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1417 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", realTemp + "/keep1/tmp0:/tmp/foo:ro"})
1418 os.RemoveAll(cr.ArvMountPoint)
1423 // Writable mount points copied to output_dir mount point
1426 cr.ArvMountPoint = ""
1427 cr.Container.Mounts = make(map[string]arvados.Mount)
1428 cr.Container.Mounts = map[string]arvados.Mount{
1429 "/tmp": {Kind: "tmp"},
1430 "/tmp/foo": {Kind: "collection",
1431 PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53",
1433 "/tmp/bar": {Kind: "collection",
1434 PortableDataHash: "59389a8f9ee9d399be35462a0f92541d+53",
1438 cr.Container.OutputPath = "/tmp"
1440 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1441 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz", os.ModePerm)
1443 rf, _ := os.Create(realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz/quux")
1444 rf.Write([]byte("bar"))
1447 err := cr.SetupMounts()
1449 _, err = os.Stat(cr.HostOutputDir + "/foo")
1451 _, err = os.Stat(cr.HostOutputDir + "/bar/quux")
1453 os.RemoveAll(cr.ArvMountPoint)
1458 // Only mount points of kind 'collection' are allowed underneath output_dir mount point
1461 cr.ArvMountPoint = ""
1462 cr.Container.Mounts = make(map[string]arvados.Mount)
1463 cr.Container.Mounts = map[string]arvados.Mount{
1464 "/tmp": {Kind: "tmp"},
1465 "/tmp/foo": {Kind: "tmp"},
1467 cr.Container.OutputPath = "/tmp"
1469 err := cr.SetupMounts()
1470 c.Check(err, NotNil)
1471 c.Check(err, ErrorMatches, `Only mount points of kind 'collection', 'text' or 'json' are supported underneath the output_path.*`)
1472 os.RemoveAll(cr.ArvMountPoint)
1477 // Only mount point of kind 'collection' is allowed for stdin
1480 cr.ArvMountPoint = ""
1481 cr.Container.Mounts = make(map[string]arvados.Mount)
1482 cr.Container.Mounts = map[string]arvados.Mount{
1483 "stdin": {Kind: "tmp"},
1486 err := cr.SetupMounts()
1487 c.Check(err, NotNil)
1488 c.Check(err, ErrorMatches, `Unsupported mount kind 'tmp' for stdin.*`)
1489 os.RemoveAll(cr.ArvMountPoint)
1497 cr.ArvMountPoint = ""
1498 (*GitMountSuite)(nil).useTestGitServer(c)
1499 cr.token = arvadostest.ActiveToken
1500 cr.Container.Mounts = make(map[string]arvados.Mount)
1501 cr.Container.Mounts = map[string]arvados.Mount{
1504 UUID: arvadostest.Repository2UUID,
1505 Commit: "fd3531f42995344f36c30b79f55f27b502f3d344",
1510 UUID: arvadostest.Repository2UUID,
1511 Commit: "5ebfab0522851df01fec11ec55a6d0f4877b542e",
1515 cr.Container.OutputPath = "/tmp"
1517 err := cr.SetupMounts()
1520 // dirMap[mountpoint] == tmpdir
1521 dirMap := make(map[string]string)
1522 for _, bind := range cr.Binds {
1523 tokens := strings.Split(bind, ":")
1524 dirMap[tokens[1]] = tokens[0]
1526 if cr.Container.Mounts[tokens[1]].Writable {
1527 c.Check(len(tokens), Equals, 2)
1529 c.Check(len(tokens), Equals, 3)
1530 c.Check(tokens[2], Equals, "ro")
1534 data, err := ioutil.ReadFile(dirMap["/tip"] + "/dir1/dir2/file with mode 0644")
1536 c.Check(string(data), Equals, "\000\001\002\003")
1537 _, err = ioutil.ReadFile(dirMap["/tip"] + "/file only on testbranch")
1538 c.Check(err, FitsTypeOf, &os.PathError{})
1539 c.Check(os.IsNotExist(err), Equals, true)
1541 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/dir1/dir2/file with mode 0644")
1543 c.Check(string(data), Equals, "\000\001\002\003")
1544 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/file only on testbranch")
1546 c.Check(string(data), Equals, "testfile\n")
1553 func (s *TestSuite) TestStdout(c *C) {
1555 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1556 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1558 "environment": {"FROBIZ": "bilbo"},
1559 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1560 "output_path": "/tmp",
1562 "runtime_constraints": {}
1565 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1566 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1570 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1571 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1572 c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1575 // Used by the TestStdoutWithWrongPath*()
1576 func (s *TestSuite) stdoutErrorRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, err error) {
1577 rec := arvados.Container{}
1578 err = json.Unmarshal([]byte(record), &rec)
1582 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
1584 api = &ArvTestClient{Container: rec}
1585 kc := &KeepTestClient{}
1587 cr, err = NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1588 c.Assert(err, IsNil)
1589 am := &ArvMountCmdLine{}
1590 cr.RunArvMount = am.ArvMountTest
1591 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, error) {
1592 return &ArvTestClient{}, &KeepTestClient{}, nil
1599 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1600 _, _, err := s.stdoutErrorRunHelper(c, `{
1601 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1602 "output_path": "/tmp"
1603 }`, func(t *TestDockerClient) {})
1605 c.Check(err, NotNil)
1606 c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
1609 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1610 _, _, err := s.stdoutErrorRunHelper(c, `{
1611 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1612 "output_path": "/tmp"
1613 }`, func(t *TestDockerClient) {})
1615 c.Check(err, NotNil)
1616 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'tmp' for stdout"), Equals, true)
1619 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1620 _, _, err := s.stdoutErrorRunHelper(c, `{
1621 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1622 "output_path": "/tmp"
1623 }`, func(t *TestDockerClient) {})
1625 c.Check(err, NotNil)
1626 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'collection' for stdout"), Equals, true)
1629 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1630 defer os.Setenv("ARVADOS_API_HOST", os.Getenv("ARVADOS_API_HOST"))
1631 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1632 api, _, _ := s.fullRunHelper(c, `{
1633 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1634 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1637 "mounts": {"/tmp": {"kind": "tmp"} },
1638 "output_path": "/tmp",
1640 "runtime_constraints": {"API": true}
1641 }`, nil, 0, func(t *TestDockerClient) {
1642 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
1646 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1647 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1648 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "test.arvados.org\n"), Equals, true)
1649 c.Check(api.CalledWith("container.output", "d41d8cd98f00b204e9800998ecf8427e+0"), NotNil)
1652 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1653 defer os.Setenv("ARVADOS_API_HOST", os.Getenv("ARVADOS_API_HOST"))
1654 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1655 api, _, _ := s.fullRunHelper(c, `{
1656 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1657 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1660 "mounts": {"/tmp": {"kind": "tmp"} },
1661 "output_path": "/tmp",
1663 "runtime_constraints": {"API": true}
1664 }`, nil, 0, func(t *TestDockerClient) {
1665 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
1669 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1670 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1671 c.Check(api.CalledWith("container.output", "d4ab34d3d4f8a72f5c4973051ae69fab+122"), NotNil)
1674 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1676 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1677 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1679 "environment": {"FROBIZ": "bilbo"},
1681 "/tmp": {"kind": "tmp"},
1682 "/tmp/foo": {"kind": "collection",
1683 "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1684 "exclude_from_output": true
1686 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1688 "output_path": "/tmp",
1690 "runtime_constraints": {}
1693 extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1695 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1696 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1700 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1701 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1702 c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1705 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1707 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1708 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1710 "environment": {"FROBIZ": "bilbo"},
1712 "/tmp": {"kind": "tmp"},
1713 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1714 "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1715 "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1716 "/tmp/foo/baz/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1717 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1719 "output_path": "/tmp",
1721 "runtime_constraints": {}
1724 extraMounts := []string{
1725 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1726 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1727 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1730 api, runner, realtemp := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1731 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1735 c.Check(runner.Binds, DeepEquals, []string{realtemp + "/tmp2:/tmp",
1736 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt:/tmp/foo/bar:ro",
1737 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt:/tmp/foo/baz/sub2file2:ro",
1738 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1:/tmp/foo/sub1:ro",
1739 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt:/tmp/foo/sub1file2:ro",
1742 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1743 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1744 for _, v := range api.Content {
1745 if v["collection"] != nil {
1746 c.Check(v["ensure_unique_name"], Equals, true)
1747 collection := v["collection"].(arvadosclient.Dict)
1748 if strings.Index(collection["name"].(string), "output") == 0 {
1749 manifest := collection["manifest_text"].(string)
1751 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1752 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:bar 36:18:sub1file2
1753 ./foo/baz 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2
1754 ./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1755 ./foo/sub1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1762 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
1764 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1765 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1767 "environment": {"FROBIZ": "bilbo"},
1769 "/tmp": {"kind": "tmp"},
1770 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/subdir1/file2_in_subdir1.txt"},
1771 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1773 "output_path": "/tmp",
1775 "runtime_constraints": {}
1778 extraMounts := []string{
1779 "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1782 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1783 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1787 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1788 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1789 for _, v := range api.Content {
1790 if v["collection"] != nil {
1791 collection := v["collection"].(arvadosclient.Dict)
1792 if strings.Index(collection["name"].(string), "output") == 0 {
1793 manifest := collection["manifest_text"].(string)
1795 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1796 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 10:17:bar
1803 func (s *TestSuite) TestOutputError(c *C) {
1805 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1806 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1808 "environment": {"FROBIZ": "bilbo"},
1810 "/tmp": {"kind": "tmp"}
1812 "output_path": "/tmp",
1814 "runtime_constraints": {}
1817 extraMounts := []string{}
1819 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1820 os.Symlink("/etc/hosts", t.realTemp+"/tmp2/baz")
1824 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1827 func (s *TestSuite) TestStdinCollectionMountPoint(c *C) {
1829 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1830 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1832 "environment": {"FROBIZ": "bilbo"},
1834 "/tmp": {"kind": "tmp"},
1835 "stdin": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/file1_in_main.txt"},
1836 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1838 "output_path": "/tmp",
1840 "runtime_constraints": {}
1843 extraMounts := []string{
1844 "b0def87f80dd594d4675809e83bd4f15+367/file1_in_main.txt",
1847 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1848 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1852 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1853 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1854 for _, v := range api.Content {
1855 if v["collection"] != nil {
1856 collection := v["collection"].(arvadosclient.Dict)
1857 if strings.Index(collection["name"].(string), "output") == 0 {
1858 manifest := collection["manifest_text"].(string)
1859 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1866 func (s *TestSuite) TestStdinJsonMountPoint(c *C) {
1868 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1869 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1871 "environment": {"FROBIZ": "bilbo"},
1873 "/tmp": {"kind": "tmp"},
1874 "stdin": {"kind": "json", "content": "foo"},
1875 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1877 "output_path": "/tmp",
1879 "runtime_constraints": {}
1882 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1883 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1887 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1888 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1889 for _, v := range api.Content {
1890 if v["collection"] != nil {
1891 collection := v["collection"].(arvadosclient.Dict)
1892 if strings.Index(collection["name"].(string), "output") == 0 {
1893 manifest := collection["manifest_text"].(string)
1894 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1901 func (s *TestSuite) TestStderrMount(c *C) {
1902 api, _, _ := s.fullRunHelper(c, `{
1903 "command": ["/bin/sh", "-c", "echo hello;exit 1"],
1904 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1907 "mounts": {"/tmp": {"kind": "tmp"},
1908 "stdout": {"kind": "file", "path": "/tmp/a/out.txt"},
1909 "stderr": {"kind": "file", "path": "/tmp/b/err.txt"}},
1910 "output_path": "/tmp",
1912 "runtime_constraints": {}
1913 }`, nil, 1, func(t *TestDockerClient) {
1914 t.logWriter.Write(dockerLog(1, "hello\n"))
1915 t.logWriter.Write(dockerLog(2, "oops\n"))
1919 final := api.CalledWith("container.state", "Complete")
1920 c.Assert(final, NotNil)
1921 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1922 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1924 c.Check(api.CalledWith("collection.manifest_text", "./a b1946ac92492d2347c6235b4d2611184+6 0:6:out.txt\n./b 38af5c54926b620264ab1501150cf189+5 0:5:err.txt\n"), NotNil)
1927 func (s *TestSuite) TestNumberRoundTrip(c *C) {
1928 kc := &KeepTestClient{}
1930 cr, err := NewContainerRunner(s.client, &ArvTestClient{callraw: true}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1931 c.Assert(err, IsNil)
1932 cr.fetchContainerRecord()
1934 jsondata, err := json.Marshal(cr.Container.Mounts["/json"].Content)
1937 c.Check(string(jsondata), Equals, `{"number":123456789123456789}`)
1940 func (s *TestSuite) TestFullBrokenDocker1(c *C) {
1941 tf, err := ioutil.TempFile("", "brokenNodeHook-")
1942 c.Assert(err, IsNil)
1943 defer os.Remove(tf.Name())
1945 tf.Write([]byte(`#!/bin/sh
1949 os.Chmod(tf.Name(), 0700)
1952 brokenNodeHook = &ech
1954 api, _, _ := s.fullRunHelper(c, `{
1955 "command": ["echo", "hello world"],
1956 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1959 "mounts": {"/tmp": {"kind": "tmp"} },
1960 "output_path": "/tmp",
1962 "runtime_constraints": {}
1963 }`, nil, 2, func(t *TestDockerClient) {
1964 t.logWriter.Write(dockerLog(1, "hello world\n"))
1968 c.Check(api.CalledWith("container.state", "Queued"), NotNil)
1969 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1970 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Running broken node hook.*")
1971 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*killme.*")
1975 func (s *TestSuite) TestFullBrokenDocker2(c *C) {
1977 brokenNodeHook = &ech
1979 api, _, _ := s.fullRunHelper(c, `{
1980 "command": ["echo", "hello world"],
1981 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1984 "mounts": {"/tmp": {"kind": "tmp"} },
1985 "output_path": "/tmp",
1987 "runtime_constraints": {}
1988 }`, nil, 2, func(t *TestDockerClient) {
1989 t.logWriter.Write(dockerLog(1, "hello world\n"))
1993 c.Check(api.CalledWith("container.state", "Queued"), NotNil)
1994 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1995 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*No broken node hook.*")
1998 func (s *TestSuite) TestFullBrokenDocker3(c *C) {
2000 brokenNodeHook = &ech
2002 api, _, _ := s.fullRunHelper(c, `{
2003 "command": ["echo", "hello world"],
2004 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2007 "mounts": {"/tmp": {"kind": "tmp"} },
2008 "output_path": "/tmp",
2010 "runtime_constraints": {}
2011 }`, nil, 3, func(t *TestDockerClient) {
2012 t.logWriter.Write(dockerLog(1, "hello world\n"))
2016 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2017 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
2020 func (s *TestSuite) TestBadCommand1(c *C) {
2022 brokenNodeHook = &ech
2024 api, _, _ := s.fullRunHelper(c, `{
2025 "command": ["echo", "hello world"],
2026 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2029 "mounts": {"/tmp": {"kind": "tmp"} },
2030 "output_path": "/tmp",
2032 "runtime_constraints": {}
2033 }`, nil, 4, func(t *TestDockerClient) {
2034 t.logWriter.Write(dockerLog(1, "hello world\n"))
2038 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2039 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2042 func (s *TestSuite) TestBadCommand2(c *C) {
2044 brokenNodeHook = &ech
2046 api, _, _ := s.fullRunHelper(c, `{
2047 "command": ["echo", "hello world"],
2048 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2051 "mounts": {"/tmp": {"kind": "tmp"} },
2052 "output_path": "/tmp",
2054 "runtime_constraints": {}
2055 }`, nil, 5, func(t *TestDockerClient) {
2056 t.logWriter.Write(dockerLog(1, "hello world\n"))
2060 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2061 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2064 func (s *TestSuite) TestBadCommand3(c *C) {
2066 brokenNodeHook = &ech
2068 api, _, _ := s.fullRunHelper(c, `{
2069 "command": ["echo", "hello world"],
2070 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2073 "mounts": {"/tmp": {"kind": "tmp"} },
2074 "output_path": "/tmp",
2076 "runtime_constraints": {}
2077 }`, nil, 6, func(t *TestDockerClient) {
2078 t.logWriter.Write(dockerLog(1, "hello world\n"))
2082 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2083 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2086 func (s *TestSuite) TestSecretTextMountPoint(c *C) {
2087 // under normal mounts, gets captured in output, oops
2089 "command": ["true"],
2090 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2093 "/tmp": {"kind": "tmp"},
2094 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2098 "output_path": "/tmp",
2100 "runtime_constraints": {}
2103 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2104 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2106 c.Check(content, DeepEquals, []byte("mypassword"))
2110 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2111 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2112 c.Check(api.CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), NotNil)
2113 c.Check(api.CalledWith("collection.manifest_text", ""), IsNil)
2115 // under secret mounts, not captured in output
2117 "command": ["true"],
2118 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2121 "/tmp": {"kind": "tmp"}
2124 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2126 "output_path": "/tmp",
2128 "runtime_constraints": {}
2131 api, _, _ = s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2132 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2134 c.Check(content, DeepEquals, []byte("mypassword"))
2138 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2139 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2140 c.Check(api.CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), IsNil)
2141 c.Check(api.CalledWith("collection.manifest_text", ""), NotNil)
2144 type FakeProcess struct {
2148 func (fp FakeProcess) CmdlineSlice() ([]string, error) {
2149 return fp.cmdLine, nil
2152 func (s *TestSuite) helpCheckContainerd(c *C, lp func() ([]PsProcess, error)) error {
2153 kc := &KeepTestClient{}
2155 cr, err := NewContainerRunner(s.client, &ArvTestClient{callraw: true}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
2156 cr.checkContainerd = time.Duration(100 * time.Millisecond)
2157 c.Assert(err, IsNil)
2158 cr.ListProcesses = lp
2160 s.docker.fn = func(t *TestDockerClient) {
2161 time.Sleep(1 * time.Second)
2165 err = cr.CreateContainer()
2168 err = cr.StartContainer()
2171 err = cr.WaitFinish()
2176 func (s *TestSuite) TestCheckContainerdPresent(c *C) {
2177 err := s.helpCheckContainerd(c, func() ([]PsProcess, error) {
2178 return []PsProcess{FakeProcess{[]string{"docker-containerd"}}}, nil
2183 func (s *TestSuite) TestCheckContainerdMissing(c *C) {
2184 err := s.helpCheckContainerd(c, func() ([]PsProcess, error) {
2185 return []PsProcess{FakeProcess{[]string{"abc"}}}, nil
2187 c.Check(err, ErrorMatches, `'containerd' not found in process list.`)