1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
27 "git.arvados.org/arvados.git/sdk/go/arvados"
28 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
29 "git.arvados.org/arvados.git/sdk/go/arvadostest"
30 "git.arvados.org/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")
164 func (t *TestDockerClient) ContainerRemove(ctx context.Context, container string, options dockertypes.ContainerRemoveOptions) error {
169 func (t *TestDockerClient) ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error) {
171 body := make(chan dockercontainer.ContainerWaitOKBody, 1)
172 err := make(chan error)
175 body <- dockercontainer.ContainerWaitOKBody{StatusCode: int64(t.exitCode)}
180 func (t *TestDockerClient) ContainerInspect(ctx context.Context, id string) (c dockertypes.ContainerJSON, err error) {
181 c.ContainerJSONBase = &dockertypes.ContainerJSONBase{}
184 c.State = &dockertypes.ContainerState{Status: "exited", Dead: true}
186 c.State = &dockertypes.ContainerState{Status: "running", Pid: 1234, Running: true}
191 func (t *TestDockerClient) ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error) {
193 return dockertypes.ImageInspect{}, nil, fmt.Errorf("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?")
196 if t.imageLoaded == image {
197 return dockertypes.ImageInspect{}, nil, nil
199 return dockertypes.ImageInspect{}, nil, errors.New("")
202 func (t *TestDockerClient) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error) {
204 return dockertypes.ImageLoadResponse{}, fmt.Errorf("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?")
206 _, err := io.Copy(ioutil.Discard, input)
208 return dockertypes.ImageLoadResponse{}, err
210 t.imageLoaded = hwImageID
211 return dockertypes.ImageLoadResponse{Body: ioutil.NopCloser(input)}, nil
214 func (*TestDockerClient) ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {
218 func (client *ArvTestClient) Create(resourceType string,
219 parameters arvadosclient.Dict,
220 output interface{}) error {
223 defer client.Mutex.Unlock()
226 client.Content = append(client.Content, parameters)
228 if resourceType == "logs" {
229 et := parameters["log"].(arvadosclient.Dict)["event_type"].(string)
230 if client.Logs == nil {
231 client.Logs = make(map[string]*bytes.Buffer)
233 if client.Logs[et] == nil {
234 client.Logs[et] = &bytes.Buffer{}
236 client.Logs[et].Write([]byte(parameters["log"].(arvadosclient.Dict)["properties"].(map[string]string)["text"]))
239 if resourceType == "collections" && output != nil {
240 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
241 outmap := output.(*arvados.Collection)
242 outmap.PortableDataHash = fmt.Sprintf("%x+%d", md5.Sum([]byte(mt)), len(mt))
243 outmap.UUID = fmt.Sprintf("zzzzz-4zz18-%15.15x", md5.Sum([]byte(mt)))
249 func (client *ArvTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
251 case method == "GET" && resourceType == "containers" && action == "auth":
252 return json.Unmarshal([]byte(`{
253 "kind": "arvados#api_client_authorization",
254 "uuid": "`+fakeAuthUUID+`",
255 "api_token": "`+fakeAuthToken+`"
257 case method == "GET" && resourceType == "containers" && action == "secret_mounts":
258 if client.secretMounts != nil {
259 return json.Unmarshal(client.secretMounts, output)
261 return json.Unmarshal([]byte(`{"secret_mounts":{}}`), output)
263 return fmt.Errorf("Not found")
267 func (client *ArvTestClient) CallRaw(method, resourceType, uuid, action string,
268 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
270 if method == "GET" && resourceType == "nodes" && uuid == "" && action == "" {
272 "kind": "arvados#nodeList",
274 "uuid": "zzzzz-7ekkf-2z3mc76g2q73aio",
275 "hostname": "compute2",
276 "properties": {"total_cpu_cores": 16}
278 } else if method == "GET" && resourceType == "containers" && action == "" && !client.callraw {
280 j, err = json.Marshal(map[string]interface{}{
281 "items": []interface{}{client.Container},
282 "kind": "arvados#nodeList",
285 j, err = json.Marshal(client.Container)
289 "command": ["sleep", "1"],
290 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
293 "mounts": {"/tmp": {"kind": "tmp"}, "/json": {"kind": "json", "content": {"number": 123456789123456789}}},
294 "output_path": "/tmp",
296 "runtime_constraints": {}
299 return ioutil.NopCloser(bytes.NewReader(j)), err
302 func (client *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
303 if resourceType == "collections" {
305 output.(*arvados.Collection).ManifestText = hwManifest
306 } else if uuid == otherPDH {
307 output.(*arvados.Collection).ManifestText = otherManifest
308 } else if uuid == normalizedWithSubdirsPDH {
309 output.(*arvados.Collection).ManifestText = normalizedManifestWithSubdirs
310 } else if uuid == denormalizedWithSubdirsPDH {
311 output.(*arvados.Collection).ManifestText = denormalizedManifestWithSubdirs
314 if resourceType == "containers" {
315 (*output.(*arvados.Container)) = client.Container
320 func (client *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
322 defer client.Mutex.Unlock()
324 client.Content = append(client.Content, parameters)
325 if resourceType == "containers" {
326 if parameters["container"].(arvadosclient.Dict)["state"] == "Running" {
327 client.WasSetRunning = true
329 } else if resourceType == "collections" {
330 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
331 output.(*arvados.Collection).UUID = uuid
332 output.(*arvados.Collection).PortableDataHash = fmt.Sprintf("%x", md5.Sum([]byte(mt)))
337 var discoveryMap = map[string]interface{}{
338 "defaultTrashLifetime": float64(1209600),
339 "crunchLimitLogBytesPerJob": float64(67108864),
340 "crunchLogThrottleBytes": float64(65536),
341 "crunchLogThrottlePeriod": float64(60),
342 "crunchLogThrottleLines": float64(1024),
343 "crunchLogPartialLineThrottlePeriod": float64(5),
344 "crunchLogBytesPerEvent": float64(4096),
345 "crunchLogSecondsBetweenEvents": float64(1),
348 func (client *ArvTestClient) Discovery(key string) (interface{}, error) {
349 return discoveryMap[key], nil
352 // CalledWith returns the parameters from the first API call whose
353 // parameters match jpath/string. E.g., CalledWith(c, "foo.bar",
354 // "baz") returns parameters with parameters["foo"]["bar"]=="baz". If
355 // no call matches, it returns nil.
356 func (client *ArvTestClient) CalledWith(jpath string, expect interface{}) arvadosclient.Dict {
358 for _, content := range client.Content {
359 var v interface{} = content
360 for _, k := range strings.Split(jpath, ".") {
361 if dict, ok := v.(arvadosclient.Dict); !ok {
374 func (client *KeepTestClient) LocalLocator(locator string) (string, error) {
378 func (client *KeepTestClient) PutB(buf []byte) (string, int, error) {
380 return fmt.Sprintf("%x+%d", md5.Sum(buf), len(buf)), len(buf), nil
383 func (client *KeepTestClient) ReadAt(string, []byte, int) (int, error) {
384 return 0, errors.New("not implemented")
387 func (client *KeepTestClient) ClearBlockCache() {
390 func (client *KeepTestClient) Close() {
394 type FileWrapper struct {
399 func (fw FileWrapper) Readdir(n int) ([]os.FileInfo, error) {
400 return nil, errors.New("not implemented")
403 func (fw FileWrapper) Seek(int64, int) (int64, error) {
404 return 0, errors.New("not implemented")
407 func (fw FileWrapper) Size() int64 {
411 func (fw FileWrapper) Stat() (os.FileInfo, error) {
412 return nil, errors.New("not implemented")
415 func (fw FileWrapper) Truncate(int64) error {
416 return errors.New("not implemented")
419 func (fw FileWrapper) Write([]byte) (int, error) {
420 return 0, errors.New("not implemented")
423 func (fw FileWrapper) Sync() error {
424 return errors.New("not implemented")
427 func (client *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
428 if filename == hwImageID+".tar" {
429 rdr := ioutil.NopCloser(&bytes.Buffer{})
431 return FileWrapper{rdr, 1321984}, nil
432 } else if filename == "/file1_in_main.txt" {
433 rdr := ioutil.NopCloser(strings.NewReader("foo"))
435 return FileWrapper{rdr, 3}, nil
440 func (s *TestSuite) TestLoadImage(c *C) {
441 cr, err := NewContainerRunner(s.client, &ArvTestClient{},
442 &KeepTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
445 kc := &KeepTestClient{}
447 cr.ContainerArvClient = &ArvTestClient{}
448 cr.ContainerKeepClient = kc
450 _, err = cr.Docker.ImageRemove(nil, hwImageID, dockertypes.ImageRemoveOptions{})
453 _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageID)
456 cr.Container.ContainerImage = hwPDH
458 // (1) Test loading image from keep
459 c.Check(kc.Called, Equals, false)
460 c.Check(cr.ContainerConfig.Image, Equals, "")
466 cr.Docker.ImageRemove(nil, hwImageID, dockertypes.ImageRemoveOptions{})
469 c.Check(kc.Called, Equals, true)
470 c.Check(cr.ContainerConfig.Image, Equals, hwImageID)
472 _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageID)
475 // (2) Test using image that's already loaded
477 cr.ContainerConfig.Image = ""
481 c.Check(kc.Called, Equals, false)
482 c.Check(cr.ContainerConfig.Image, Equals, hwImageID)
486 type ArvErrorTestClient struct{}
488 func (ArvErrorTestClient) Create(resourceType string,
489 parameters arvadosclient.Dict,
490 output interface{}) error {
494 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
495 if method == "GET" && resourceType == "containers" && action == "auth" {
498 return errors.New("ArvError")
501 func (ArvErrorTestClient) CallRaw(method, resourceType, uuid, action string,
502 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
503 return nil, errors.New("ArvError")
506 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
507 return errors.New("ArvError")
510 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
514 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
515 return discoveryMap[key], nil
518 type KeepErrorTestClient struct {
522 func (*KeepErrorTestClient) ManifestFileReader(manifest.Manifest, string) (arvados.File, error) {
523 return nil, errors.New("KeepError")
526 func (*KeepErrorTestClient) PutB(buf []byte) (string, int, error) {
527 return "", 0, errors.New("KeepError")
530 func (*KeepErrorTestClient) LocalLocator(string) (string, error) {
531 return "", errors.New("KeepError")
534 type KeepReadErrorTestClient struct {
538 func (*KeepReadErrorTestClient) ReadAt(string, []byte, int) (int, error) {
539 return 0, errors.New("KeepError")
542 type ErrorReader struct {
546 func (ErrorReader) Read(p []byte) (n int, err error) {
547 return 0, errors.New("ErrorReader")
550 func (ErrorReader) Seek(int64, int) (int64, error) {
551 return 0, errors.New("ErrorReader")
554 func (KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
555 return ErrorReader{}, nil
558 func (s *TestSuite) TestLoadImageArvError(c *C) {
560 kc := &KeepTestClient{}
562 cr, err := NewContainerRunner(s.client, &ArvErrorTestClient{}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
565 cr.ContainerArvClient = &ArvErrorTestClient{}
566 cr.ContainerKeepClient = &KeepTestClient{}
568 cr.Container.ContainerImage = hwPDH
571 c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
574 func (s *TestSuite) TestLoadImageKeepError(c *C) {
576 kc := &KeepErrorTestClient{}
577 cr, err := NewContainerRunner(s.client, &ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
580 cr.ContainerArvClient = &ArvTestClient{}
581 cr.ContainerKeepClient = &KeepErrorTestClient{}
583 cr.Container.ContainerImage = hwPDH
586 c.Assert(err, NotNil)
587 c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
590 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
591 // (3) Collection doesn't contain image
592 kc := &KeepReadErrorTestClient{}
593 cr, err := NewContainerRunner(s.client, &ArvTestClient{}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
595 cr.Container.ContainerImage = otherPDH
597 cr.ContainerArvClient = &ArvTestClient{}
598 cr.ContainerKeepClient = &KeepReadErrorTestClient{}
601 c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
604 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
605 // (4) Collection doesn't contain image
606 kc := &KeepReadErrorTestClient{}
607 cr, err := NewContainerRunner(s.client, &ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
609 cr.Container.ContainerImage = hwPDH
610 cr.ContainerArvClient = &ArvTestClient{}
611 cr.ContainerKeepClient = &KeepReadErrorTestClient{}
617 type ClosableBuffer struct {
621 func (*ClosableBuffer) Close() error {
625 type TestLogs struct {
626 Stdout ClosableBuffer
627 Stderr ClosableBuffer
630 func (tl *TestLogs) NewTestLoggingWriter(logstr string) (io.WriteCloser, error) {
631 if logstr == "stdout" {
632 return &tl.Stdout, nil
634 if logstr == "stderr" {
635 return &tl.Stderr, nil
637 return nil, errors.New("???")
640 func dockerLog(fd byte, msg string) []byte {
642 header := make([]byte, 8+len(by))
644 header[7] = byte(len(by))
649 func (s *TestSuite) TestRunContainer(c *C) {
650 s.docker.fn = func(t *TestDockerClient) {
651 t.logWriter.Write(dockerLog(1, "Hello world\n"))
654 kc := &KeepTestClient{}
656 cr, err := NewContainerRunner(s.client, &ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
659 cr.ContainerArvClient = &ArvTestClient{}
660 cr.ContainerKeepClient = &KeepTestClient{}
663 cr.NewLogWriter = logs.NewTestLoggingWriter
664 cr.Container.ContainerImage = hwPDH
665 cr.Container.Command = []string{"./hw"}
669 err = cr.CreateContainer()
672 err = cr.StartContainer()
675 err = cr.WaitFinish()
678 c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
679 c.Check(logs.Stderr.String(), Equals, "")
682 func (s *TestSuite) TestCommitLogs(c *C) {
683 api := &ArvTestClient{}
684 kc := &KeepTestClient{}
686 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
688 cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
690 cr.CrunchLog.Print("Hello world!")
691 cr.CrunchLog.Print("Goodbye")
692 cr.finalState = "Complete"
694 err = cr.CommitLogs()
697 c.Check(api.Calls, Equals, 2)
698 c.Check(api.Content[1]["ensure_unique_name"], Equals, true)
699 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
700 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
701 c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
704 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
705 api := &ArvTestClient{}
706 kc := &KeepTestClient{}
708 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
711 err = cr.UpdateContainerRunning()
714 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
717 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
718 api := &ArvTestClient{}
719 kc := &KeepTestClient{}
721 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
724 cr.LogsPDH = new(string)
725 *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
727 cr.ExitCode = new(int)
729 cr.finalState = "Complete"
731 err = cr.UpdateContainerFinal()
734 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
735 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
736 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
739 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
740 api := &ArvTestClient{}
741 kc := &KeepTestClient{}
743 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
746 cr.finalState = "Cancelled"
748 err = cr.UpdateContainerFinal()
751 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
752 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
753 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
756 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
757 // dress rehearsal of the Run() function, starting from a JSON container record.
758 func (s *TestSuite) fullRunHelper(c *C, record string, extraMounts []string, exitCode int, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, realTemp string) {
759 rec := arvados.Container{}
760 err := json.Unmarshal([]byte(record), &rec)
764 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
766 err = json.Unmarshal([]byte(record), &sm)
768 secretMounts, err := json.Marshal(sm)
769 c.Logf("%s %q", sm, secretMounts)
772 s.docker.exitCode = exitCode
774 s.docker.ImageRemove(nil, hwImageID, dockertypes.ImageRemoveOptions{})
776 api = &ArvTestClient{Container: rec}
778 kc := &KeepTestClient{}
780 cr, err = NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
783 cr.statInterval = 100 * time.Millisecond
784 cr.containerWatchdogInterval = time.Second
785 am := &ArvMountCmdLine{}
786 cr.RunArvMount = am.ArvMountTest
788 realTemp, err = ioutil.TempDir("", "crunchrun_test1-")
790 defer os.RemoveAll(realTemp)
792 s.docker.realTemp = realTemp
795 cr.MkTempDir = func(_ string, prefix string) (string, error) {
797 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, tempcount)
798 err := os.Mkdir(d, os.ModePerm)
799 if err != nil && strings.Contains(err.Error(), ": file exists") {
800 // Test case must have pre-populated the tempdir
805 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
806 return &ArvTestClient{secretMounts: secretMounts}, &KeepTestClient{}, nil, nil
809 if extraMounts != nil && len(extraMounts) > 0 {
810 err := cr.SetupArvMountPoint("keep")
813 for _, m := range extraMounts {
814 os.MkdirAll(cr.ArvMountPoint+"/by_id/"+m, os.ModePerm)
819 if api.CalledWith("container.state", "Complete") != nil {
823 c.Check(api.WasSetRunning, Equals, true)
824 var lastupdate arvadosclient.Dict
825 for _, content := range api.Content {
826 if content["container"] != nil {
827 lastupdate = content["container"].(arvadosclient.Dict)
830 if lastupdate["log"] == nil {
831 c.Errorf("no container update with non-nil log -- updates were: %v", api.Content)
836 for k, v := range api.Logs {
845 func (s *TestSuite) TestFullRunHello(c *C) {
846 api, _, _ := s.fullRunHelper(c, `{
847 "command": ["echo", "hello world"],
848 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
851 "mounts": {"/tmp": {"kind": "tmp"} },
852 "output_path": "/tmp",
854 "runtime_constraints": {},
856 }`, nil, 0, func(t *TestDockerClient) {
857 t.logWriter.Write(dockerLog(1, "hello world\n"))
861 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
862 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
863 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
867 func (s *TestSuite) TestRunAlreadyRunning(c *C) {
869 api, _, _ := s.fullRunHelper(c, `{
870 "command": ["sleep", "3"],
871 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
874 "mounts": {"/tmp": {"kind": "tmp"} },
875 "output_path": "/tmp",
877 "runtime_constraints": {},
878 "scheduling_parameters":{"max_run_time": 1},
880 }`, nil, 2, func(t *TestDockerClient) {
884 c.Check(api.CalledWith("container.state", "Cancelled"), IsNil)
885 c.Check(api.CalledWith("container.state", "Complete"), IsNil)
886 c.Check(ran, Equals, false)
889 func (s *TestSuite) TestRunTimeExceeded(c *C) {
890 api, _, _ := s.fullRunHelper(c, `{
891 "command": ["sleep", "3"],
892 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
895 "mounts": {"/tmp": {"kind": "tmp"} },
896 "output_path": "/tmp",
898 "runtime_constraints": {},
899 "scheduling_parameters":{"max_run_time": 1},
901 }`, nil, 0, func(t *TestDockerClient) {
902 time.Sleep(3 * time.Second)
906 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
907 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*maximum run time exceeded.*")
910 func (s *TestSuite) TestContainerWaitFails(c *C) {
911 api, _, _ := s.fullRunHelper(c, `{
912 "command": ["sleep", "3"],
913 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
915 "mounts": {"/tmp": {"kind": "tmp"} },
916 "output_path": "/tmp",
919 }`, nil, 0, func(t *TestDockerClient) {
921 time.Sleep(10 * time.Second)
925 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
926 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Container is not running.*")
929 func (s *TestSuite) TestCrunchstat(c *C) {
930 api, _, _ := s.fullRunHelper(c, `{
931 "command": ["sleep", "1"],
932 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
935 "mounts": {"/tmp": {"kind": "tmp"} },
936 "output_path": "/tmp",
938 "runtime_constraints": {},
940 }`, nil, 0, func(t *TestDockerClient) {
941 time.Sleep(time.Second)
945 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
946 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
948 // We didn't actually start a container, so crunchstat didn't
949 // find accounting files and therefore didn't log any stats.
950 // It should have logged a "can't find accounting files"
951 // message after one poll interval, though, so we can confirm
953 c.Assert(api.Logs["crunchstat"], NotNil)
954 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
956 // The "files never appeared" log assures us that we called
957 // (*crunchstat.Reporter)Stop(), and that we set it up with
958 // the correct container ID "abcde":
959 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files never appeared for abcde\n`)
962 func (s *TestSuite) TestNodeInfoLog(c *C) {
963 os.Setenv("SLURMD_NODENAME", "compute2")
964 api, _, _ := s.fullRunHelper(c, `{
965 "command": ["sleep", "1"],
966 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
969 "mounts": {"/tmp": {"kind": "tmp"} },
970 "output_path": "/tmp",
972 "runtime_constraints": {},
975 func(t *TestDockerClient) {
976 time.Sleep(time.Second)
980 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
981 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
983 c.Assert(api.Logs["node"], NotNil)
984 json := api.Logs["node"].String()
985 c.Check(json, Matches, `(?ms).*"uuid": *"zzzzz-7ekkf-2z3mc76g2q73aio".*`)
986 c.Check(json, Matches, `(?ms).*"total_cpu_cores": *16.*`)
987 c.Check(json, Not(Matches), `(?ms).*"info":.*`)
989 c.Assert(api.Logs["node-info"], NotNil)
990 json = api.Logs["node-info"].String()
991 c.Check(json, Matches, `(?ms).*Host Information.*`)
992 c.Check(json, Matches, `(?ms).*CPU Information.*`)
993 c.Check(json, Matches, `(?ms).*Memory Information.*`)
994 c.Check(json, Matches, `(?ms).*Disk Space.*`)
995 c.Check(json, Matches, `(?ms).*Disk INodes.*`)
998 func (s *TestSuite) TestContainerRecordLog(c *C) {
999 api, _, _ := s.fullRunHelper(c, `{
1000 "command": ["sleep", "1"],
1001 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1004 "mounts": {"/tmp": {"kind": "tmp"} },
1005 "output_path": "/tmp",
1007 "runtime_constraints": {},
1010 func(t *TestDockerClient) {
1011 time.Sleep(time.Second)
1015 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1016 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1018 c.Assert(api.Logs["container"], NotNil)
1019 c.Check(api.Logs["container"].String(), Matches, `(?ms).*container_image.*`)
1022 func (s *TestSuite) TestFullRunStderr(c *C) {
1023 api, _, _ := s.fullRunHelper(c, `{
1024 "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
1025 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1028 "mounts": {"/tmp": {"kind": "tmp"} },
1029 "output_path": "/tmp",
1031 "runtime_constraints": {},
1033 }`, nil, 1, func(t *TestDockerClient) {
1034 t.logWriter.Write(dockerLog(1, "hello\n"))
1035 t.logWriter.Write(dockerLog(2, "world\n"))
1039 final := api.CalledWith("container.state", "Complete")
1040 c.Assert(final, NotNil)
1041 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1042 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1044 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
1045 c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
1048 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
1049 api, _, _ := s.fullRunHelper(c, `{
1051 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1054 "mounts": {"/tmp": {"kind": "tmp"} },
1055 "output_path": "/tmp",
1057 "runtime_constraints": {},
1059 }`, nil, 0, func(t *TestDockerClient) {
1060 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
1064 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1065 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1066 c.Log(api.Logs["stdout"])
1067 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
1070 func (s *TestSuite) TestFullRunSetCwd(c *C) {
1071 api, _, _ := s.fullRunHelper(c, `{
1073 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1076 "mounts": {"/tmp": {"kind": "tmp"} },
1077 "output_path": "/tmp",
1079 "runtime_constraints": {},
1081 }`, nil, 0, func(t *TestDockerClient) {
1082 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
1086 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1087 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1088 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
1091 func (s *TestSuite) TestStopOnSignal(c *C) {
1092 s.testStopContainer(c, func(cr *ContainerRunner) {
1094 for !s.docker.calledWait {
1095 time.Sleep(time.Millisecond)
1097 cr.SigChan <- syscall.SIGINT
1102 func (s *TestSuite) TestStopOnArvMountDeath(c *C) {
1103 s.testStopContainer(c, func(cr *ContainerRunner) {
1104 cr.ArvMountExit = make(chan error)
1106 cr.ArvMountExit <- exec.Command("true").Run()
1107 close(cr.ArvMountExit)
1112 func (s *TestSuite) testStopContainer(c *C, setup func(cr *ContainerRunner)) {
1114 "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
1115 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1118 "mounts": {"/tmp": {"kind": "tmp"} },
1119 "output_path": "/tmp",
1121 "runtime_constraints": {},
1125 rec := arvados.Container{}
1126 err := json.Unmarshal([]byte(record), &rec)
1129 s.docker.fn = func(t *TestDockerClient) {
1131 t.logWriter.Write(dockerLog(1, "foo\n"))
1134 s.docker.ImageRemove(nil, hwImageID, dockertypes.ImageRemoveOptions{})
1136 api := &ArvTestClient{Container: rec}
1137 kc := &KeepTestClient{}
1139 cr, err := NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1140 c.Assert(err, IsNil)
1141 cr.RunArvMount = func([]string, string) (*exec.Cmd, error) { return nil, nil }
1142 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1143 return &ArvTestClient{}, &KeepTestClient{}, nil, nil
1147 done := make(chan error)
1152 case <-time.After(20 * time.Second):
1153 pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
1154 c.Fatal("timed out")
1158 for k, v := range api.Logs {
1163 c.Check(api.CalledWith("container.log", nil), NotNil)
1164 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1165 c.Check(api.Logs["stdout"].String(), Matches, "(?ms).*foo\n$")
1168 func (s *TestSuite) TestFullRunSetEnv(c *C) {
1169 api, _, _ := s.fullRunHelper(c, `{
1170 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1171 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1173 "environment": {"FROBIZ": "bilbo"},
1174 "mounts": {"/tmp": {"kind": "tmp"} },
1175 "output_path": "/tmp",
1177 "runtime_constraints": {},
1179 }`, nil, 0, func(t *TestDockerClient) {
1180 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1184 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1185 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1186 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)
1189 type ArvMountCmdLine struct {
1194 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
1200 func stubCert(temp string) string {
1201 path := temp + "/ca-certificates.crt"
1202 crt, _ := os.Create(path)
1204 arvadosclient.CertFiles = []string{path}
1208 func (s *TestSuite) TestSetupMounts(c *C) {
1209 api := &ArvTestClient{}
1210 kc := &KeepTestClient{}
1212 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1213 c.Assert(err, IsNil)
1214 am := &ArvMountCmdLine{}
1215 cr.RunArvMount = am.ArvMountTest
1216 cr.ContainerArvClient = &ArvTestClient{}
1217 cr.ContainerKeepClient = &KeepTestClient{}
1219 realTemp, err := ioutil.TempDir("", "crunchrun_test1-")
1220 c.Assert(err, IsNil)
1221 certTemp, err := ioutil.TempDir("", "crunchrun_test2-")
1222 c.Assert(err, IsNil)
1223 stubCertPath := stubCert(certTemp)
1225 cr.parentTemp = realTemp
1227 defer os.RemoveAll(realTemp)
1228 defer os.RemoveAll(certTemp)
1231 cr.MkTempDir = func(_ string, prefix string) (string, error) {
1233 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
1234 err := os.Mkdir(d, os.ModePerm)
1235 if err != nil && strings.Contains(err.Error(), ": file exists") {
1236 // Test case must have pre-populated the tempdir
1242 checkEmpty := func() {
1243 // Should be deleted.
1244 _, err := os.Stat(realTemp)
1245 c.Assert(os.IsNotExist(err), Equals, true)
1247 // Now recreate it for the next test.
1248 c.Assert(os.Mkdir(realTemp, 0777), IsNil)
1253 cr.ArvMountPoint = ""
1254 cr.Container.Mounts = make(map[string]arvados.Mount)
1255 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1256 cr.Container.OutputPath = "/tmp"
1257 cr.statInterval = 5 * time.Second
1258 err := cr.SetupMounts()
1260 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1261 "--read-write", "--crunchstat-interval=5",
1262 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1263 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp"})
1264 os.RemoveAll(cr.ArvMountPoint)
1271 cr.ArvMountPoint = ""
1272 cr.Container.Mounts = make(map[string]arvados.Mount)
1273 cr.Container.Mounts["/out"] = arvados.Mount{Kind: "tmp"}
1274 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1275 cr.Container.OutputPath = "/out"
1277 err := cr.SetupMounts()
1279 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1280 "--read-write", "--crunchstat-interval=5",
1281 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1282 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/out", realTemp + "/tmp3:/tmp"})
1283 os.RemoveAll(cr.ArvMountPoint)
1290 cr.ArvMountPoint = ""
1291 cr.Container.Mounts = make(map[string]arvados.Mount)
1292 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1293 cr.Container.OutputPath = "/tmp"
1294 cr.Container.RuntimeConstraints.API = true
1296 err := cr.SetupMounts()
1298 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1299 "--read-write", "--crunchstat-interval=5",
1300 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1301 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", stubCertPath + ":/etc/arvados/ca-certificates.crt:ro"})
1302 os.RemoveAll(cr.ArvMountPoint)
1306 cr.Container.RuntimeConstraints.API = false
1311 cr.ArvMountPoint = ""
1312 cr.Container.Mounts = map[string]arvados.Mount{
1313 "/keeptmp": {Kind: "collection", Writable: true},
1315 cr.Container.OutputPath = "/keeptmp"
1317 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1319 err := cr.SetupMounts()
1321 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1322 "--read-write", "--crunchstat-interval=5",
1323 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1324 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/tmp0:/keeptmp"})
1325 os.RemoveAll(cr.ArvMountPoint)
1332 cr.ArvMountPoint = ""
1333 cr.Container.Mounts = map[string]arvados.Mount{
1334 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1335 "/keepout": {Kind: "collection", Writable: true},
1337 cr.Container.OutputPath = "/keepout"
1339 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1340 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1342 err := cr.SetupMounts()
1344 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1345 "--read-write", "--crunchstat-interval=5",
1346 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1347 sort.StringSlice(cr.Binds).Sort()
1348 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1349 realTemp + "/keep1/tmp0:/keepout"})
1350 os.RemoveAll(cr.ArvMountPoint)
1357 cr.ArvMountPoint = ""
1358 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
1359 cr.Container.Mounts = map[string]arvados.Mount{
1360 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1361 "/keepout": {Kind: "collection", Writable: true},
1363 cr.Container.OutputPath = "/keepout"
1365 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1366 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1368 err := cr.SetupMounts()
1370 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1371 "--read-write", "--crunchstat-interval=5",
1372 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1373 sort.StringSlice(cr.Binds).Sort()
1374 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1375 realTemp + "/keep1/tmp0:/keepout"})
1376 os.RemoveAll(cr.ArvMountPoint)
1381 for _, test := range []struct {
1385 {in: "foo", out: `"foo"`},
1386 {in: nil, out: `null`},
1387 {in: map[string]int64{"foo": 123456789123456789}, out: `{"foo":123456789123456789}`},
1390 cr.ArvMountPoint = ""
1391 cr.Container.Mounts = map[string]arvados.Mount{
1392 "/mnt/test.json": {Kind: "json", Content: test.in},
1394 err := cr.SetupMounts()
1396 sort.StringSlice(cr.Binds).Sort()
1397 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/json2/mountdata.json:/mnt/test.json:ro"})
1398 content, err := ioutil.ReadFile(realTemp + "/json2/mountdata.json")
1400 c.Check(content, DeepEquals, []byte(test.out))
1401 os.RemoveAll(cr.ArvMountPoint)
1406 for _, test := range []struct {
1410 {in: "foo", out: `foo`},
1411 {in: nil, out: "error"},
1412 {in: map[string]int64{"foo": 123456789123456789}, out: "error"},
1415 cr.ArvMountPoint = ""
1416 cr.Container.Mounts = map[string]arvados.Mount{
1417 "/mnt/test.txt": {Kind: "text", Content: test.in},
1419 err := cr.SetupMounts()
1420 if test.out == "error" {
1421 c.Check(err.Error(), Equals, "content for mount \"/mnt/test.txt\" must be a string")
1424 sort.StringSlice(cr.Binds).Sort()
1425 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/text2/mountdata.text:/mnt/test.txt:ro"})
1426 content, err := ioutil.ReadFile(realTemp + "/text2/mountdata.text")
1428 c.Check(content, DeepEquals, []byte(test.out))
1430 os.RemoveAll(cr.ArvMountPoint)
1435 // Read-only mount points are allowed underneath output_dir mount point
1438 cr.ArvMountPoint = ""
1439 cr.Container.Mounts = make(map[string]arvados.Mount)
1440 cr.Container.Mounts = map[string]arvados.Mount{
1441 "/tmp": {Kind: "tmp"},
1442 "/tmp/foo": {Kind: "collection"},
1444 cr.Container.OutputPath = "/tmp"
1446 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1448 err := cr.SetupMounts()
1450 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1451 "--read-write", "--crunchstat-interval=5",
1452 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1453 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", realTemp + "/keep1/tmp0:/tmp/foo:ro"})
1454 os.RemoveAll(cr.ArvMountPoint)
1459 // Writable mount points copied to output_dir mount point
1462 cr.ArvMountPoint = ""
1463 cr.Container.Mounts = make(map[string]arvados.Mount)
1464 cr.Container.Mounts = map[string]arvados.Mount{
1465 "/tmp": {Kind: "tmp"},
1466 "/tmp/foo": {Kind: "collection",
1467 PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53",
1469 "/tmp/bar": {Kind: "collection",
1470 PortableDataHash: "59389a8f9ee9d399be35462a0f92541d+53",
1474 cr.Container.OutputPath = "/tmp"
1476 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1477 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz", os.ModePerm)
1479 rf, _ := os.Create(realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz/quux")
1480 rf.Write([]byte("bar"))
1483 err := cr.SetupMounts()
1485 _, err = os.Stat(cr.HostOutputDir + "/foo")
1487 _, err = os.Stat(cr.HostOutputDir + "/bar/quux")
1489 os.RemoveAll(cr.ArvMountPoint)
1494 // Only mount points of kind 'collection' are allowed underneath output_dir mount point
1497 cr.ArvMountPoint = ""
1498 cr.Container.Mounts = make(map[string]arvados.Mount)
1499 cr.Container.Mounts = map[string]arvados.Mount{
1500 "/tmp": {Kind: "tmp"},
1501 "/tmp/foo": {Kind: "tmp"},
1503 cr.Container.OutputPath = "/tmp"
1505 err := cr.SetupMounts()
1506 c.Check(err, NotNil)
1507 c.Check(err, ErrorMatches, `only mount points of kind 'collection', 'text' or 'json' are supported underneath the output_path.*`)
1508 os.RemoveAll(cr.ArvMountPoint)
1513 // Only mount point of kind 'collection' is allowed for stdin
1516 cr.ArvMountPoint = ""
1517 cr.Container.Mounts = make(map[string]arvados.Mount)
1518 cr.Container.Mounts = map[string]arvados.Mount{
1519 "stdin": {Kind: "tmp"},
1522 err := cr.SetupMounts()
1523 c.Check(err, NotNil)
1524 c.Check(err, ErrorMatches, `unsupported mount kind 'tmp' for stdin.*`)
1525 os.RemoveAll(cr.ArvMountPoint)
1533 cr.ArvMountPoint = ""
1534 (*GitMountSuite)(nil).useTestGitServer(c)
1535 cr.token = arvadostest.ActiveToken
1536 cr.Container.Mounts = make(map[string]arvados.Mount)
1537 cr.Container.Mounts = map[string]arvados.Mount{
1540 UUID: arvadostest.Repository2UUID,
1541 Commit: "fd3531f42995344f36c30b79f55f27b502f3d344",
1546 UUID: arvadostest.Repository2UUID,
1547 Commit: "5ebfab0522851df01fec11ec55a6d0f4877b542e",
1551 cr.Container.OutputPath = "/tmp"
1553 err := cr.SetupMounts()
1556 // dirMap[mountpoint] == tmpdir
1557 dirMap := make(map[string]string)
1558 for _, bind := range cr.Binds {
1559 tokens := strings.Split(bind, ":")
1560 dirMap[tokens[1]] = tokens[0]
1562 if cr.Container.Mounts[tokens[1]].Writable {
1563 c.Check(len(tokens), Equals, 2)
1565 c.Check(len(tokens), Equals, 3)
1566 c.Check(tokens[2], Equals, "ro")
1570 data, err := ioutil.ReadFile(dirMap["/tip"] + "/dir1/dir2/file with mode 0644")
1572 c.Check(string(data), Equals, "\000\001\002\003")
1573 _, err = ioutil.ReadFile(dirMap["/tip"] + "/file only on testbranch")
1574 c.Check(err, FitsTypeOf, &os.PathError{})
1575 c.Check(os.IsNotExist(err), Equals, true)
1577 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/dir1/dir2/file with mode 0644")
1579 c.Check(string(data), Equals, "\000\001\002\003")
1580 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/file only on testbranch")
1582 c.Check(string(data), Equals, "testfile\n")
1589 func (s *TestSuite) TestStdout(c *C) {
1591 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1592 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1594 "environment": {"FROBIZ": "bilbo"},
1595 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1596 "output_path": "/tmp",
1598 "runtime_constraints": {},
1602 api, cr, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1603 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1607 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1608 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1609 c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1612 // Used by the TestStdoutWithWrongPath*()
1613 func (s *TestSuite) stdoutErrorRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, err error) {
1614 rec := arvados.Container{}
1615 err = json.Unmarshal([]byte(record), &rec)
1619 s.docker.ImageRemove(nil, hwImageID, dockertypes.ImageRemoveOptions{})
1621 api = &ArvTestClient{Container: rec}
1622 kc := &KeepTestClient{}
1624 cr, err = NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1625 c.Assert(err, IsNil)
1626 am := &ArvMountCmdLine{}
1627 cr.RunArvMount = am.ArvMountTest
1628 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1629 return &ArvTestClient{}, &KeepTestClient{}, nil, nil
1636 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1637 _, _, err := s.stdoutErrorRunHelper(c, `{
1638 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1639 "output_path": "/tmp",
1641 }`, func(t *TestDockerClient) {})
1643 c.Check(err, NotNil)
1644 c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
1647 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1648 _, _, err := s.stdoutErrorRunHelper(c, `{
1649 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1650 "output_path": "/tmp",
1652 }`, func(t *TestDockerClient) {})
1654 c.Check(err, NotNil)
1655 c.Check(strings.Contains(err.Error(), "unsupported mount kind 'tmp' for stdout"), Equals, true)
1658 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1659 _, _, err := s.stdoutErrorRunHelper(c, `{
1660 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1661 "output_path": "/tmp",
1663 }`, func(t *TestDockerClient) {})
1665 c.Check(err, NotNil)
1666 c.Check(strings.Contains(err.Error(), "unsupported mount kind 'collection' for stdout"), Equals, true)
1669 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1670 defer os.Setenv("ARVADOS_API_HOST", os.Getenv("ARVADOS_API_HOST"))
1671 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1672 api, _, _ := s.fullRunHelper(c, `{
1673 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1674 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1677 "mounts": {"/tmp": {"kind": "tmp"} },
1678 "output_path": "/tmp",
1680 "runtime_constraints": {"API": true},
1682 }`, nil, 0, func(t *TestDockerClient) {
1683 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
1687 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1688 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1689 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "test.arvados.org\n"), Equals, true)
1690 c.Check(api.CalledWith("container.output", "d41d8cd98f00b204e9800998ecf8427e+0"), NotNil)
1693 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1694 defer os.Setenv("ARVADOS_API_HOST", os.Getenv("ARVADOS_API_HOST"))
1695 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1696 api, _, _ := s.fullRunHelper(c, `{
1697 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1698 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1701 "mounts": {"/tmp": {"kind": "tmp"} },
1702 "output_path": "/tmp",
1704 "runtime_constraints": {"API": true},
1706 }`, nil, 0, func(t *TestDockerClient) {
1707 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
1711 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1712 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1713 c.Check(api.CalledWith("container.output", "d4ab34d3d4f8a72f5c4973051ae69fab+122"), NotNil)
1716 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1718 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1719 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1721 "environment": {"FROBIZ": "bilbo"},
1723 "/tmp": {"kind": "tmp"},
1724 "/tmp/foo": {"kind": "collection",
1725 "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1726 "exclude_from_output": true
1728 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1730 "output_path": "/tmp",
1732 "runtime_constraints": {},
1736 extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1738 api, cr, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1739 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1743 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1744 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1745 c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1748 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1750 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1751 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1753 "environment": {"FROBIZ": "bilbo"},
1755 "/tmp": {"kind": "tmp"},
1756 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1757 "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1758 "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1759 "/tmp/foo/baz/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1760 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1762 "output_path": "/tmp",
1764 "runtime_constraints": {},
1768 extraMounts := []string{
1769 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1770 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1771 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1774 api, runner, realtemp := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1775 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1779 c.Check(runner.Binds, DeepEquals, []string{realtemp + "/tmp2:/tmp",
1780 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt:/tmp/foo/bar:ro",
1781 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt:/tmp/foo/baz/sub2file2:ro",
1782 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1:/tmp/foo/sub1:ro",
1783 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt:/tmp/foo/sub1file2:ro",
1786 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1787 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1788 for _, v := range api.Content {
1789 if v["collection"] != nil {
1790 c.Check(v["ensure_unique_name"], Equals, true)
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 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:bar 36:18:sub1file2
1797 ./foo/baz 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2
1798 ./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1799 ./foo/sub1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1806 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
1808 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1809 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1811 "environment": {"FROBIZ": "bilbo"},
1813 "/tmp": {"kind": "tmp"},
1814 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/subdir1/file2_in_subdir1.txt"},
1815 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1817 "output_path": "/tmp",
1819 "runtime_constraints": {},
1823 extraMounts := []string{
1824 "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1827 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1828 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1832 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1833 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1834 for _, v := range api.Content {
1835 if v["collection"] != nil {
1836 collection := v["collection"].(arvadosclient.Dict)
1837 if strings.Index(collection["name"].(string), "output") == 0 {
1838 manifest := collection["manifest_text"].(string)
1840 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1841 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 10:17:bar
1848 func (s *TestSuite) TestOutputError(c *C) {
1850 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1851 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1853 "environment": {"FROBIZ": "bilbo"},
1855 "/tmp": {"kind": "tmp"}
1857 "output_path": "/tmp",
1859 "runtime_constraints": {},
1863 extraMounts := []string{}
1865 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1866 os.Symlink("/etc/hosts", t.realTemp+"/tmp2/baz")
1870 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1873 func (s *TestSuite) TestStdinCollectionMountPoint(c *C) {
1875 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1876 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1878 "environment": {"FROBIZ": "bilbo"},
1880 "/tmp": {"kind": "tmp"},
1881 "stdin": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/file1_in_main.txt"},
1882 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1884 "output_path": "/tmp",
1886 "runtime_constraints": {},
1890 extraMounts := []string{
1891 "b0def87f80dd594d4675809e83bd4f15+367/file1_in_main.txt",
1894 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1895 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1899 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1900 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1901 for _, v := range api.Content {
1902 if v["collection"] != nil {
1903 collection := v["collection"].(arvadosclient.Dict)
1904 if strings.Index(collection["name"].(string), "output") == 0 {
1905 manifest := collection["manifest_text"].(string)
1906 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1913 func (s *TestSuite) TestStdinJsonMountPoint(c *C) {
1915 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1916 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1918 "environment": {"FROBIZ": "bilbo"},
1920 "/tmp": {"kind": "tmp"},
1921 "stdin": {"kind": "json", "content": "foo"},
1922 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1924 "output_path": "/tmp",
1926 "runtime_constraints": {},
1930 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1931 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1935 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1936 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1937 for _, v := range api.Content {
1938 if v["collection"] != nil {
1939 collection := v["collection"].(arvadosclient.Dict)
1940 if strings.Index(collection["name"].(string), "output") == 0 {
1941 manifest := collection["manifest_text"].(string)
1942 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1949 func (s *TestSuite) TestStderrMount(c *C) {
1950 api, cr, _ := s.fullRunHelper(c, `{
1951 "command": ["/bin/sh", "-c", "echo hello;exit 1"],
1952 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1955 "mounts": {"/tmp": {"kind": "tmp"},
1956 "stdout": {"kind": "file", "path": "/tmp/a/out.txt"},
1957 "stderr": {"kind": "file", "path": "/tmp/b/err.txt"}},
1958 "output_path": "/tmp",
1960 "runtime_constraints": {},
1962 }`, nil, 1, func(t *TestDockerClient) {
1963 t.logWriter.Write(dockerLog(1, "hello\n"))
1964 t.logWriter.Write(dockerLog(2, "oops\n"))
1968 final := api.CalledWith("container.state", "Complete")
1969 c.Assert(final, NotNil)
1970 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1971 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1973 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)
1976 func (s *TestSuite) TestNumberRoundTrip(c *C) {
1977 kc := &KeepTestClient{}
1979 cr, err := NewContainerRunner(s.client, &ArvTestClient{callraw: true}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1980 c.Assert(err, IsNil)
1981 cr.fetchContainerRecord()
1983 jsondata, err := json.Marshal(cr.Container.Mounts["/json"].Content)
1986 c.Check(string(jsondata), Equals, `{"number":123456789123456789}`)
1989 func (s *TestSuite) TestFullBrokenDocker1(c *C) {
1990 tf, err := ioutil.TempFile("", "brokenNodeHook-")
1991 c.Assert(err, IsNil)
1992 defer os.Remove(tf.Name())
1994 tf.Write([]byte(`#!/bin/sh
1998 os.Chmod(tf.Name(), 0700)
2001 brokenNodeHook = &ech
2003 api, _, _ := s.fullRunHelper(c, `{
2004 "command": ["echo", "hello world"],
2005 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2008 "mounts": {"/tmp": {"kind": "tmp"} },
2009 "output_path": "/tmp",
2011 "runtime_constraints": {},
2013 }`, nil, 2, func(t *TestDockerClient) {
2014 t.logWriter.Write(dockerLog(1, "hello world\n"))
2018 c.Check(api.CalledWith("container.state", "Queued"), NotNil)
2019 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
2020 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Running broken node hook.*")
2021 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*killme.*")
2025 func (s *TestSuite) TestFullBrokenDocker2(c *C) {
2027 brokenNodeHook = &ech
2029 api, _, _ := s.fullRunHelper(c, `{
2030 "command": ["echo", "hello world"],
2031 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2034 "mounts": {"/tmp": {"kind": "tmp"} },
2035 "output_path": "/tmp",
2037 "runtime_constraints": {},
2039 }`, nil, 2, func(t *TestDockerClient) {
2040 t.logWriter.Write(dockerLog(1, "hello world\n"))
2044 c.Check(api.CalledWith("container.state", "Queued"), NotNil)
2045 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
2046 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Writing /var/lock/crunch-run-broken to mark node as broken.*")
2049 func (s *TestSuite) TestFullBrokenDocker3(c *C) {
2051 brokenNodeHook = &ech
2053 api, _, _ := s.fullRunHelper(c, `{
2054 "command": ["echo", "hello world"],
2055 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2058 "mounts": {"/tmp": {"kind": "tmp"} },
2059 "output_path": "/tmp",
2061 "runtime_constraints": {},
2063 }`, nil, 3, func(t *TestDockerClient) {
2064 t.logWriter.Write(dockerLog(1, "hello world\n"))
2068 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2069 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
2072 func (s *TestSuite) TestBadCommand1(c *C) {
2074 brokenNodeHook = &ech
2076 api, _, _ := s.fullRunHelper(c, `{
2077 "command": ["echo", "hello world"],
2078 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2081 "mounts": {"/tmp": {"kind": "tmp"} },
2082 "output_path": "/tmp",
2084 "runtime_constraints": {},
2086 }`, nil, 4, 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) TestBadCommand2(c *C) {
2097 brokenNodeHook = &ech
2099 api, _, _ := s.fullRunHelper(c, `{
2100 "command": ["echo", "hello world"],
2101 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2104 "mounts": {"/tmp": {"kind": "tmp"} },
2105 "output_path": "/tmp",
2107 "runtime_constraints": {},
2109 }`, nil, 5, func(t *TestDockerClient) {
2110 t.logWriter.Write(dockerLog(1, "hello world\n"))
2114 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2115 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2118 func (s *TestSuite) TestBadCommand3(c *C) {
2120 brokenNodeHook = &ech
2122 api, _, _ := s.fullRunHelper(c, `{
2123 "command": ["echo", "hello world"],
2124 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2127 "mounts": {"/tmp": {"kind": "tmp"} },
2128 "output_path": "/tmp",
2130 "runtime_constraints": {},
2132 }`, nil, 6, func(t *TestDockerClient) {
2133 t.logWriter.Write(dockerLog(1, "hello world\n"))
2137 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2138 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2141 func (s *TestSuite) TestSecretTextMountPoint(c *C) {
2142 // under normal mounts, gets captured in output, oops
2144 "command": ["true"],
2145 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2148 "/tmp": {"kind": "tmp"},
2149 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2153 "output_path": "/tmp",
2155 "runtime_constraints": {},
2159 api, cr, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2160 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2162 c.Check(content, DeepEquals, []byte("mypassword"))
2166 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2167 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2168 c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), NotNil)
2169 c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ""), IsNil)
2171 // under secret mounts, not captured in output
2173 "command": ["true"],
2174 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2177 "/tmp": {"kind": "tmp"}
2180 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2182 "output_path": "/tmp",
2184 "runtime_constraints": {},
2188 api, cr, _ = s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2189 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2191 c.Check(content, DeepEquals, []byte("mypassword"))
2195 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2196 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2197 c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), IsNil)
2198 c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ""), NotNil)
2201 type FakeProcess struct {
2205 func (fp FakeProcess) CmdlineSlice() ([]string, error) {
2206 return fp.cmdLine, nil