1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
29 "git.curoverse.com/arvados.git/sdk/go/arvados"
30 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
31 "git.curoverse.com/arvados.git/sdk/go/manifest"
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 type TestSuite struct{}
46 // Gocheck boilerplate
47 var _ = Suite(&TestSuite{})
49 type ArvTestClient struct {
52 Content []arvadosclient.Dict
54 Logs map[string]*bytes.Buffer
60 type KeepTestClient struct {
65 var hwManifest = ". 82ab40c24fc8df01798e57ba66795bb1+841216+Aa124ac75e5168396c73c0a18eda641a4f41791c0@569fa8c3 0:841216:9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7.tar\n"
66 var hwPDH = "a45557269dcb65a6b78f9ac061c0850b+120"
67 var hwImageId = "9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7"
69 var otherManifest = ". 68a84f561b1d1708c6baff5e019a9ab3+46+Ae5d0af96944a3690becb1decdf60cc1c937f556d@5693216f 0:46:md5sum.txt\n"
70 var otherPDH = "a3e8f74c6f101eae01fa08bfb4e49b3a+54"
72 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
73 ./subdir1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
74 ./subdir1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
77 var normalizedWithSubdirsPDH = "a0def87f80dd594d4675809e83bd4f15+367"
79 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"
80 var denormalizedWithSubdirsPDH = "b0def87f80dd594d4675809e83bd4f15+367"
82 var fakeAuthUUID = "zzzzz-gj3su-55pqoyepgi2glem"
83 var fakeAuthToken = "a3ltuwzqcu2u4sc0q7yhpc2w7s00fdcqecg5d6e0u3pfohmbjt"
85 type TestDockerClient struct {
87 logReader io.ReadCloser
88 logWriter io.WriteCloser
89 fn func(t *TestDockerClient)
98 func NewTestDockerClient(exitCode int) *TestDockerClient {
99 t := &TestDockerClient{}
100 t.logReader, t.logWriter = io.Pipe()
102 t.stop = make(chan bool, 1)
107 type MockConn struct {
111 func (m *MockConn) Write(b []byte) (int, error) {
115 func NewMockConn() *MockConn {
120 func (t *TestDockerClient) ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error) {
121 return dockertypes.HijackedResponse{Conn: NewMockConn(), Reader: bufio.NewReader(t.logReader)}, nil
124 func (t *TestDockerClient) ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig, networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error) {
125 if config.WorkingDir != "" {
126 t.cwd = config.WorkingDir
129 return dockercontainer.ContainerCreateCreatedBody{ID: "abcde"}, nil
132 func (t *TestDockerClient) ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error {
133 if container == "abcde" {
134 // t.fn gets executed in ContainerWait
137 return errors.New("Invalid container id")
141 func (t *TestDockerClient) ContainerStop(ctx context.Context, container string, timeout *time.Duration) error {
146 func (t *TestDockerClient) ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error) {
147 body := make(chan dockercontainer.ContainerWaitOKBody)
148 err := make(chan error)
151 body <- dockercontainer.ContainerWaitOKBody{StatusCode: int64(t.finish)}
158 func (t *TestDockerClient) ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error) {
159 if t.imageLoaded == image {
160 return dockertypes.ImageInspect{}, nil, nil
162 return dockertypes.ImageInspect{}, nil, errors.New("")
166 func (t *TestDockerClient) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error) {
167 _, err := io.Copy(ioutil.Discard, input)
169 return dockertypes.ImageLoadResponse{}, err
171 t.imageLoaded = hwImageId
172 return dockertypes.ImageLoadResponse{Body: ioutil.NopCloser(input)}, nil
176 func (*TestDockerClient) ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {
180 func (client *ArvTestClient) Create(resourceType string,
181 parameters arvadosclient.Dict,
182 output interface{}) error {
185 defer client.Mutex.Unlock()
188 client.Content = append(client.Content, parameters)
190 if resourceType == "logs" {
191 et := parameters["log"].(arvadosclient.Dict)["event_type"].(string)
192 if client.Logs == nil {
193 client.Logs = make(map[string]*bytes.Buffer)
195 if client.Logs[et] == nil {
196 client.Logs[et] = &bytes.Buffer{}
198 client.Logs[et].Write([]byte(parameters["log"].(arvadosclient.Dict)["properties"].(map[string]string)["text"]))
201 if resourceType == "collections" && output != nil {
202 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
203 outmap := output.(*arvados.Collection)
204 outmap.PortableDataHash = fmt.Sprintf("%x+%d", md5.Sum([]byte(mt)), len(mt))
210 func (client *ArvTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
212 case method == "GET" && resourceType == "containers" && action == "auth":
213 return json.Unmarshal([]byte(`{
214 "kind": "arvados#api_client_authorization",
215 "uuid": "`+fakeAuthUUID+`",
216 "api_token": "`+fakeAuthToken+`"
219 return fmt.Errorf("Not found")
223 func (client *ArvTestClient) CallRaw(method, resourceType, uuid, action string,
224 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
226 if method == "GET" && resourceType == "containers" && action == "" && !client.callraw {
227 j, err = json.Marshal(client.Container)
230 "command": ["sleep", "1"],
231 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
234 "mounts": {"/tmp": {"kind": "tmp"}, "/json": {"kind": "json", "content": {"number": 123456789123456789}}},
235 "output_path": "/tmp",
237 "runtime_constraints": {}
240 return ioutil.NopCloser(bytes.NewReader(j)), err
243 func (client *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
244 if resourceType == "collections" {
246 output.(*arvados.Collection).ManifestText = hwManifest
247 } else if uuid == otherPDH {
248 output.(*arvados.Collection).ManifestText = otherManifest
249 } else if uuid == normalizedWithSubdirsPDH {
250 output.(*arvados.Collection).ManifestText = normalizedManifestWithSubdirs
251 } else if uuid == denormalizedWithSubdirsPDH {
252 output.(*arvados.Collection).ManifestText = denormalizedManifestWithSubdirs
255 if resourceType == "containers" {
256 (*output.(*arvados.Container)) = client.Container
261 func (client *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
263 defer client.Mutex.Unlock()
265 client.Content = append(client.Content, parameters)
266 if resourceType == "containers" {
267 if parameters["container"].(arvadosclient.Dict)["state"] == "Running" {
268 client.WasSetRunning = true
274 var discoveryMap = map[string]interface{}{
275 "defaultTrashLifetime": float64(1209600),
276 "crunchLimitLogBytesPerJob": float64(67108864),
277 "crunchLogThrottleBytes": float64(65536),
278 "crunchLogThrottlePeriod": float64(60),
279 "crunchLogThrottleLines": float64(1024),
280 "crunchLogPartialLineThrottlePeriod": float64(5),
281 "crunchLogBytesPerEvent": float64(4096),
282 "crunchLogSecondsBetweenEvents": float64(1),
285 func (client *ArvTestClient) Discovery(key string) (interface{}, error) {
286 return discoveryMap[key], nil
289 // CalledWith returns the parameters from the first API call whose
290 // parameters match jpath/string. E.g., CalledWith(c, "foo.bar",
291 // "baz") returns parameters with parameters["foo"]["bar"]=="baz". If
292 // no call matches, it returns nil.
293 func (client *ArvTestClient) CalledWith(jpath string, expect interface{}) arvadosclient.Dict {
295 for _, content := range client.Content {
296 var v interface{} = content
297 for _, k := range strings.Split(jpath, ".") {
298 if dict, ok := v.(arvadosclient.Dict); !ok {
311 func (client *KeepTestClient) PutHB(hash string, buf []byte) (string, int, error) {
313 return fmt.Sprintf("%s+%d", hash, len(buf)), len(buf), nil
316 func (*KeepTestClient) ClearBlockCache() {
319 type FileWrapper struct {
324 func (fw FileWrapper) Size() int64 {
328 func (fw FileWrapper) Seek(int64, int) (int64, error) {
329 return 0, errors.New("not implemented")
332 func (client *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
333 if filename == hwImageId+".tar" {
334 rdr := ioutil.NopCloser(&bytes.Buffer{})
336 return FileWrapper{rdr, 1321984}, nil
337 } else if filename == "/file1_in_main.txt" {
338 rdr := ioutil.NopCloser(strings.NewReader("foo"))
340 return FileWrapper{rdr, 3}, nil
345 func (s *TestSuite) TestLoadImage(c *C) {
346 kc := &KeepTestClient{}
347 docker := NewTestDockerClient(0)
348 cr := NewContainerRunner(&ArvTestClient{}, kc, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
350 _, err := cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
352 _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
355 cr.Container.ContainerImage = hwPDH
357 // (1) Test loading image from keep
358 c.Check(kc.Called, Equals, false)
359 c.Check(cr.ContainerConfig.Image, Equals, "")
365 cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
368 c.Check(kc.Called, Equals, true)
369 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
371 _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
374 // (2) Test using image that's already loaded
376 cr.ContainerConfig.Image = ""
380 c.Check(kc.Called, Equals, false)
381 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
385 type ArvErrorTestClient struct{}
387 func (ArvErrorTestClient) Create(resourceType string,
388 parameters arvadosclient.Dict,
389 output interface{}) error {
393 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
394 return errors.New("ArvError")
397 func (ArvErrorTestClient) CallRaw(method, resourceType, uuid, action string,
398 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
399 return nil, errors.New("ArvError")
402 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
403 return errors.New("ArvError")
406 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
410 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
411 return discoveryMap[key], nil
414 type KeepErrorTestClient struct{}
416 func (KeepErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
417 return "", 0, errors.New("KeepError")
420 func (KeepErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
421 return nil, errors.New("KeepError")
424 func (KeepErrorTestClient) ClearBlockCache() {
427 type KeepReadErrorTestClient struct{}
429 func (KeepReadErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
433 func (KeepReadErrorTestClient) ClearBlockCache() {
436 type ErrorReader struct{}
438 func (ErrorReader) Read(p []byte) (n int, err error) {
439 return 0, errors.New("ErrorReader")
442 func (ErrorReader) Close() error {
446 func (ErrorReader) Size() int64 {
450 func (ErrorReader) Seek(int64, int) (int64, error) {
451 return 0, errors.New("ErrorReader")
454 func (KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
455 return ErrorReader{}, nil
458 func (s *TestSuite) TestLoadImageArvError(c *C) {
460 cr := NewContainerRunner(ArvErrorTestClient{}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
461 cr.Container.ContainerImage = hwPDH
463 err := cr.LoadImage()
464 c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
467 func (s *TestSuite) TestLoadImageKeepError(c *C) {
469 docker := NewTestDockerClient(0)
470 cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
471 cr.Container.ContainerImage = hwPDH
473 err := cr.LoadImage()
474 c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
477 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
478 // (3) Collection doesn't contain image
479 cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
480 cr.Container.ContainerImage = otherPDH
482 err := cr.LoadImage()
483 c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
486 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
487 // (4) Collection doesn't contain image
488 docker := NewTestDockerClient(0)
489 cr := NewContainerRunner(&ArvTestClient{}, KeepReadErrorTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
490 cr.Container.ContainerImage = hwPDH
492 err := cr.LoadImage()
496 type ClosableBuffer struct {
500 func (*ClosableBuffer) Close() error {
504 type TestLogs struct {
505 Stdout ClosableBuffer
506 Stderr ClosableBuffer
509 func (tl *TestLogs) NewTestLoggingWriter(logstr string) io.WriteCloser {
510 if logstr == "stdout" {
513 if logstr == "stderr" {
519 func dockerLog(fd byte, msg string) []byte {
521 header := make([]byte, 8+len(by))
523 header[7] = byte(len(by))
528 func (s *TestSuite) TestRunContainer(c *C) {
529 docker := NewTestDockerClient(0)
530 docker.fn = func(t *TestDockerClient) {
531 t.logWriter.Write(dockerLog(1, "Hello world\n"))
534 cr := NewContainerRunner(&ArvTestClient{}, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
537 cr.NewLogWriter = logs.NewTestLoggingWriter
538 cr.Container.ContainerImage = hwPDH
539 cr.Container.Command = []string{"./hw"}
540 err := cr.LoadImage()
543 err = cr.CreateContainer()
546 err = cr.StartContainer()
549 err = cr.WaitFinish()
552 c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
553 c.Check(logs.Stderr.String(), Equals, "")
556 func (s *TestSuite) TestCommitLogs(c *C) {
557 api := &ArvTestClient{}
558 kc := &KeepTestClient{}
559 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
560 cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
562 cr.CrunchLog.Print("Hello world!")
563 cr.CrunchLog.Print("Goodbye")
564 cr.finalState = "Complete"
566 err := cr.CommitLogs()
569 c.Check(api.Calls, Equals, 2)
570 c.Check(api.Content[1]["ensure_unique_name"], Equals, true)
571 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
572 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
573 c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
576 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
577 api := &ArvTestClient{}
578 kc := &KeepTestClient{}
579 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
581 err := cr.UpdateContainerRunning()
584 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
587 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
588 api := &ArvTestClient{}
589 kc := &KeepTestClient{}
590 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
592 cr.LogsPDH = new(string)
593 *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
595 cr.ExitCode = new(int)
597 cr.finalState = "Complete"
599 err := cr.UpdateContainerFinal()
602 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
603 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
604 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
607 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
608 api := &ArvTestClient{}
609 kc := &KeepTestClient{}
610 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
612 cr.finalState = "Cancelled"
614 err := cr.UpdateContainerFinal()
617 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
618 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
619 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
622 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
623 // dress rehearsal of the Run() function, starting from a JSON container record.
624 func FullRunHelper(c *C, record string, extraMounts []string, exitCode int, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, realTemp string) {
625 rec := arvados.Container{}
626 err := json.Unmarshal([]byte(record), &rec)
629 docker := NewTestDockerClient(exitCode)
631 docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
633 api = &ArvTestClient{Container: rec}
635 cr = NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
636 cr.statInterval = 100 * time.Millisecond
637 am := &ArvMountCmdLine{}
638 cr.RunArvMount = am.ArvMountTest
640 realTemp, err = ioutil.TempDir("", "crunchrun_test1-")
642 defer os.RemoveAll(realTemp)
644 docker.realTemp = realTemp
647 cr.MkTempDir = func(_ string, prefix string) (string, error) {
649 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, tempcount)
650 err := os.Mkdir(d, os.ModePerm)
651 if err != nil && strings.Contains(err.Error(), ": file exists") {
652 // Test case must have pre-populated the tempdir
658 if extraMounts != nil && len(extraMounts) > 0 {
659 err := cr.SetupArvMountPoint("keep")
662 for _, m := range extraMounts {
663 os.MkdirAll(cr.ArvMountPoint+"/by_id/"+m, os.ModePerm)
668 if api.CalledWith("container.state", "Complete") != nil {
671 c.Check(api.WasSetRunning, Equals, true)
673 c.Check(api.Content[api.Calls-1]["container"].(arvadosclient.Dict)["log"], NotNil)
676 for k, v := range api.Logs {
685 func (s *TestSuite) TestFullRunHello(c *C) {
686 api, _, _ := FullRunHelper(c, `{
687 "command": ["echo", "hello world"],
688 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
691 "mounts": {"/tmp": {"kind": "tmp"} },
692 "output_path": "/tmp",
694 "runtime_constraints": {}
695 }`, nil, 0, func(t *TestDockerClient) {
696 t.logWriter.Write(dockerLog(1, "hello world\n"))
700 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
701 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
702 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
706 func (s *TestSuite) TestCrunchstat(c *C) {
707 api, _, _ := FullRunHelper(c, `{
708 "command": ["sleep", "1"],
709 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
712 "mounts": {"/tmp": {"kind": "tmp"} },
713 "output_path": "/tmp",
715 "runtime_constraints": {}
716 }`, nil, 0, func(t *TestDockerClient) {
717 time.Sleep(time.Second)
721 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
722 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
724 // We didn't actually start a container, so crunchstat didn't
725 // find accounting files and therefore didn't log any stats.
726 // It should have logged a "can't find accounting files"
727 // message after one poll interval, though, so we can confirm
729 c.Assert(api.Logs["crunchstat"], NotNil)
730 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
732 // The "files never appeared" log assures us that we called
733 // (*crunchstat.Reporter)Stop(), and that we set it up with
734 // the correct container ID "abcde":
735 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files never appeared for abcde\n`)
738 func (s *TestSuite) TestNodeInfoLog(c *C) {
739 api, _, _ := FullRunHelper(c, `{
740 "command": ["sleep", "1"],
741 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
744 "mounts": {"/tmp": {"kind": "tmp"} },
745 "output_path": "/tmp",
747 "runtime_constraints": {}
749 func(t *TestDockerClient) {
750 time.Sleep(time.Second)
754 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
755 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
757 c.Assert(api.Logs["node-info"], NotNil)
758 c.Check(api.Logs["node-info"].String(), Matches, `(?ms).*Host Information.*`)
759 c.Check(api.Logs["node-info"].String(), Matches, `(?ms).*CPU Information.*`)
760 c.Check(api.Logs["node-info"].String(), Matches, `(?ms).*Memory Information.*`)
761 c.Check(api.Logs["node-info"].String(), Matches, `(?ms).*Disk Space.*`)
762 c.Check(api.Logs["node-info"].String(), Matches, `(?ms).*Disk INodes.*`)
765 func (s *TestSuite) TestContainerRecordLog(c *C) {
766 api, _, _ := FullRunHelper(c, `{
767 "command": ["sleep", "1"],
768 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
771 "mounts": {"/tmp": {"kind": "tmp"} },
772 "output_path": "/tmp",
774 "runtime_constraints": {}
776 func(t *TestDockerClient) {
777 time.Sleep(time.Second)
781 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
782 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
784 c.Assert(api.Logs["container"], NotNil)
785 c.Check(api.Logs["container"].String(), Matches, `(?ms).*container_image.*`)
788 func (s *TestSuite) TestFullRunStderr(c *C) {
789 api, _, _ := FullRunHelper(c, `{
790 "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
791 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
794 "mounts": {"/tmp": {"kind": "tmp"} },
795 "output_path": "/tmp",
797 "runtime_constraints": {}
798 }`, nil, 1, func(t *TestDockerClient) {
799 t.logWriter.Write(dockerLog(1, "hello\n"))
800 t.logWriter.Write(dockerLog(2, "world\n"))
804 final := api.CalledWith("container.state", "Complete")
805 c.Assert(final, NotNil)
806 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
807 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
809 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
810 c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
813 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
814 api, _, _ := FullRunHelper(c, `{
816 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
819 "mounts": {"/tmp": {"kind": "tmp"} },
820 "output_path": "/tmp",
822 "runtime_constraints": {}
823 }`, nil, 0, func(t *TestDockerClient) {
824 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
828 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
829 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
830 c.Log(api.Logs["stdout"])
831 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
834 func (s *TestSuite) TestFullRunSetCwd(c *C) {
835 api, _, _ := FullRunHelper(c, `{
837 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
840 "mounts": {"/tmp": {"kind": "tmp"} },
841 "output_path": "/tmp",
843 "runtime_constraints": {}
844 }`, nil, 0, func(t *TestDockerClient) {
845 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
849 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
850 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
851 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
854 func (s *TestSuite) TestStopOnSignal(c *C) {
855 s.testStopContainer(c, func(cr *ContainerRunner) {
858 time.Sleep(time.Millisecond)
860 cr.SigChan <- syscall.SIGINT
865 func (s *TestSuite) TestStopOnArvMountDeath(c *C) {
866 s.testStopContainer(c, func(cr *ContainerRunner) {
867 cr.ArvMountExit = make(chan error)
869 cr.ArvMountExit <- exec.Command("true").Run()
870 close(cr.ArvMountExit)
875 func (s *TestSuite) testStopContainer(c *C, setup func(cr *ContainerRunner)) {
877 "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
878 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
881 "mounts": {"/tmp": {"kind": "tmp"} },
882 "output_path": "/tmp",
884 "runtime_constraints": {}
887 rec := arvados.Container{}
888 err := json.Unmarshal([]byte(record), &rec)
891 docker := NewTestDockerClient(0)
892 docker.fn = func(t *TestDockerClient) {
894 t.logWriter.Write(dockerLog(1, "foo\n"))
897 docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
899 api := &ArvTestClient{Container: rec}
900 cr := NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
901 cr.RunArvMount = func([]string, string) (*exec.Cmd, error) { return nil, nil }
904 done := make(chan error)
909 case <-time.After(20 * time.Second):
910 pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
915 for k, v := range api.Logs {
920 c.Check(api.CalledWith("container.log", nil), NotNil)
921 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
922 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "foo\n"), Equals, true)
925 func (s *TestSuite) TestFullRunSetEnv(c *C) {
926 api, _, _ := FullRunHelper(c, `{
927 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
928 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
930 "environment": {"FROBIZ": "bilbo"},
931 "mounts": {"/tmp": {"kind": "tmp"} },
932 "output_path": "/tmp",
934 "runtime_constraints": {}
935 }`, nil, 0, func(t *TestDockerClient) {
936 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
940 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
941 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
942 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)
945 type ArvMountCmdLine struct {
950 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
956 func stubCert(temp string) string {
957 path := temp + "/ca-certificates.crt"
958 crt, _ := os.Create(path)
960 arvadosclient.CertFiles = []string{path}
964 func (s *TestSuite) TestSetupMounts(c *C) {
965 api := &ArvTestClient{}
966 kc := &KeepTestClient{}
967 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
968 am := &ArvMountCmdLine{}
969 cr.RunArvMount = am.ArvMountTest
971 realTemp, err := ioutil.TempDir("", "crunchrun_test1-")
973 certTemp, err := ioutil.TempDir("", "crunchrun_test2-")
975 stubCertPath := stubCert(certTemp)
977 defer os.RemoveAll(realTemp)
978 defer os.RemoveAll(certTemp)
981 cr.MkTempDir = func(_ string, prefix string) (string, error) {
983 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
984 err := os.Mkdir(d, os.ModePerm)
985 if err != nil && strings.Contains(err.Error(), ": file exists") {
986 // Test case must have pre-populated the tempdir
992 checkEmpty := func() {
993 filepath.Walk(realTemp, func(path string, _ os.FileInfo, err error) error {
994 c.Check(path, Equals, realTemp)
1002 cr.ArvMountPoint = ""
1003 cr.Container.Mounts = make(map[string]arvados.Mount)
1004 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1005 cr.OutputPath = "/tmp"
1006 cr.statInterval = 5 * time.Second
1007 err := cr.SetupMounts()
1009 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1010 "--read-write", "--crunchstat-interval=5",
1011 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1012 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/tmp"})
1019 cr.ArvMountPoint = ""
1020 cr.Container.Mounts = make(map[string]arvados.Mount)
1021 cr.Container.Mounts["/out"] = arvados.Mount{Kind: "tmp"}
1022 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1023 cr.OutputPath = "/out"
1025 err := cr.SetupMounts()
1027 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1028 "--read-write", "--crunchstat-interval=5",
1029 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1030 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/out", realTemp + "/3:/tmp"})
1037 cr.ArvMountPoint = ""
1038 cr.Container.Mounts = make(map[string]arvados.Mount)
1039 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1040 cr.OutputPath = "/tmp"
1043 cr.Container.RuntimeConstraints.API = &apiflag
1045 err := cr.SetupMounts()
1047 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1048 "--read-write", "--crunchstat-interval=5",
1049 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1050 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/tmp", stubCertPath + ":/etc/arvados/ca-certificates.crt:ro"})
1059 cr.ArvMountPoint = ""
1060 cr.Container.Mounts = map[string]arvados.Mount{
1061 "/keeptmp": {Kind: "collection", Writable: true},
1063 cr.OutputPath = "/keeptmp"
1065 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1067 err := cr.SetupMounts()
1069 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1070 "--read-write", "--crunchstat-interval=5",
1071 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1072 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/tmp0:/keeptmp"})
1079 cr.ArvMountPoint = ""
1080 cr.Container.Mounts = map[string]arvados.Mount{
1081 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1082 "/keepout": {Kind: "collection", Writable: true},
1084 cr.OutputPath = "/keepout"
1086 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1087 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1089 err := cr.SetupMounts()
1091 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1092 "--read-write", "--crunchstat-interval=5",
1093 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1094 sort.StringSlice(cr.Binds).Sort()
1095 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1096 realTemp + "/keep1/tmp0:/keepout"})
1103 cr.ArvMountPoint = ""
1104 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
1105 cr.Container.Mounts = map[string]arvados.Mount{
1106 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1107 "/keepout": {Kind: "collection", Writable: true},
1109 cr.OutputPath = "/keepout"
1111 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1112 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1114 err := cr.SetupMounts()
1116 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1117 "--read-write", "--crunchstat-interval=5",
1118 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1119 sort.StringSlice(cr.Binds).Sort()
1120 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1121 realTemp + "/keep1/tmp0:/keepout"})
1126 for _, test := range []struct {
1130 {in: "foo", out: `"foo"`},
1131 {in: nil, out: `null`},
1132 {in: map[string]int64{"foo": 123456789123456789}, out: `{"foo":123456789123456789}`},
1135 cr.ArvMountPoint = ""
1136 cr.Container.Mounts = map[string]arvados.Mount{
1137 "/mnt/test.json": {Kind: "json", Content: test.in},
1139 err := cr.SetupMounts()
1141 sort.StringSlice(cr.Binds).Sort()
1142 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2/mountdata.json:/mnt/test.json:ro"})
1143 content, err := ioutil.ReadFile(realTemp + "/2/mountdata.json")
1145 c.Check(content, DeepEquals, []byte(test.out))
1150 // Read-only mount points are allowed underneath output_dir mount point
1153 cr.ArvMountPoint = ""
1154 cr.Container.Mounts = make(map[string]arvados.Mount)
1155 cr.Container.Mounts = map[string]arvados.Mount{
1156 "/tmp": {Kind: "tmp"},
1157 "/tmp/foo": {Kind: "collection"},
1159 cr.OutputPath = "/tmp"
1161 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1163 err := cr.SetupMounts()
1165 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1166 "--read-write", "--crunchstat-interval=5",
1167 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1168 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/tmp", realTemp + "/keep1/tmp0:/tmp/foo:ro"})
1173 // Writable mount points are not allowed underneath output_dir mount point
1176 cr.ArvMountPoint = ""
1177 cr.Container.Mounts = make(map[string]arvados.Mount)
1178 cr.Container.Mounts = map[string]arvados.Mount{
1179 "/tmp": {Kind: "tmp"},
1180 "/tmp/foo": {Kind: "collection", Writable: true},
1182 cr.OutputPath = "/tmp"
1184 err := cr.SetupMounts()
1185 c.Check(err, NotNil)
1186 c.Check(err, ErrorMatches, `Writable mount points are not permitted underneath the output_path.*`)
1191 // Only mount points of kind 'collection' are allowed underneath output_dir mount point
1194 cr.ArvMountPoint = ""
1195 cr.Container.Mounts = make(map[string]arvados.Mount)
1196 cr.Container.Mounts = map[string]arvados.Mount{
1197 "/tmp": {Kind: "tmp"},
1198 "/tmp/foo": {Kind: "json"},
1200 cr.OutputPath = "/tmp"
1202 err := cr.SetupMounts()
1203 c.Check(err, NotNil)
1204 c.Check(err, ErrorMatches, `Only mount points of kind 'collection' are supported underneath the output_path.*`)
1209 // Only mount point of kind 'collection' is allowed for stdin
1212 cr.ArvMountPoint = ""
1213 cr.Container.Mounts = make(map[string]arvados.Mount)
1214 cr.Container.Mounts = map[string]arvados.Mount{
1215 "stdin": {Kind: "tmp"},
1218 err := cr.SetupMounts()
1219 c.Check(err, NotNil)
1220 c.Check(err, ErrorMatches, `Unsupported mount kind 'tmp' for stdin.*`)
1226 func (s *TestSuite) TestStdout(c *C) {
1228 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1229 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1231 "environment": {"FROBIZ": "bilbo"},
1232 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1233 "output_path": "/tmp",
1235 "runtime_constraints": {}
1238 api, _, _ := FullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1239 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1243 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1244 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1245 c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1248 // Used by the TestStdoutWithWrongPath*()
1249 func StdoutErrorRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, err error) {
1250 rec := arvados.Container{}
1251 err = json.Unmarshal([]byte(record), &rec)
1254 docker := NewTestDockerClient(0)
1256 docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
1258 api = &ArvTestClient{Container: rec}
1259 cr = NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1260 am := &ArvMountCmdLine{}
1261 cr.RunArvMount = am.ArvMountTest
1267 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1268 _, _, err := StdoutErrorRunHelper(c, `{
1269 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1270 "output_path": "/tmp"
1271 }`, func(t *TestDockerClient) {})
1273 c.Check(err, NotNil)
1274 c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
1277 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1278 _, _, err := StdoutErrorRunHelper(c, `{
1279 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1280 "output_path": "/tmp"
1281 }`, func(t *TestDockerClient) {})
1283 c.Check(err, NotNil)
1284 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'tmp' for stdout"), Equals, true)
1287 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1288 _, _, err := StdoutErrorRunHelper(c, `{
1289 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1290 "output_path": "/tmp"
1291 }`, func(t *TestDockerClient) {})
1293 c.Check(err, NotNil)
1294 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'collection' for stdout"), Equals, true)
1297 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1298 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1299 defer os.Unsetenv("ARVADOS_API_HOST")
1300 api, _, _ := FullRunHelper(c, `{
1301 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1302 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1305 "mounts": {"/tmp": {"kind": "tmp"} },
1306 "output_path": "/tmp",
1308 "runtime_constraints": {"API": true}
1309 }`, nil, 0, func(t *TestDockerClient) {
1310 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
1314 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1315 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1316 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "test.arvados.org\n"), Equals, true)
1317 c.Check(api.CalledWith("container.output", "d41d8cd98f00b204e9800998ecf8427e+0"), NotNil)
1320 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1321 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1322 defer os.Unsetenv("ARVADOS_API_HOST")
1323 api, _, _ := FullRunHelper(c, `{
1324 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1325 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1328 "mounts": {"/tmp": {"kind": "tmp"} },
1329 "output_path": "/tmp",
1331 "runtime_constraints": {"API": true}
1332 }`, nil, 0, func(t *TestDockerClient) {
1333 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
1337 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1338 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1339 c.Check(api.CalledWith("container.output", "d4ab34d3d4f8a72f5c4973051ae69fab+122"), NotNil)
1342 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1344 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1345 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1347 "environment": {"FROBIZ": "bilbo"},
1349 "/tmp": {"kind": "tmp"},
1350 "/tmp/foo": {"kind": "collection",
1351 "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1352 "exclude_from_output": true
1354 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1356 "output_path": "/tmp",
1358 "runtime_constraints": {}
1361 extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1363 api, _, _ := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1364 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1368 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1369 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1370 c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1373 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1375 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1376 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1378 "environment": {"FROBIZ": "bilbo"},
1380 "/tmp": {"kind": "tmp"},
1381 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1382 "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1383 "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1384 "/tmp/foo/baz/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1385 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1387 "output_path": "/tmp",
1389 "runtime_constraints": {}
1392 extraMounts := []string{
1393 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1394 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1395 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1398 api, runner, realtemp := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1399 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1403 c.Check(runner.Binds, DeepEquals, []string{realtemp + "/2:/tmp",
1404 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt:/tmp/foo/bar:ro",
1405 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt:/tmp/foo/baz/sub2file2:ro",
1406 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1:/tmp/foo/sub1:ro",
1407 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt:/tmp/foo/sub1file2:ro",
1410 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1411 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1412 for _, v := range api.Content {
1413 if v["collection"] != nil {
1414 c.Check(v["ensure_unique_name"], Equals, true)
1415 collection := v["collection"].(arvadosclient.Dict)
1416 if strings.Index(collection["name"].(string), "output") == 0 {
1417 manifest := collection["manifest_text"].(string)
1419 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1420 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 9:18:bar 9:18:sub1file2
1421 ./foo/baz 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2
1422 ./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1423 ./foo/sub1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1430 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
1432 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1433 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1435 "environment": {"FROBIZ": "bilbo"},
1437 "/tmp": {"kind": "tmp"},
1438 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt"},
1439 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1441 "output_path": "/tmp",
1443 "runtime_constraints": {}
1446 extraMounts := []string{
1447 "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1450 api, _, _ := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1451 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1455 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1456 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1457 for _, v := range api.Content {
1458 if v["collection"] != nil {
1459 collection := v["collection"].(arvadosclient.Dict)
1460 if strings.Index(collection["name"].(string), "output") == 0 {
1461 manifest := collection["manifest_text"].(string)
1463 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1464 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 10:17:bar
1471 func (s *TestSuite) TestOutputSymlinkToInput(c *C) {
1473 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1474 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1476 "environment": {"FROBIZ": "bilbo"},
1478 "/tmp": {"kind": "tmp"},
1479 "/keep/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path": "/subdir1/file2_in_subdir1.txt"},
1480 "/keep/foo2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367"}
1482 "output_path": "/tmp",
1484 "runtime_constraints": {}
1487 extraMounts := []string{
1488 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1491 api, _, _ := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1492 os.Symlink("/keep/foo/sub1file2", t.realTemp+"/2/baz")
1493 os.Symlink("/keep/foo2/subdir1/file2_in_subdir1.txt", t.realTemp+"/2/baz2")
1494 os.Symlink("/keep/foo2/subdir1", t.realTemp+"/2/baz3")
1495 os.Mkdir(t.realTemp+"/2/baz4", 0700)
1496 os.Symlink("/keep/foo2/subdir1/file2_in_subdir1.txt", t.realTemp+"/2/baz4/baz5")
1500 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1501 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1502 for _, v := range api.Content {
1503 if v["collection"] != nil {
1504 collection := v["collection"].(arvadosclient.Dict)
1505 if strings.Index(collection["name"].(string), "output") == 0 {
1506 manifest := collection["manifest_text"].(string)
1507 c.Check(manifest, Equals, `. 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:baz 9:18:baz2
1508 ./baz3 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1509 ./baz3/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1510 ./baz4 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:baz5
1517 func (s *TestSuite) TestOutputError(c *C) {
1519 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1520 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1522 "environment": {"FROBIZ": "bilbo"},
1524 "/tmp": {"kind": "tmp"}
1526 "output_path": "/tmp",
1528 "runtime_constraints": {}
1531 extraMounts := []string{}
1533 api, _, _ := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1534 os.Symlink("/etc/hosts", t.realTemp+"/2/baz")
1538 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1541 func (s *TestSuite) TestOutputSymlinkToOutput(c *C) {
1543 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1544 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1546 "environment": {"FROBIZ": "bilbo"},
1548 "/tmp": {"kind": "tmp"}
1550 "output_path": "/tmp",
1552 "runtime_constraints": {}
1555 extraMounts := []string{}
1557 api, _, _ := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1558 rf, _ := os.Create(t.realTemp + "/2/realfile")
1559 rf.Write([]byte("foo"))
1562 os.Mkdir(t.realTemp+"/2/realdir", 0700)
1563 rf, _ = os.Create(t.realTemp + "/2/realdir/subfile")
1564 rf.Write([]byte("bar"))
1567 os.Symlink("/tmp/realfile", t.realTemp+"/2/file1")
1568 os.Symlink("realfile", t.realTemp+"/2/file2")
1569 os.Symlink("/tmp/file1", t.realTemp+"/2/file3")
1570 os.Symlink("file2", t.realTemp+"/2/file4")
1571 os.Symlink("realdir", t.realTemp+"/2/dir1")
1572 os.Symlink("/tmp/realdir", t.realTemp+"/2/dir2")
1576 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1577 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1578 for _, v := range api.Content {
1579 if v["collection"] != nil {
1580 collection := v["collection"].(arvadosclient.Dict)
1581 if strings.Index(collection["name"].(string), "output") == 0 {
1582 manifest := collection["manifest_text"].(string)
1583 c.Check(manifest, Equals,
1584 `. 7a2c86e102dcc231bd232aad99686dfa+15 0:3:file1 3:3:file2 6:3:file3 9:3:file4 12:3:realfile
1585 ./dir1 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1586 ./dir2 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1587 ./realdir 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1594 func (s *TestSuite) TestStdinCollectionMountPoint(c *C) {
1596 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1597 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1599 "environment": {"FROBIZ": "bilbo"},
1601 "/tmp": {"kind": "tmp"},
1602 "stdin": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/file1_in_main.txt"},
1603 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1605 "output_path": "/tmp",
1607 "runtime_constraints": {}
1610 extraMounts := []string{
1611 "b0def87f80dd594d4675809e83bd4f15+367/file1_in_main.txt",
1614 api, _, _ := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1615 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1619 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1620 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1621 for _, v := range api.Content {
1622 if v["collection"] != nil {
1623 collection := v["collection"].(arvadosclient.Dict)
1624 if strings.Index(collection["name"].(string), "output") == 0 {
1625 manifest := collection["manifest_text"].(string)
1626 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1633 func (s *TestSuite) TestStdinJsonMountPoint(c *C) {
1635 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1636 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1638 "environment": {"FROBIZ": "bilbo"},
1640 "/tmp": {"kind": "tmp"},
1641 "stdin": {"kind": "json", "content": "foo"},
1642 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1644 "output_path": "/tmp",
1646 "runtime_constraints": {}
1649 api, _, _ := FullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1650 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1654 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1655 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1656 for _, v := range api.Content {
1657 if v["collection"] != nil {
1658 collection := v["collection"].(arvadosclient.Dict)
1659 if strings.Index(collection["name"].(string), "output") == 0 {
1660 manifest := collection["manifest_text"].(string)
1661 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1668 func (s *TestSuite) TestStderrMount(c *C) {
1669 api, _, _ := FullRunHelper(c, `{
1670 "command": ["/bin/sh", "-c", "echo hello;exit 1"],
1671 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1674 "mounts": {"/tmp": {"kind": "tmp"},
1675 "stdout": {"kind": "file", "path": "/tmp/a/out.txt"},
1676 "stderr": {"kind": "file", "path": "/tmp/b/err.txt"}},
1677 "output_path": "/tmp",
1679 "runtime_constraints": {}
1680 }`, nil, 1, func(t *TestDockerClient) {
1681 t.logWriter.Write(dockerLog(1, "hello\n"))
1682 t.logWriter.Write(dockerLog(2, "oops\n"))
1686 final := api.CalledWith("container.state", "Complete")
1687 c.Assert(final, NotNil)
1688 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1689 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1691 c.Check(api.CalledWith("collection.manifest_text", "./a b1946ac92492d2347c6235b4d2611184+6 0:6:out.txt\n./b 38af5c54926b620264ab1501150cf189+5 0:5:err.txt\n"), NotNil)
1694 func (s *TestSuite) TestNumberRoundTrip(c *C) {
1695 cr := NewContainerRunner(&ArvTestClient{callraw: true}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1696 cr.fetchContainerRecord()
1698 jsondata, err := json.Marshal(cr.Container.Mounts["/json"].Content)
1701 c.Check(string(jsondata), Equals, `{"number":123456789123456789}`)
1704 func (s *TestSuite) TestEvalSymlinks(c *C) {
1705 cr := NewContainerRunner(&ArvTestClient{callraw: true}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1707 realTemp, err := ioutil.TempDir("", "crunchrun_test-")
1708 c.Assert(err, IsNil)
1709 defer os.RemoveAll(realTemp)
1711 cr.HostOutputDir = realTemp
1713 // Absolute path outside output dir
1714 os.Symlink("/etc/passwd", realTemp+"/p1")
1716 // Relative outside output dir
1717 os.Symlink("../zip", realTemp+"/p2")
1719 // Circular references
1720 os.Symlink("p4", realTemp+"/p3")
1721 os.Symlink("p5", realTemp+"/p4")
1722 os.Symlink("p3", realTemp+"/p5")
1724 // Target doesn't exist
1725 os.Symlink("p99", realTemp+"/p6")
1727 for _, v := range []string{"p1", "p2", "p3", "p4", "p5"} {
1728 info, err := os.Lstat(realTemp + "/" + v)
1729 _, _, _, err = cr.derefOutputSymlink(realTemp+"/"+v, info)
1730 c.Assert(err, NotNil)
1734 func (s *TestSuite) TestEvalSymlinkDir(c *C) {
1735 cr := NewContainerRunner(&ArvTestClient{callraw: true}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1737 realTemp, err := ioutil.TempDir("", "crunchrun_test-")
1738 c.Assert(err, IsNil)
1739 defer os.RemoveAll(realTemp)
1741 cr.HostOutputDir = realTemp
1743 // Absolute path outside output dir
1744 os.Symlink(".", realTemp+"/loop")
1747 info, err := os.Lstat(realTemp + "/" + v)
1748 _, err = cr.UploadOutputFile(realTemp+"/"+v, info, err, []string{}, nil, "", "", 0)
1749 c.Assert(err, NotNil)