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) {
160 return dockertypes.ImageInspect{}, nil, fmt.Errorf("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?")
163 if t.imageLoaded == image {
164 return dockertypes.ImageInspect{}, nil, nil
166 return dockertypes.ImageInspect{}, nil, errors.New("")
170 func (t *TestDockerClient) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error) {
172 return dockertypes.ImageLoadResponse{}, fmt.Errorf("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?")
174 _, err := io.Copy(ioutil.Discard, input)
176 return dockertypes.ImageLoadResponse{}, err
178 t.imageLoaded = hwImageId
179 return dockertypes.ImageLoadResponse{Body: ioutil.NopCloser(input)}, nil
183 func (*TestDockerClient) ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {
187 func (client *ArvTestClient) Create(resourceType string,
188 parameters arvadosclient.Dict,
189 output interface{}) error {
192 defer client.Mutex.Unlock()
195 client.Content = append(client.Content, parameters)
197 if resourceType == "logs" {
198 et := parameters["log"].(arvadosclient.Dict)["event_type"].(string)
199 if client.Logs == nil {
200 client.Logs = make(map[string]*bytes.Buffer)
202 if client.Logs[et] == nil {
203 client.Logs[et] = &bytes.Buffer{}
205 client.Logs[et].Write([]byte(parameters["log"].(arvadosclient.Dict)["properties"].(map[string]string)["text"]))
208 if resourceType == "collections" && output != nil {
209 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
210 outmap := output.(*arvados.Collection)
211 outmap.PortableDataHash = fmt.Sprintf("%x+%d", md5.Sum([]byte(mt)), len(mt))
217 func (client *ArvTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
219 case method == "GET" && resourceType == "containers" && action == "auth":
220 return json.Unmarshal([]byte(`{
221 "kind": "arvados#api_client_authorization",
222 "uuid": "`+fakeAuthUUID+`",
223 "api_token": "`+fakeAuthToken+`"
226 return fmt.Errorf("Not found")
230 func (client *ArvTestClient) CallRaw(method, resourceType, uuid, action string,
231 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
233 if method == "GET" && resourceType == "containers" && action == "" && !client.callraw {
234 j, err = json.Marshal(client.Container)
237 "command": ["sleep", "1"],
238 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
241 "mounts": {"/tmp": {"kind": "tmp"}, "/json": {"kind": "json", "content": {"number": 123456789123456789}}},
242 "output_path": "/tmp",
244 "runtime_constraints": {}
247 return ioutil.NopCloser(bytes.NewReader(j)), err
250 func (client *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
251 if resourceType == "collections" {
253 output.(*arvados.Collection).ManifestText = hwManifest
254 } else if uuid == otherPDH {
255 output.(*arvados.Collection).ManifestText = otherManifest
256 } else if uuid == normalizedWithSubdirsPDH {
257 output.(*arvados.Collection).ManifestText = normalizedManifestWithSubdirs
258 } else if uuid == denormalizedWithSubdirsPDH {
259 output.(*arvados.Collection).ManifestText = denormalizedManifestWithSubdirs
262 if resourceType == "containers" {
263 (*output.(*arvados.Container)) = client.Container
268 func (client *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
270 defer client.Mutex.Unlock()
272 client.Content = append(client.Content, parameters)
273 if resourceType == "containers" {
274 if parameters["container"].(arvadosclient.Dict)["state"] == "Running" {
275 client.WasSetRunning = true
281 var discoveryMap = map[string]interface{}{
282 "defaultTrashLifetime": float64(1209600),
283 "crunchLimitLogBytesPerJob": float64(67108864),
284 "crunchLogThrottleBytes": float64(65536),
285 "crunchLogThrottlePeriod": float64(60),
286 "crunchLogThrottleLines": float64(1024),
287 "crunchLogPartialLineThrottlePeriod": float64(5),
288 "crunchLogBytesPerEvent": float64(4096),
289 "crunchLogSecondsBetweenEvents": float64(1),
292 func (client *ArvTestClient) Discovery(key string) (interface{}, error) {
293 return discoveryMap[key], nil
296 // CalledWith returns the parameters from the first API call whose
297 // parameters match jpath/string. E.g., CalledWith(c, "foo.bar",
298 // "baz") returns parameters with parameters["foo"]["bar"]=="baz". If
299 // no call matches, it returns nil.
300 func (client *ArvTestClient) CalledWith(jpath string, expect interface{}) arvadosclient.Dict {
302 for _, content := range client.Content {
303 var v interface{} = content
304 for _, k := range strings.Split(jpath, ".") {
305 if dict, ok := v.(arvadosclient.Dict); !ok {
318 func (client *KeepTestClient) PutHB(hash string, buf []byte) (string, int, error) {
320 return fmt.Sprintf("%s+%d", hash, len(buf)), len(buf), nil
323 func (*KeepTestClient) ClearBlockCache() {
326 type FileWrapper struct {
331 func (fw FileWrapper) Size() int64 {
335 func (fw FileWrapper) Seek(int64, int) (int64, error) {
336 return 0, errors.New("not implemented")
339 func (client *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
340 if filename == hwImageId+".tar" {
341 rdr := ioutil.NopCloser(&bytes.Buffer{})
343 return FileWrapper{rdr, 1321984}, nil
344 } else if filename == "/file1_in_main.txt" {
345 rdr := ioutil.NopCloser(strings.NewReader("foo"))
347 return FileWrapper{rdr, 3}, nil
352 func (s *TestSuite) TestLoadImage(c *C) {
353 kc := &KeepTestClient{}
354 docker := NewTestDockerClient(0)
355 cr := NewContainerRunner(&ArvTestClient{}, kc, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
357 _, err := cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
359 _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
362 cr.Container.ContainerImage = hwPDH
364 // (1) Test loading image from keep
365 c.Check(kc.Called, Equals, false)
366 c.Check(cr.ContainerConfig.Image, Equals, "")
372 cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
375 c.Check(kc.Called, Equals, true)
376 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
378 _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
381 // (2) Test using image that's already loaded
383 cr.ContainerConfig.Image = ""
387 c.Check(kc.Called, Equals, false)
388 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
392 type ArvErrorTestClient struct{}
394 func (ArvErrorTestClient) Create(resourceType string,
395 parameters arvadosclient.Dict,
396 output interface{}) error {
400 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
401 return errors.New("ArvError")
404 func (ArvErrorTestClient) CallRaw(method, resourceType, uuid, action string,
405 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
406 return nil, errors.New("ArvError")
409 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
410 return errors.New("ArvError")
413 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
417 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
418 return discoveryMap[key], nil
421 type KeepErrorTestClient struct{}
423 func (KeepErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
424 return "", 0, errors.New("KeepError")
427 func (KeepErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
428 return nil, errors.New("KeepError")
431 func (KeepErrorTestClient) ClearBlockCache() {
434 type KeepReadErrorTestClient struct{}
436 func (KeepReadErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
440 func (KeepReadErrorTestClient) ClearBlockCache() {
443 type ErrorReader struct{}
445 func (ErrorReader) Read(p []byte) (n int, err error) {
446 return 0, errors.New("ErrorReader")
449 func (ErrorReader) Close() error {
453 func (ErrorReader) Size() int64 {
457 func (ErrorReader) Seek(int64, int) (int64, error) {
458 return 0, errors.New("ErrorReader")
461 func (KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
462 return ErrorReader{}, nil
465 func (s *TestSuite) TestLoadImageArvError(c *C) {
467 cr := NewContainerRunner(ArvErrorTestClient{}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
468 cr.Container.ContainerImage = hwPDH
470 err := cr.LoadImage()
471 c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
474 func (s *TestSuite) TestLoadImageKeepError(c *C) {
476 docker := NewTestDockerClient(0)
477 cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
478 cr.Container.ContainerImage = hwPDH
480 err := cr.LoadImage()
481 c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
484 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
485 // (3) Collection doesn't contain image
486 cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
487 cr.Container.ContainerImage = otherPDH
489 err := cr.LoadImage()
490 c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
493 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
494 // (4) Collection doesn't contain image
495 docker := NewTestDockerClient(0)
496 cr := NewContainerRunner(&ArvTestClient{}, KeepReadErrorTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
497 cr.Container.ContainerImage = hwPDH
499 err := cr.LoadImage()
503 type ClosableBuffer struct {
507 func (*ClosableBuffer) Close() error {
511 type TestLogs struct {
512 Stdout ClosableBuffer
513 Stderr ClosableBuffer
516 func (tl *TestLogs) NewTestLoggingWriter(logstr string) io.WriteCloser {
517 if logstr == "stdout" {
520 if logstr == "stderr" {
526 func dockerLog(fd byte, msg string) []byte {
528 header := make([]byte, 8+len(by))
530 header[7] = byte(len(by))
535 func (s *TestSuite) TestRunContainer(c *C) {
536 docker := NewTestDockerClient(0)
537 docker.fn = func(t *TestDockerClient) {
538 t.logWriter.Write(dockerLog(1, "Hello world\n"))
541 cr := NewContainerRunner(&ArvTestClient{}, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
544 cr.NewLogWriter = logs.NewTestLoggingWriter
545 cr.Container.ContainerImage = hwPDH
546 cr.Container.Command = []string{"./hw"}
547 err := cr.LoadImage()
550 err = cr.CreateContainer()
553 err = cr.StartContainer()
556 err = cr.WaitFinish()
559 c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
560 c.Check(logs.Stderr.String(), Equals, "")
563 func (s *TestSuite) TestCommitLogs(c *C) {
564 api := &ArvTestClient{}
565 kc := &KeepTestClient{}
566 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
567 cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
569 cr.CrunchLog.Print("Hello world!")
570 cr.CrunchLog.Print("Goodbye")
571 cr.finalState = "Complete"
573 err := cr.CommitLogs()
576 c.Check(api.Calls, Equals, 2)
577 c.Check(api.Content[1]["ensure_unique_name"], Equals, true)
578 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
579 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
580 c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
583 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
584 api := &ArvTestClient{}
585 kc := &KeepTestClient{}
586 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
588 err := cr.UpdateContainerRunning()
591 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
594 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
595 api := &ArvTestClient{}
596 kc := &KeepTestClient{}
597 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
599 cr.LogsPDH = new(string)
600 *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
602 cr.ExitCode = new(int)
604 cr.finalState = "Complete"
606 err := cr.UpdateContainerFinal()
609 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
610 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
611 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
614 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
615 api := &ArvTestClient{}
616 kc := &KeepTestClient{}
617 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
619 cr.finalState = "Cancelled"
621 err := cr.UpdateContainerFinal()
624 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
625 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
626 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
629 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
630 // dress rehearsal of the Run() function, starting from a JSON container record.
631 func FullRunHelper(c *C, record string, extraMounts []string, exitCode int, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, realTemp string) {
632 rec := arvados.Container{}
633 err := json.Unmarshal([]byte(record), &rec)
636 docker := NewTestDockerClient(exitCode)
638 docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
640 api = &ArvTestClient{Container: rec}
642 cr = NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
643 cr.statInterval = 100 * time.Millisecond
644 am := &ArvMountCmdLine{}
645 cr.RunArvMount = am.ArvMountTest
647 realTemp, err = ioutil.TempDir("", "crunchrun_test1-")
649 defer os.RemoveAll(realTemp)
651 docker.realTemp = realTemp
654 cr.MkTempDir = func(_ string, prefix string) (string, error) {
656 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, tempcount)
657 err := os.Mkdir(d, os.ModePerm)
658 if err != nil && strings.Contains(err.Error(), ": file exists") {
659 // Test case must have pre-populated the tempdir
665 if extraMounts != nil && len(extraMounts) > 0 {
666 err := cr.SetupArvMountPoint("keep")
669 for _, m := range extraMounts {
670 os.MkdirAll(cr.ArvMountPoint+"/by_id/"+m, os.ModePerm)
675 if api.CalledWith("container.state", "Complete") != nil {
679 c.Check(api.WasSetRunning, Equals, true)
680 c.Check(api.Content[api.Calls-2]["container"].(arvadosclient.Dict)["log"], NotNil)
684 for k, v := range api.Logs {
693 func (s *TestSuite) TestFullRunHello(c *C) {
694 api, _, _ := FullRunHelper(c, `{
695 "command": ["echo", "hello world"],
696 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
699 "mounts": {"/tmp": {"kind": "tmp"} },
700 "output_path": "/tmp",
702 "runtime_constraints": {}
703 }`, nil, 0, func(t *TestDockerClient) {
704 t.logWriter.Write(dockerLog(1, "hello world\n"))
708 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
709 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
710 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
714 func (s *TestSuite) TestCrunchstat(c *C) {
715 api, _, _ := FullRunHelper(c, `{
716 "command": ["sleep", "1"],
717 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
720 "mounts": {"/tmp": {"kind": "tmp"} },
721 "output_path": "/tmp",
723 "runtime_constraints": {}
724 }`, nil, 0, func(t *TestDockerClient) {
725 time.Sleep(time.Second)
729 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
730 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
732 // We didn't actually start a container, so crunchstat didn't
733 // find accounting files and therefore didn't log any stats.
734 // It should have logged a "can't find accounting files"
735 // message after one poll interval, though, so we can confirm
737 c.Assert(api.Logs["crunchstat"], NotNil)
738 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
740 // The "files never appeared" log assures us that we called
741 // (*crunchstat.Reporter)Stop(), and that we set it up with
742 // the correct container ID "abcde":
743 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files never appeared for abcde\n`)
746 func (s *TestSuite) TestNodeInfoLog(c *C) {
747 api, _, _ := FullRunHelper(c, `{
748 "command": ["sleep", "1"],
749 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
752 "mounts": {"/tmp": {"kind": "tmp"} },
753 "output_path": "/tmp",
755 "runtime_constraints": {}
757 func(t *TestDockerClient) {
758 time.Sleep(time.Second)
762 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
763 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
765 c.Assert(api.Logs["node-info"], NotNil)
766 c.Check(api.Logs["node-info"].String(), Matches, `(?ms).*Host Information.*`)
767 c.Check(api.Logs["node-info"].String(), Matches, `(?ms).*CPU Information.*`)
768 c.Check(api.Logs["node-info"].String(), Matches, `(?ms).*Memory Information.*`)
769 c.Check(api.Logs["node-info"].String(), Matches, `(?ms).*Disk Space.*`)
770 c.Check(api.Logs["node-info"].String(), Matches, `(?ms).*Disk INodes.*`)
773 func (s *TestSuite) TestContainerRecordLog(c *C) {
774 api, _, _ := FullRunHelper(c, `{
775 "command": ["sleep", "1"],
776 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
779 "mounts": {"/tmp": {"kind": "tmp"} },
780 "output_path": "/tmp",
782 "runtime_constraints": {}
784 func(t *TestDockerClient) {
785 time.Sleep(time.Second)
789 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
790 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
792 c.Assert(api.Logs["container"], NotNil)
793 c.Check(api.Logs["container"].String(), Matches, `(?ms).*container_image.*`)
796 func (s *TestSuite) TestFullRunStderr(c *C) {
797 api, _, _ := FullRunHelper(c, `{
798 "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
799 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
802 "mounts": {"/tmp": {"kind": "tmp"} },
803 "output_path": "/tmp",
805 "runtime_constraints": {}
806 }`, nil, 1, func(t *TestDockerClient) {
807 t.logWriter.Write(dockerLog(1, "hello\n"))
808 t.logWriter.Write(dockerLog(2, "world\n"))
812 final := api.CalledWith("container.state", "Complete")
813 c.Assert(final, NotNil)
814 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
815 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
817 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
818 c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
821 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
822 api, _, _ := FullRunHelper(c, `{
824 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
827 "mounts": {"/tmp": {"kind": "tmp"} },
828 "output_path": "/tmp",
830 "runtime_constraints": {}
831 }`, nil, 0, func(t *TestDockerClient) {
832 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
836 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
837 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
838 c.Log(api.Logs["stdout"])
839 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
842 func (s *TestSuite) TestFullRunSetCwd(c *C) {
843 api, _, _ := FullRunHelper(c, `{
845 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
848 "mounts": {"/tmp": {"kind": "tmp"} },
849 "output_path": "/tmp",
851 "runtime_constraints": {}
852 }`, nil, 0, func(t *TestDockerClient) {
853 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
857 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
858 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
859 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
862 func (s *TestSuite) TestStopOnSignal(c *C) {
863 s.testStopContainer(c, func(cr *ContainerRunner) {
866 time.Sleep(time.Millisecond)
868 cr.SigChan <- syscall.SIGINT
873 func (s *TestSuite) TestStopOnArvMountDeath(c *C) {
874 s.testStopContainer(c, func(cr *ContainerRunner) {
875 cr.ArvMountExit = make(chan error)
877 cr.ArvMountExit <- exec.Command("true").Run()
878 close(cr.ArvMountExit)
883 func (s *TestSuite) testStopContainer(c *C, setup func(cr *ContainerRunner)) {
885 "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
886 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
889 "mounts": {"/tmp": {"kind": "tmp"} },
890 "output_path": "/tmp",
892 "runtime_constraints": {}
895 rec := arvados.Container{}
896 err := json.Unmarshal([]byte(record), &rec)
899 docker := NewTestDockerClient(0)
900 docker.fn = func(t *TestDockerClient) {
902 t.logWriter.Write(dockerLog(1, "foo\n"))
905 docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
907 api := &ArvTestClient{Container: rec}
908 cr := NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
909 cr.RunArvMount = func([]string, string) (*exec.Cmd, error) { return nil, nil }
912 done := make(chan error)
917 case <-time.After(20 * time.Second):
918 pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
923 for k, v := range api.Logs {
928 c.Check(api.CalledWith("container.log", nil), NotNil)
929 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
930 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "foo\n"), Equals, true)
933 func (s *TestSuite) TestFullRunSetEnv(c *C) {
934 api, _, _ := FullRunHelper(c, `{
935 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
936 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
938 "environment": {"FROBIZ": "bilbo"},
939 "mounts": {"/tmp": {"kind": "tmp"} },
940 "output_path": "/tmp",
942 "runtime_constraints": {}
943 }`, nil, 0, func(t *TestDockerClient) {
944 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
948 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
949 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
950 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)
953 type ArvMountCmdLine struct {
958 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
964 func stubCert(temp string) string {
965 path := temp + "/ca-certificates.crt"
966 crt, _ := os.Create(path)
968 arvadosclient.CertFiles = []string{path}
972 func (s *TestSuite) TestSetupMounts(c *C) {
973 api := &ArvTestClient{}
974 kc := &KeepTestClient{}
975 cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
976 am := &ArvMountCmdLine{}
977 cr.RunArvMount = am.ArvMountTest
979 realTemp, err := ioutil.TempDir("", "crunchrun_test1-")
981 certTemp, err := ioutil.TempDir("", "crunchrun_test2-")
983 stubCertPath := stubCert(certTemp)
985 defer os.RemoveAll(realTemp)
986 defer os.RemoveAll(certTemp)
989 cr.MkTempDir = func(_ string, prefix string) (string, error) {
991 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
992 err := os.Mkdir(d, os.ModePerm)
993 if err != nil && strings.Contains(err.Error(), ": file exists") {
994 // Test case must have pre-populated the tempdir
1000 checkEmpty := func() {
1001 filepath.Walk(realTemp, func(path string, _ os.FileInfo, err error) error {
1002 c.Check(path, Equals, realTemp)
1010 cr.ArvMountPoint = ""
1011 cr.Container.Mounts = make(map[string]arvados.Mount)
1012 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1013 cr.OutputPath = "/tmp"
1014 cr.statInterval = 5 * time.Second
1015 err := cr.SetupMounts()
1017 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1018 "--read-write", "--crunchstat-interval=5",
1019 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1020 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/tmp"})
1021 os.RemoveAll(cr.ArvMountPoint)
1028 cr.ArvMountPoint = ""
1029 cr.Container.Mounts = make(map[string]arvados.Mount)
1030 cr.Container.Mounts["/out"] = arvados.Mount{Kind: "tmp"}
1031 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1032 cr.OutputPath = "/out"
1034 err := cr.SetupMounts()
1036 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1037 "--read-write", "--crunchstat-interval=5",
1038 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1039 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/out", realTemp + "/3:/tmp"})
1040 os.RemoveAll(cr.ArvMountPoint)
1047 cr.ArvMountPoint = ""
1048 cr.Container.Mounts = make(map[string]arvados.Mount)
1049 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1050 cr.OutputPath = "/tmp"
1053 cr.Container.RuntimeConstraints.API = &apiflag
1055 err := cr.SetupMounts()
1057 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1058 "--read-write", "--crunchstat-interval=5",
1059 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1060 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/tmp", stubCertPath + ":/etc/arvados/ca-certificates.crt:ro"})
1061 os.RemoveAll(cr.ArvMountPoint)
1070 cr.ArvMountPoint = ""
1071 cr.Container.Mounts = map[string]arvados.Mount{
1072 "/keeptmp": {Kind: "collection", Writable: true},
1074 cr.OutputPath = "/keeptmp"
1076 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1078 err := cr.SetupMounts()
1080 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1081 "--read-write", "--crunchstat-interval=5",
1082 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1083 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/tmp0:/keeptmp"})
1084 os.RemoveAll(cr.ArvMountPoint)
1091 cr.ArvMountPoint = ""
1092 cr.Container.Mounts = map[string]arvados.Mount{
1093 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1094 "/keepout": {Kind: "collection", Writable: true},
1096 cr.OutputPath = "/keepout"
1098 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1099 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1101 err := cr.SetupMounts()
1103 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1104 "--read-write", "--crunchstat-interval=5",
1105 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1106 sort.StringSlice(cr.Binds).Sort()
1107 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1108 realTemp + "/keep1/tmp0:/keepout"})
1109 os.RemoveAll(cr.ArvMountPoint)
1116 cr.ArvMountPoint = ""
1117 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
1118 cr.Container.Mounts = map[string]arvados.Mount{
1119 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1120 "/keepout": {Kind: "collection", Writable: true},
1122 cr.OutputPath = "/keepout"
1124 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1125 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1127 err := cr.SetupMounts()
1129 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1130 "--read-write", "--crunchstat-interval=5",
1131 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1132 sort.StringSlice(cr.Binds).Sort()
1133 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1134 realTemp + "/keep1/tmp0:/keepout"})
1135 os.RemoveAll(cr.ArvMountPoint)
1140 for _, test := range []struct {
1144 {in: "foo", out: `"foo"`},
1145 {in: nil, out: `null`},
1146 {in: map[string]int64{"foo": 123456789123456789}, out: `{"foo":123456789123456789}`},
1149 cr.ArvMountPoint = ""
1150 cr.Container.Mounts = map[string]arvados.Mount{
1151 "/mnt/test.json": {Kind: "json", Content: test.in},
1153 err := cr.SetupMounts()
1155 sort.StringSlice(cr.Binds).Sort()
1156 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2/mountdata.json:/mnt/test.json:ro"})
1157 content, err := ioutil.ReadFile(realTemp + "/2/mountdata.json")
1159 c.Check(content, DeepEquals, []byte(test.out))
1160 os.RemoveAll(cr.ArvMountPoint)
1165 // Read-only mount points are allowed underneath output_dir mount point
1168 cr.ArvMountPoint = ""
1169 cr.Container.Mounts = make(map[string]arvados.Mount)
1170 cr.Container.Mounts = map[string]arvados.Mount{
1171 "/tmp": {Kind: "tmp"},
1172 "/tmp/foo": {Kind: "collection"},
1174 cr.OutputPath = "/tmp"
1176 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1178 err := cr.SetupMounts()
1180 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1181 "--read-write", "--crunchstat-interval=5",
1182 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1183 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/tmp", realTemp + "/keep1/tmp0:/tmp/foo:ro"})
1184 os.RemoveAll(cr.ArvMountPoint)
1189 // Writable mount points are not allowed underneath output_dir mount point
1192 cr.ArvMountPoint = ""
1193 cr.Container.Mounts = make(map[string]arvados.Mount)
1194 cr.Container.Mounts = map[string]arvados.Mount{
1195 "/tmp": {Kind: "tmp"},
1196 "/tmp/foo": {Kind: "collection", Writable: true},
1198 cr.OutputPath = "/tmp"
1200 err := cr.SetupMounts()
1201 c.Check(err, NotNil)
1202 c.Check(err, ErrorMatches, `Writable mount points are not permitted underneath the output_path.*`)
1203 os.RemoveAll(cr.ArvMountPoint)
1208 // Only mount points of kind 'collection' are allowed underneath output_dir mount point
1211 cr.ArvMountPoint = ""
1212 cr.Container.Mounts = make(map[string]arvados.Mount)
1213 cr.Container.Mounts = map[string]arvados.Mount{
1214 "/tmp": {Kind: "tmp"},
1215 "/tmp/foo": {Kind: "json"},
1217 cr.OutputPath = "/tmp"
1219 err := cr.SetupMounts()
1220 c.Check(err, NotNil)
1221 c.Check(err, ErrorMatches, `Only mount points of kind 'collection' are supported underneath the output_path.*`)
1222 os.RemoveAll(cr.ArvMountPoint)
1227 // Only mount point of kind 'collection' is allowed for stdin
1230 cr.ArvMountPoint = ""
1231 cr.Container.Mounts = make(map[string]arvados.Mount)
1232 cr.Container.Mounts = map[string]arvados.Mount{
1233 "stdin": {Kind: "tmp"},
1236 err := cr.SetupMounts()
1237 c.Check(err, NotNil)
1238 c.Check(err, ErrorMatches, `Unsupported mount kind 'tmp' for stdin.*`)
1239 os.RemoveAll(cr.ArvMountPoint)
1245 func (s *TestSuite) TestStdout(c *C) {
1247 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1248 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1250 "environment": {"FROBIZ": "bilbo"},
1251 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1252 "output_path": "/tmp",
1254 "runtime_constraints": {}
1257 api, _, _ := FullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1258 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1262 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1263 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1264 c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1267 // Used by the TestStdoutWithWrongPath*()
1268 func StdoutErrorRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, err error) {
1269 rec := arvados.Container{}
1270 err = json.Unmarshal([]byte(record), &rec)
1273 docker := NewTestDockerClient(0)
1275 docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
1277 api = &ArvTestClient{Container: rec}
1278 cr = NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1279 am := &ArvMountCmdLine{}
1280 cr.RunArvMount = am.ArvMountTest
1286 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1287 _, _, err := StdoutErrorRunHelper(c, `{
1288 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1289 "output_path": "/tmp"
1290 }`, func(t *TestDockerClient) {})
1292 c.Check(err, NotNil)
1293 c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
1296 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1297 _, _, err := StdoutErrorRunHelper(c, `{
1298 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1299 "output_path": "/tmp"
1300 }`, func(t *TestDockerClient) {})
1302 c.Check(err, NotNil)
1303 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'tmp' for stdout"), Equals, true)
1306 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1307 _, _, err := StdoutErrorRunHelper(c, `{
1308 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1309 "output_path": "/tmp"
1310 }`, func(t *TestDockerClient) {})
1312 c.Check(err, NotNil)
1313 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'collection' for stdout"), Equals, true)
1316 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1317 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1318 defer os.Unsetenv("ARVADOS_API_HOST")
1319 api, _, _ := FullRunHelper(c, `{
1320 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1321 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1324 "mounts": {"/tmp": {"kind": "tmp"} },
1325 "output_path": "/tmp",
1327 "runtime_constraints": {"API": true}
1328 }`, nil, 0, func(t *TestDockerClient) {
1329 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
1333 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1334 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1335 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "test.arvados.org\n"), Equals, true)
1336 c.Check(api.CalledWith("container.output", "d41d8cd98f00b204e9800998ecf8427e+0"), NotNil)
1339 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1340 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1341 defer os.Unsetenv("ARVADOS_API_HOST")
1342 api, _, _ := FullRunHelper(c, `{
1343 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1344 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1347 "mounts": {"/tmp": {"kind": "tmp"} },
1348 "output_path": "/tmp",
1350 "runtime_constraints": {"API": true}
1351 }`, nil, 0, func(t *TestDockerClient) {
1352 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
1356 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1357 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1358 c.Check(api.CalledWith("container.output", "d4ab34d3d4f8a72f5c4973051ae69fab+122"), NotNil)
1361 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1363 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1364 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1366 "environment": {"FROBIZ": "bilbo"},
1368 "/tmp": {"kind": "tmp"},
1369 "/tmp/foo": {"kind": "collection",
1370 "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1371 "exclude_from_output": true
1373 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1375 "output_path": "/tmp",
1377 "runtime_constraints": {}
1380 extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1382 api, _, _ := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1383 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1387 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1388 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1389 c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1392 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1394 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1395 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1397 "environment": {"FROBIZ": "bilbo"},
1399 "/tmp": {"kind": "tmp"},
1400 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1401 "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1402 "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1403 "/tmp/foo/baz/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1404 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1406 "output_path": "/tmp",
1408 "runtime_constraints": {}
1411 extraMounts := []string{
1412 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1413 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1414 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1417 api, runner, realtemp := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1418 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1422 c.Check(runner.Binds, DeepEquals, []string{realtemp + "/2:/tmp",
1423 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt:/tmp/foo/bar:ro",
1424 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt:/tmp/foo/baz/sub2file2:ro",
1425 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1:/tmp/foo/sub1:ro",
1426 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt:/tmp/foo/sub1file2:ro",
1429 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1430 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1431 for _, v := range api.Content {
1432 if v["collection"] != nil {
1433 c.Check(v["ensure_unique_name"], Equals, true)
1434 collection := v["collection"].(arvadosclient.Dict)
1435 if strings.Index(collection["name"].(string), "output") == 0 {
1436 manifest := collection["manifest_text"].(string)
1438 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1439 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 9:18:bar 9:18:sub1file2
1440 ./foo/baz 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2
1441 ./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1442 ./foo/sub1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1449 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
1451 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1452 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1454 "environment": {"FROBIZ": "bilbo"},
1456 "/tmp": {"kind": "tmp"},
1457 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt"},
1458 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1460 "output_path": "/tmp",
1462 "runtime_constraints": {}
1465 extraMounts := []string{
1466 "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1469 api, _, _ := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1470 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1474 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1475 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1476 for _, v := range api.Content {
1477 if v["collection"] != nil {
1478 collection := v["collection"].(arvadosclient.Dict)
1479 if strings.Index(collection["name"].(string), "output") == 0 {
1480 manifest := collection["manifest_text"].(string)
1482 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1483 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 10:17:bar
1490 func (s *TestSuite) TestOutputSymlinkToInput(c *C) {
1492 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1493 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1495 "environment": {"FROBIZ": "bilbo"},
1497 "/tmp": {"kind": "tmp"},
1498 "/keep/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path": "/subdir1/file2_in_subdir1.txt"},
1499 "/keep/foo2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367"}
1501 "output_path": "/tmp",
1503 "runtime_constraints": {}
1506 extraMounts := []string{
1507 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1510 api, _, _ := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1511 os.Symlink("/keep/foo/sub1file2", t.realTemp+"/2/baz")
1512 os.Symlink("/keep/foo2/subdir1/file2_in_subdir1.txt", t.realTemp+"/2/baz2")
1513 os.Symlink("/keep/foo2/subdir1", t.realTemp+"/2/baz3")
1514 os.Mkdir(t.realTemp+"/2/baz4", 0700)
1515 os.Symlink("/keep/foo2/subdir1/file2_in_subdir1.txt", t.realTemp+"/2/baz4/baz5")
1519 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1520 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1521 for _, v := range api.Content {
1522 if v["collection"] != nil {
1523 collection := v["collection"].(arvadosclient.Dict)
1524 if strings.Index(collection["name"].(string), "output") == 0 {
1525 manifest := collection["manifest_text"].(string)
1526 c.Check(manifest, Equals, `. 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:baz 9:18:baz2
1527 ./baz3 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1528 ./baz3/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1529 ./baz4 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:baz5
1536 func (s *TestSuite) TestOutputError(c *C) {
1538 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1539 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1541 "environment": {"FROBIZ": "bilbo"},
1543 "/tmp": {"kind": "tmp"}
1545 "output_path": "/tmp",
1547 "runtime_constraints": {}
1550 extraMounts := []string{}
1552 api, _, _ := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1553 os.Symlink("/etc/hosts", t.realTemp+"/2/baz")
1557 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1560 func (s *TestSuite) TestOutputSymlinkToOutput(c *C) {
1562 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1563 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1565 "environment": {"FROBIZ": "bilbo"},
1567 "/tmp": {"kind": "tmp"}
1569 "output_path": "/tmp",
1571 "runtime_constraints": {}
1574 extraMounts := []string{}
1576 api, _, _ := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1577 rf, _ := os.Create(t.realTemp + "/2/realfile")
1578 rf.Write([]byte("foo"))
1581 os.Mkdir(t.realTemp+"/2/realdir", 0700)
1582 rf, _ = os.Create(t.realTemp + "/2/realdir/subfile")
1583 rf.Write([]byte("bar"))
1586 os.Symlink("/tmp/realfile", t.realTemp+"/2/file1")
1587 os.Symlink("realfile", t.realTemp+"/2/file2")
1588 os.Symlink("/tmp/file1", t.realTemp+"/2/file3")
1589 os.Symlink("file2", t.realTemp+"/2/file4")
1590 os.Symlink("realdir", t.realTemp+"/2/dir1")
1591 os.Symlink("/tmp/realdir", t.realTemp+"/2/dir2")
1595 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1596 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1597 for _, v := range api.Content {
1598 if v["collection"] != nil {
1599 collection := v["collection"].(arvadosclient.Dict)
1600 if strings.Index(collection["name"].(string), "output") == 0 {
1601 manifest := collection["manifest_text"].(string)
1602 c.Check(manifest, Equals,
1603 `. 7a2c86e102dcc231bd232aad99686dfa+15 0:3:file1 3:3:file2 6:3:file3 9:3:file4 12:3:realfile
1604 ./dir1 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1605 ./dir2 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1606 ./realdir 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1613 func (s *TestSuite) TestStdinCollectionMountPoint(c *C) {
1615 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1616 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1618 "environment": {"FROBIZ": "bilbo"},
1620 "/tmp": {"kind": "tmp"},
1621 "stdin": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/file1_in_main.txt"},
1622 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1624 "output_path": "/tmp",
1626 "runtime_constraints": {}
1629 extraMounts := []string{
1630 "b0def87f80dd594d4675809e83bd4f15+367/file1_in_main.txt",
1633 api, _, _ := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1634 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1638 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1639 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1640 for _, v := range api.Content {
1641 if v["collection"] != nil {
1642 collection := v["collection"].(arvadosclient.Dict)
1643 if strings.Index(collection["name"].(string), "output") == 0 {
1644 manifest := collection["manifest_text"].(string)
1645 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1652 func (s *TestSuite) TestStdinJsonMountPoint(c *C) {
1654 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1655 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1657 "environment": {"FROBIZ": "bilbo"},
1659 "/tmp": {"kind": "tmp"},
1660 "stdin": {"kind": "json", "content": "foo"},
1661 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1663 "output_path": "/tmp",
1665 "runtime_constraints": {}
1668 api, _, _ := FullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1669 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1673 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1674 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1675 for _, v := range api.Content {
1676 if v["collection"] != nil {
1677 collection := v["collection"].(arvadosclient.Dict)
1678 if strings.Index(collection["name"].(string), "output") == 0 {
1679 manifest := collection["manifest_text"].(string)
1680 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1687 func (s *TestSuite) TestStderrMount(c *C) {
1688 api, _, _ := FullRunHelper(c, `{
1689 "command": ["/bin/sh", "-c", "echo hello;exit 1"],
1690 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1693 "mounts": {"/tmp": {"kind": "tmp"},
1694 "stdout": {"kind": "file", "path": "/tmp/a/out.txt"},
1695 "stderr": {"kind": "file", "path": "/tmp/b/err.txt"}},
1696 "output_path": "/tmp",
1698 "runtime_constraints": {}
1699 }`, nil, 1, func(t *TestDockerClient) {
1700 t.logWriter.Write(dockerLog(1, "hello\n"))
1701 t.logWriter.Write(dockerLog(2, "oops\n"))
1705 final := api.CalledWith("container.state", "Complete")
1706 c.Assert(final, NotNil)
1707 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1708 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1710 c.Check(api.CalledWith("collection.manifest_text", "./a b1946ac92492d2347c6235b4d2611184+6 0:6:out.txt\n./b 38af5c54926b620264ab1501150cf189+5 0:5:err.txt\n"), NotNil)
1713 func (s *TestSuite) TestNumberRoundTrip(c *C) {
1714 cr := NewContainerRunner(&ArvTestClient{callraw: true}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1715 cr.fetchContainerRecord()
1717 jsondata, err := json.Marshal(cr.Container.Mounts["/json"].Content)
1720 c.Check(string(jsondata), Equals, `{"number":123456789123456789}`)
1723 func (s *TestSuite) TestEvalSymlinks(c *C) {
1724 cr := NewContainerRunner(&ArvTestClient{callraw: true}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1726 realTemp, err := ioutil.TempDir("", "crunchrun_test-")
1727 c.Assert(err, IsNil)
1728 defer os.RemoveAll(realTemp)
1730 cr.HostOutputDir = realTemp
1732 // Absolute path outside output dir
1733 os.Symlink("/etc/passwd", realTemp+"/p1")
1735 // Relative outside output dir
1736 os.Symlink("../zip", realTemp+"/p2")
1738 // Circular references
1739 os.Symlink("p4", realTemp+"/p3")
1740 os.Symlink("p5", realTemp+"/p4")
1741 os.Symlink("p3", realTemp+"/p5")
1743 // Target doesn't exist
1744 os.Symlink("p99", realTemp+"/p6")
1746 for _, v := range []string{"p1", "p2", "p3", "p4", "p5"} {
1747 info, err := os.Lstat(realTemp + "/" + v)
1748 _, _, _, err = cr.derefOutputSymlink(realTemp+"/"+v, info)
1749 c.Assert(err, NotNil)
1753 func (s *TestSuite) TestEvalSymlinkDir(c *C) {
1754 cr := NewContainerRunner(&ArvTestClient{callraw: true}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1756 realTemp, err := ioutil.TempDir("", "crunchrun_test-")
1757 c.Assert(err, IsNil)
1758 defer os.RemoveAll(realTemp)
1760 cr.HostOutputDir = realTemp
1762 // Absolute path outside output dir
1763 os.Symlink(".", realTemp+"/loop")
1766 info, err := os.Lstat(realTemp + "/" + v)
1767 _, err = cr.UploadOutputFile(realTemp+"/"+v, info, err, []string{}, nil, "", "", 0)
1768 c.Assert(err, NotNil)
1771 func (s *TestSuite) TestFullBrokenDocker1(c *C) {
1772 tf, err := ioutil.TempFile("", "brokenNodeHook-")
1773 c.Assert(err, IsNil)
1774 defer os.Remove(tf.Name())
1776 tf.Write([]byte(`#!/bin/sh
1780 os.Chmod(tf.Name(), 0700)
1783 brokenNodeHook = &ech
1785 api, _, _ := FullRunHelper(c, `{
1786 "command": ["echo", "hello world"],
1787 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1790 "mounts": {"/tmp": {"kind": "tmp"} },
1791 "output_path": "/tmp",
1793 "runtime_constraints": {}
1794 }`, nil, 2, func(t *TestDockerClient) {
1795 t.logWriter.Write(dockerLog(1, "hello world\n"))
1799 c.Check(api.CalledWith("container.state", "Queued"), NotNil)
1800 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1801 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Running broken node hook.*")
1802 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*killme.*")
1806 func (s *TestSuite) TestFullBrokenDocker2(c *C) {
1808 brokenNodeHook = &ech
1810 api, _, _ := FullRunHelper(c, `{
1811 "command": ["echo", "hello world"],
1812 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1815 "mounts": {"/tmp": {"kind": "tmp"} },
1816 "output_path": "/tmp",
1818 "runtime_constraints": {}
1819 }`, nil, 2, func(t *TestDockerClient) {
1820 t.logWriter.Write(dockerLog(1, "hello world\n"))
1824 c.Check(api.CalledWith("container.state", "Queued"), NotNil)
1825 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1826 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*No broken node hook.*")