1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
27 "git.curoverse.com/arvados.git/sdk/go/arvados"
28 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
29 "git.curoverse.com/arvados.git/sdk/go/arvadostest"
30 "git.curoverse.com/arvados.git/sdk/go/manifest"
31 "golang.org/x/net/context"
33 dockertypes "github.com/docker/docker/api/types"
34 dockercontainer "github.com/docker/docker/api/types/container"
35 dockernetwork "github.com/docker/docker/api/types/network"
39 // Gocheck boilerplate
40 func TestCrunchExec(t *testing.T) {
44 // Gocheck boilerplate
45 var _ = Suite(&TestSuite{})
47 type TestSuite struct {
48 client *arvados.Client
49 docker *TestDockerClient
52 func (s *TestSuite) SetUpTest(c *C) {
53 s.client = arvados.NewClientFromEnv()
54 s.docker = NewTestDockerClient()
57 type ArvTestClient struct {
60 Content []arvadosclient.Dict
63 Logs map[string]*bytes.Buffer
69 type KeepTestClient struct {
74 var hwManifest = ". 82ab40c24fc8df01798e57ba66795bb1+841216+Aa124ac75e5168396c73c0a18eda641a4f41791c0@569fa8c3 0:841216:9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7.tar\n"
75 var hwPDH = "a45557269dcb65a6b78f9ac061c0850b+120"
76 var hwImageId = "9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7"
78 var otherManifest = ". 68a84f561b1d1708c6baff5e019a9ab3+46+Ae5d0af96944a3690becb1decdf60cc1c937f556d@5693216f 0:46:md5sum.txt\n"
79 var otherPDH = "a3e8f74c6f101eae01fa08bfb4e49b3a+54"
81 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
82 ./subdir1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
83 ./subdir1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
86 var normalizedWithSubdirsPDH = "a0def87f80dd594d4675809e83bd4f15+367"
88 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"
89 var denormalizedWithSubdirsPDH = "b0def87f80dd594d4675809e83bd4f15+367"
91 var fakeAuthUUID = "zzzzz-gj3su-55pqoyepgi2glem"
92 var fakeAuthToken = "a3ltuwzqcu2u4sc0q7yhpc2w7s00fdcqecg5d6e0u3pfohmbjt"
94 type TestDockerClient struct {
96 logReader io.ReadCloser
97 logWriter io.WriteCloser
98 fn func(t *TestDockerClient)
108 func NewTestDockerClient() *TestDockerClient {
109 t := &TestDockerClient{}
110 t.logReader, t.logWriter = io.Pipe()
111 t.stop = make(chan bool, 1)
116 type MockConn struct {
120 func (m *MockConn) Write(b []byte) (int, error) {
124 func NewMockConn() *MockConn {
129 func (t *TestDockerClient) ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error) {
130 return dockertypes.HijackedResponse{Conn: NewMockConn(), Reader: bufio.NewReader(t.logReader)}, nil
133 func (t *TestDockerClient) ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig, networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error) {
134 if config.WorkingDir != "" {
135 t.cwd = config.WorkingDir
138 return dockercontainer.ContainerCreateCreatedBody{ID: "abcde"}, nil
141 func (t *TestDockerClient) ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error {
143 return errors.New(`Error response from daemon: oci runtime error: container_linux.go:247: starting container process caused "process_linux.go:359: container init caused \"rootfs_linux.go:54: mounting \\\"/tmp/keep453790790/by_id/99999999999999999999999999999999+99999/myGenome\\\" to rootfs \\\"/tmp/docker/overlay2/9999999999999999999999999999999999999999999999999999999999999999/merged\\\" at \\\"/tmp/docker/overlay2/9999999999999999999999999999999999999999999999999999999999999999/merged/keep/99999999999999999999999999999999+99999/myGenome\\\" caused \\\"no such file or directory\\\"\""`)
146 return errors.New(`panic: standard_init_linux.go:175: exec user process caused "no such file or directory"`)
149 return errors.New(`Error response from daemon: Cannot start container 41f26cbc43bcc1280f4323efb1830a394ba8660c9d1c2b564ba42bf7f7694845: [8] System error: no such file or directory`)
152 return errors.New(`Error response from daemon: Cannot start container 58099cd76c834f3dc2a4fb76c8028f049ae6d4fdf0ec373e1f2cfea030670c2d: [8] System error: exec: "foobar": executable file not found in $PATH`)
155 if container == "abcde" {
156 // t.fn gets executed in ContainerWait
159 return errors.New("Invalid container id")
163 func (t *TestDockerClient) ContainerRemove(ctx context.Context, container string, options dockertypes.ContainerRemoveOptions) error {
168 func (t *TestDockerClient) ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error) {
170 body := make(chan dockercontainer.ContainerWaitOKBody, 1)
171 err := make(chan error)
174 body <- dockercontainer.ContainerWaitOKBody{StatusCode: int64(t.exitCode)}
179 func (t *TestDockerClient) ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error) {
181 return dockertypes.ImageInspect{}, nil, fmt.Errorf("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?")
184 if t.imageLoaded == image {
185 return dockertypes.ImageInspect{}, nil, nil
187 return dockertypes.ImageInspect{}, nil, errors.New("")
191 func (t *TestDockerClient) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error) {
193 return dockertypes.ImageLoadResponse{}, fmt.Errorf("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?")
195 _, err := io.Copy(ioutil.Discard, input)
197 return dockertypes.ImageLoadResponse{}, err
199 t.imageLoaded = hwImageId
200 return dockertypes.ImageLoadResponse{Body: ioutil.NopCloser(input)}, nil
204 func (*TestDockerClient) ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {
208 func (client *ArvTestClient) Create(resourceType string,
209 parameters arvadosclient.Dict,
210 output interface{}) error {
213 defer client.Mutex.Unlock()
216 client.Content = append(client.Content, parameters)
218 if resourceType == "logs" {
219 et := parameters["log"].(arvadosclient.Dict)["event_type"].(string)
220 if client.Logs == nil {
221 client.Logs = make(map[string]*bytes.Buffer)
223 if client.Logs[et] == nil {
224 client.Logs[et] = &bytes.Buffer{}
226 client.Logs[et].Write([]byte(parameters["log"].(arvadosclient.Dict)["properties"].(map[string]string)["text"]))
229 if resourceType == "collections" && output != nil {
230 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
231 outmap := output.(*arvados.Collection)
232 outmap.PortableDataHash = fmt.Sprintf("%x+%d", md5.Sum([]byte(mt)), len(mt))
238 func (client *ArvTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
240 case method == "GET" && resourceType == "containers" && action == "auth":
241 return json.Unmarshal([]byte(`{
242 "kind": "arvados#api_client_authorization",
243 "uuid": "`+fakeAuthUUID+`",
244 "api_token": "`+fakeAuthToken+`"
246 case method == "GET" && resourceType == "containers" && action == "secret_mounts":
247 if client.secretMounts != nil {
248 return json.Unmarshal(client.secretMounts, output)
250 return json.Unmarshal([]byte(`{"secret_mounts":{}}`), output)
253 return fmt.Errorf("Not found")
257 func (client *ArvTestClient) CallRaw(method, resourceType, uuid, action string,
258 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
260 if method == "GET" && resourceType == "nodes" && uuid == "" && action == "" {
262 "kind": "arvados#nodeList",
264 "uuid": "zzzzz-7ekkf-2z3mc76g2q73aio",
265 "hostname": "compute2",
266 "properties": {"total_cpu_cores": 16}
268 } else if method == "GET" && resourceType == "containers" && action == "" && !client.callraw {
270 j, err = json.Marshal(map[string]interface{}{
271 "items": []interface{}{client.Container},
272 "kind": "arvados#nodeList",
275 j, err = json.Marshal(client.Container)
279 "command": ["sleep", "1"],
280 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
283 "mounts": {"/tmp": {"kind": "tmp"}, "/json": {"kind": "json", "content": {"number": 123456789123456789}}},
284 "output_path": "/tmp",
286 "runtime_constraints": {}
289 return ioutil.NopCloser(bytes.NewReader(j)), err
292 func (client *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
293 if resourceType == "collections" {
295 output.(*arvados.Collection).ManifestText = hwManifest
296 } else if uuid == otherPDH {
297 output.(*arvados.Collection).ManifestText = otherManifest
298 } else if uuid == normalizedWithSubdirsPDH {
299 output.(*arvados.Collection).ManifestText = normalizedManifestWithSubdirs
300 } else if uuid == denormalizedWithSubdirsPDH {
301 output.(*arvados.Collection).ManifestText = denormalizedManifestWithSubdirs
304 if resourceType == "containers" {
305 (*output.(*arvados.Container)) = client.Container
310 func (client *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
312 defer client.Mutex.Unlock()
314 client.Content = append(client.Content, parameters)
315 if resourceType == "containers" {
316 if parameters["container"].(arvadosclient.Dict)["state"] == "Running" {
317 client.WasSetRunning = true
323 var discoveryMap = map[string]interface{}{
324 "defaultTrashLifetime": float64(1209600),
325 "crunchLimitLogBytesPerJob": float64(67108864),
326 "crunchLogThrottleBytes": float64(65536),
327 "crunchLogThrottlePeriod": float64(60),
328 "crunchLogThrottleLines": float64(1024),
329 "crunchLogPartialLineThrottlePeriod": float64(5),
330 "crunchLogBytesPerEvent": float64(4096),
331 "crunchLogSecondsBetweenEvents": float64(1),
334 func (client *ArvTestClient) Discovery(key string) (interface{}, error) {
335 return discoveryMap[key], nil
338 // CalledWith returns the parameters from the first API call whose
339 // parameters match jpath/string. E.g., CalledWith(c, "foo.bar",
340 // "baz") returns parameters with parameters["foo"]["bar"]=="baz". If
341 // no call matches, it returns nil.
342 func (client *ArvTestClient) CalledWith(jpath string, expect interface{}) arvadosclient.Dict {
344 for _, content := range client.Content {
345 var v interface{} = content
346 for _, k := range strings.Split(jpath, ".") {
347 if dict, ok := v.(arvadosclient.Dict); !ok {
360 func (client *KeepTestClient) PutB(buf []byte) (string, int, error) {
362 return fmt.Sprintf("%x+%d", md5.Sum(buf), len(buf)), len(buf), nil
365 func (client *KeepTestClient) ReadAt(string, []byte, int) (int, error) {
366 return 0, errors.New("not implemented")
369 func (client *KeepTestClient) ClearBlockCache() {
372 func (client *KeepTestClient) Close() {
376 type FileWrapper struct {
381 func (fw FileWrapper) Readdir(n int) ([]os.FileInfo, error) {
382 return nil, errors.New("not implemented")
385 func (fw FileWrapper) Seek(int64, int) (int64, error) {
386 return 0, errors.New("not implemented")
389 func (fw FileWrapper) Size() int64 {
393 func (fw FileWrapper) Stat() (os.FileInfo, error) {
394 return nil, errors.New("not implemented")
397 func (fw FileWrapper) Truncate(int64) error {
398 return errors.New("not implemented")
401 func (fw FileWrapper) Write([]byte) (int, error) {
402 return 0, errors.New("not implemented")
405 func (fw FileWrapper) Sync() error {
406 return errors.New("not implemented")
409 func (client *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
410 if filename == hwImageId+".tar" {
411 rdr := ioutil.NopCloser(&bytes.Buffer{})
413 return FileWrapper{rdr, 1321984}, nil
414 } else if filename == "/file1_in_main.txt" {
415 rdr := ioutil.NopCloser(strings.NewReader("foo"))
417 return FileWrapper{rdr, 3}, nil
422 func (s *TestSuite) TestLoadImage(c *C) {
423 kc := &KeepTestClient{}
425 cr, err := NewContainerRunner(s.client, &ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
428 _, err = cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
431 _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
434 cr.Container.ContainerImage = hwPDH
436 // (1) Test loading image from keep
437 c.Check(kc.Called, Equals, false)
438 c.Check(cr.ContainerConfig.Image, Equals, "")
444 cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
447 c.Check(kc.Called, Equals, true)
448 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
450 _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
453 // (2) Test using image that's already loaded
455 cr.ContainerConfig.Image = ""
459 c.Check(kc.Called, Equals, false)
460 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
464 type ArvErrorTestClient struct{}
466 func (ArvErrorTestClient) Create(resourceType string,
467 parameters arvadosclient.Dict,
468 output interface{}) error {
472 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
473 return errors.New("ArvError")
476 func (ArvErrorTestClient) CallRaw(method, resourceType, uuid, action string,
477 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
478 return nil, errors.New("ArvError")
481 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
482 return errors.New("ArvError")
485 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
489 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
490 return discoveryMap[key], nil
493 type KeepErrorTestClient struct {
497 func (*KeepErrorTestClient) ManifestFileReader(manifest.Manifest, string) (arvados.File, error) {
498 return nil, errors.New("KeepError")
501 func (*KeepErrorTestClient) PutB(buf []byte) (string, int, error) {
502 return "", 0, errors.New("KeepError")
505 type KeepReadErrorTestClient struct {
509 func (*KeepReadErrorTestClient) ReadAt(string, []byte, int) (int, error) {
510 return 0, errors.New("KeepError")
513 type ErrorReader struct {
517 func (ErrorReader) Read(p []byte) (n int, err error) {
518 return 0, errors.New("ErrorReader")
521 func (ErrorReader) Seek(int64, int) (int64, error) {
522 return 0, errors.New("ErrorReader")
525 func (KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
526 return ErrorReader{}, nil
529 func (s *TestSuite) TestLoadImageArvError(c *C) {
531 kc := &KeepTestClient{}
533 cr, err := NewContainerRunner(s.client, ArvErrorTestClient{}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
535 cr.Container.ContainerImage = hwPDH
538 c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
541 func (s *TestSuite) TestLoadImageKeepError(c *C) {
543 cr, err := NewContainerRunner(s.client, &ArvTestClient{}, &KeepErrorTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
545 cr.Container.ContainerImage = hwPDH
548 c.Assert(err, NotNil)
549 c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
552 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
553 // (3) Collection doesn't contain image
554 cr, err := NewContainerRunner(s.client, &ArvTestClient{}, &KeepReadErrorTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
556 cr.Container.ContainerImage = otherPDH
559 c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
562 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
563 // (4) Collection doesn't contain image
564 cr, err := NewContainerRunner(s.client, &ArvTestClient{}, &KeepReadErrorTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
566 cr.Container.ContainerImage = hwPDH
572 type ClosableBuffer struct {
576 func (*ClosableBuffer) Close() error {
580 type TestLogs struct {
581 Stdout ClosableBuffer
582 Stderr ClosableBuffer
585 func (tl *TestLogs) NewTestLoggingWriter(logstr string) (io.WriteCloser, error) {
586 if logstr == "stdout" {
587 return &tl.Stdout, nil
589 if logstr == "stderr" {
590 return &tl.Stderr, nil
592 return nil, errors.New("???")
595 func dockerLog(fd byte, msg string) []byte {
597 header := make([]byte, 8+len(by))
599 header[7] = byte(len(by))
604 func (s *TestSuite) TestRunContainer(c *C) {
605 s.docker.fn = func(t *TestDockerClient) {
606 t.logWriter.Write(dockerLog(1, "Hello world\n"))
609 kc := &KeepTestClient{}
611 cr, err := NewContainerRunner(s.client, &ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
615 cr.NewLogWriter = logs.NewTestLoggingWriter
616 cr.Container.ContainerImage = hwPDH
617 cr.Container.Command = []string{"./hw"}
621 err = cr.CreateContainer()
624 err = cr.StartContainer()
627 err = cr.WaitFinish()
630 c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
631 c.Check(logs.Stderr.String(), Equals, "")
634 func (s *TestSuite) TestCommitLogs(c *C) {
635 api := &ArvTestClient{}
636 kc := &KeepTestClient{}
638 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
640 cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
642 cr.CrunchLog.Print("Hello world!")
643 cr.CrunchLog.Print("Goodbye")
644 cr.finalState = "Complete"
646 err = cr.CommitLogs()
649 c.Check(api.Calls, Equals, 2)
650 c.Check(api.Content[1]["ensure_unique_name"], Equals, true)
651 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
652 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
653 c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
656 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
657 api := &ArvTestClient{}
658 kc := &KeepTestClient{}
660 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
663 err = cr.UpdateContainerRunning()
666 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
669 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
670 api := &ArvTestClient{}
671 kc := &KeepTestClient{}
673 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
676 cr.LogsPDH = new(string)
677 *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
679 cr.ExitCode = new(int)
681 cr.finalState = "Complete"
683 err = cr.UpdateContainerFinal()
686 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
687 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
688 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
691 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
692 api := &ArvTestClient{}
693 kc := &KeepTestClient{}
695 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
698 cr.finalState = "Cancelled"
700 err = cr.UpdateContainerFinal()
703 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
704 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
705 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
708 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
709 // dress rehearsal of the Run() function, starting from a JSON container record.
710 func (s *TestSuite) fullRunHelper(c *C, record string, extraMounts []string, exitCode int, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, realTemp string) {
711 rec := arvados.Container{}
712 err := json.Unmarshal([]byte(record), &rec)
716 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
718 err = json.Unmarshal([]byte(record), &sm)
720 secretMounts, err := json.Marshal(sm)
721 c.Logf("%s %q", sm, secretMounts)
724 s.docker.exitCode = exitCode
726 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
728 api = &ArvTestClient{Container: rec}
730 kc := &KeepTestClient{}
732 cr, err = NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
734 cr.statInterval = 100 * time.Millisecond
735 am := &ArvMountCmdLine{}
736 cr.RunArvMount = am.ArvMountTest
738 realTemp, err = ioutil.TempDir("", "crunchrun_test1-")
740 defer os.RemoveAll(realTemp)
742 s.docker.realTemp = realTemp
745 cr.MkTempDir = func(_ string, prefix string) (string, error) {
747 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, tempcount)
748 err := os.Mkdir(d, os.ModePerm)
749 if err != nil && strings.Contains(err.Error(), ": file exists") {
750 // Test case must have pre-populated the tempdir
755 cr.MkArvClient = func(token string) (IArvadosClient, error) {
756 return &ArvTestClient{secretMounts: secretMounts}, nil
759 if extraMounts != nil && len(extraMounts) > 0 {
760 err := cr.SetupArvMountPoint("keep")
763 for _, m := range extraMounts {
764 os.MkdirAll(cr.ArvMountPoint+"/by_id/"+m, os.ModePerm)
769 if api.CalledWith("container.state", "Complete") != nil {
773 c.Check(api.WasSetRunning, Equals, true)
774 c.Check(api.Content[api.Calls-2]["container"].(arvadosclient.Dict)["log"], NotNil)
778 for k, v := range api.Logs {
787 func (s *TestSuite) TestFullRunHello(c *C) {
788 api, _, _ := s.fullRunHelper(c, `{
789 "command": ["echo", "hello world"],
790 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
793 "mounts": {"/tmp": {"kind": "tmp"} },
794 "output_path": "/tmp",
796 "runtime_constraints": {}
797 }`, nil, 0, func(t *TestDockerClient) {
798 t.logWriter.Write(dockerLog(1, "hello world\n"))
802 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
803 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
804 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
808 func (s *TestSuite) TestRunTimeExceeded(c *C) {
809 api, _, _ := s.fullRunHelper(c, `{
810 "command": ["sleep", "3"],
811 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
814 "mounts": {"/tmp": {"kind": "tmp"} },
815 "output_path": "/tmp",
817 "runtime_constraints": {},
818 "scheduling_parameters":{"max_run_time": 1}
819 }`, nil, 0, func(t *TestDockerClient) {
820 time.Sleep(3 * time.Second)
824 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
825 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*maximum run time exceeded.*")
828 func (s *TestSuite) TestCrunchstat(c *C) {
829 api, _, _ := s.fullRunHelper(c, `{
830 "command": ["sleep", "1"],
831 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
834 "mounts": {"/tmp": {"kind": "tmp"} },
835 "output_path": "/tmp",
837 "runtime_constraints": {}
838 }`, nil, 0, func(t *TestDockerClient) {
839 time.Sleep(time.Second)
843 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
844 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
846 // We didn't actually start a container, so crunchstat didn't
847 // find accounting files and therefore didn't log any stats.
848 // It should have logged a "can't find accounting files"
849 // message after one poll interval, though, so we can confirm
851 c.Assert(api.Logs["crunchstat"], NotNil)
852 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
854 // The "files never appeared" log assures us that we called
855 // (*crunchstat.Reporter)Stop(), and that we set it up with
856 // the correct container ID "abcde":
857 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files never appeared for abcde\n`)
860 func (s *TestSuite) TestNodeInfoLog(c *C) {
861 os.Setenv("SLURMD_NODENAME", "compute2")
862 api, _, _ := s.fullRunHelper(c, `{
863 "command": ["sleep", "1"],
864 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
867 "mounts": {"/tmp": {"kind": "tmp"} },
868 "output_path": "/tmp",
870 "runtime_constraints": {}
872 func(t *TestDockerClient) {
873 time.Sleep(time.Second)
877 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
878 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
880 c.Assert(api.Logs["node"], NotNil)
881 json := api.Logs["node"].String()
882 c.Check(json, Matches, `(?ms).*"uuid": *"zzzzz-7ekkf-2z3mc76g2q73aio".*`)
883 c.Check(json, Matches, `(?ms).*"total_cpu_cores": *16.*`)
884 c.Check(json, Not(Matches), `(?ms).*"info":.*`)
886 c.Assert(api.Logs["node-info"], NotNil)
887 json = api.Logs["node-info"].String()
888 c.Check(json, Matches, `(?ms).*Host Information.*`)
889 c.Check(json, Matches, `(?ms).*CPU Information.*`)
890 c.Check(json, Matches, `(?ms).*Memory Information.*`)
891 c.Check(json, Matches, `(?ms).*Disk Space.*`)
892 c.Check(json, Matches, `(?ms).*Disk INodes.*`)
895 func (s *TestSuite) TestContainerRecordLog(c *C) {
896 api, _, _ := s.fullRunHelper(c, `{
897 "command": ["sleep", "1"],
898 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
901 "mounts": {"/tmp": {"kind": "tmp"} },
902 "output_path": "/tmp",
904 "runtime_constraints": {}
906 func(t *TestDockerClient) {
907 time.Sleep(time.Second)
911 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
912 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
914 c.Assert(api.Logs["container"], NotNil)
915 c.Check(api.Logs["container"].String(), Matches, `(?ms).*container_image.*`)
918 func (s *TestSuite) TestFullRunStderr(c *C) {
919 api, _, _ := s.fullRunHelper(c, `{
920 "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
921 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
924 "mounts": {"/tmp": {"kind": "tmp"} },
925 "output_path": "/tmp",
927 "runtime_constraints": {}
928 }`, nil, 1, func(t *TestDockerClient) {
929 t.logWriter.Write(dockerLog(1, "hello\n"))
930 t.logWriter.Write(dockerLog(2, "world\n"))
934 final := api.CalledWith("container.state", "Complete")
935 c.Assert(final, NotNil)
936 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
937 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
939 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
940 c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
943 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
944 api, _, _ := s.fullRunHelper(c, `{
946 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
949 "mounts": {"/tmp": {"kind": "tmp"} },
950 "output_path": "/tmp",
952 "runtime_constraints": {}
953 }`, nil, 0, func(t *TestDockerClient) {
954 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
958 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
959 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
960 c.Log(api.Logs["stdout"])
961 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
964 func (s *TestSuite) TestFullRunSetCwd(c *C) {
965 api, _, _ := s.fullRunHelper(c, `{
967 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
970 "mounts": {"/tmp": {"kind": "tmp"} },
971 "output_path": "/tmp",
973 "runtime_constraints": {}
974 }`, nil, 0, func(t *TestDockerClient) {
975 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
979 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
980 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
981 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
984 func (s *TestSuite) TestStopOnSignal(c *C) {
985 s.testStopContainer(c, func(cr *ContainerRunner) {
987 for !s.docker.calledWait {
988 time.Sleep(time.Millisecond)
990 cr.SigChan <- syscall.SIGINT
995 func (s *TestSuite) TestStopOnArvMountDeath(c *C) {
996 s.testStopContainer(c, func(cr *ContainerRunner) {
997 cr.ArvMountExit = make(chan error)
999 cr.ArvMountExit <- exec.Command("true").Run()
1000 close(cr.ArvMountExit)
1005 func (s *TestSuite) testStopContainer(c *C, setup func(cr *ContainerRunner)) {
1007 "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
1008 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1011 "mounts": {"/tmp": {"kind": "tmp"} },
1012 "output_path": "/tmp",
1014 "runtime_constraints": {}
1017 rec := arvados.Container{}
1018 err := json.Unmarshal([]byte(record), &rec)
1021 s.docker.fn = func(t *TestDockerClient) {
1023 t.logWriter.Write(dockerLog(1, "foo\n"))
1026 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
1028 api := &ArvTestClient{Container: rec}
1029 kc := &KeepTestClient{}
1031 cr, err := NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1032 c.Assert(err, IsNil)
1033 cr.RunArvMount = func([]string, string) (*exec.Cmd, error) { return nil, nil }
1034 cr.MkArvClient = func(token string) (IArvadosClient, error) {
1035 return &ArvTestClient{}, nil
1039 done := make(chan error)
1044 case <-time.After(20 * time.Second):
1045 pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
1046 c.Fatal("timed out")
1050 for k, v := range api.Logs {
1055 c.Check(api.CalledWith("container.log", nil), NotNil)
1056 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1057 c.Check(api.Logs["stdout"].String(), Matches, "(?ms).*foo\n$")
1060 func (s *TestSuite) TestFullRunSetEnv(c *C) {
1061 api, _, _ := s.fullRunHelper(c, `{
1062 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1063 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1065 "environment": {"FROBIZ": "bilbo"},
1066 "mounts": {"/tmp": {"kind": "tmp"} },
1067 "output_path": "/tmp",
1069 "runtime_constraints": {}
1070 }`, nil, 0, func(t *TestDockerClient) {
1071 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1075 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1076 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1077 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)
1080 type ArvMountCmdLine struct {
1085 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
1091 func stubCert(temp string) string {
1092 path := temp + "/ca-certificates.crt"
1093 crt, _ := os.Create(path)
1095 arvadosclient.CertFiles = []string{path}
1099 func (s *TestSuite) TestSetupMounts(c *C) {
1100 api := &ArvTestClient{}
1101 kc := &KeepTestClient{}
1103 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1104 c.Assert(err, IsNil)
1105 am := &ArvMountCmdLine{}
1106 cr.RunArvMount = am.ArvMountTest
1108 realTemp, err := ioutil.TempDir("", "crunchrun_test1-")
1109 c.Assert(err, IsNil)
1110 certTemp, err := ioutil.TempDir("", "crunchrun_test2-")
1111 c.Assert(err, IsNil)
1112 stubCertPath := stubCert(certTemp)
1114 cr.parentTemp = realTemp
1116 defer os.RemoveAll(realTemp)
1117 defer os.RemoveAll(certTemp)
1120 cr.MkTempDir = func(_ string, prefix string) (string, error) {
1122 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
1123 err := os.Mkdir(d, os.ModePerm)
1124 if err != nil && strings.Contains(err.Error(), ": file exists") {
1125 // Test case must have pre-populated the tempdir
1131 checkEmpty := func() {
1132 // Should be deleted.
1133 _, err := os.Stat(realTemp)
1134 c.Assert(os.IsNotExist(err), Equals, true)
1136 // Now recreate it for the next test.
1137 c.Assert(os.Mkdir(realTemp, 0777), IsNil)
1142 cr.ArvMountPoint = ""
1143 cr.Container.Mounts = make(map[string]arvados.Mount)
1144 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1145 cr.OutputPath = "/tmp"
1146 cr.statInterval = 5 * time.Second
1147 err := cr.SetupMounts()
1149 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1150 "--read-write", "--crunchstat-interval=5",
1151 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1152 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp"})
1153 os.RemoveAll(cr.ArvMountPoint)
1160 cr.ArvMountPoint = ""
1161 cr.Container.Mounts = make(map[string]arvados.Mount)
1162 cr.Container.Mounts["/out"] = arvados.Mount{Kind: "tmp"}
1163 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1164 cr.OutputPath = "/out"
1166 err := cr.SetupMounts()
1168 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1169 "--read-write", "--crunchstat-interval=5",
1170 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1171 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/out", realTemp + "/tmp3:/tmp"})
1172 os.RemoveAll(cr.ArvMountPoint)
1179 cr.ArvMountPoint = ""
1180 cr.Container.Mounts = make(map[string]arvados.Mount)
1181 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1182 cr.OutputPath = "/tmp"
1185 cr.Container.RuntimeConstraints.API = &apiflag
1187 err := cr.SetupMounts()
1189 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1190 "--read-write", "--crunchstat-interval=5",
1191 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1192 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", stubCertPath + ":/etc/arvados/ca-certificates.crt:ro"})
1193 os.RemoveAll(cr.ArvMountPoint)
1202 cr.ArvMountPoint = ""
1203 cr.Container.Mounts = map[string]arvados.Mount{
1204 "/keeptmp": {Kind: "collection", Writable: true},
1206 cr.OutputPath = "/keeptmp"
1208 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1210 err := cr.SetupMounts()
1212 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1213 "--read-write", "--crunchstat-interval=5",
1214 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1215 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/tmp0:/keeptmp"})
1216 os.RemoveAll(cr.ArvMountPoint)
1223 cr.ArvMountPoint = ""
1224 cr.Container.Mounts = map[string]arvados.Mount{
1225 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1226 "/keepout": {Kind: "collection", Writable: true},
1228 cr.OutputPath = "/keepout"
1230 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1231 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1233 err := cr.SetupMounts()
1235 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1236 "--read-write", "--crunchstat-interval=5",
1237 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1238 sort.StringSlice(cr.Binds).Sort()
1239 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1240 realTemp + "/keep1/tmp0:/keepout"})
1241 os.RemoveAll(cr.ArvMountPoint)
1248 cr.ArvMountPoint = ""
1249 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
1250 cr.Container.Mounts = map[string]arvados.Mount{
1251 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1252 "/keepout": {Kind: "collection", Writable: true},
1254 cr.OutputPath = "/keepout"
1256 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1257 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1259 err := cr.SetupMounts()
1261 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1262 "--read-write", "--crunchstat-interval=5",
1263 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1264 sort.StringSlice(cr.Binds).Sort()
1265 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1266 realTemp + "/keep1/tmp0:/keepout"})
1267 os.RemoveAll(cr.ArvMountPoint)
1272 for _, test := range []struct {
1276 {in: "foo", out: `"foo"`},
1277 {in: nil, out: `null`},
1278 {in: map[string]int64{"foo": 123456789123456789}, out: `{"foo":123456789123456789}`},
1281 cr.ArvMountPoint = ""
1282 cr.Container.Mounts = map[string]arvados.Mount{
1283 "/mnt/test.json": {Kind: "json", Content: test.in},
1285 err := cr.SetupMounts()
1287 sort.StringSlice(cr.Binds).Sort()
1288 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/json2/mountdata.json:/mnt/test.json:ro"})
1289 content, err := ioutil.ReadFile(realTemp + "/json2/mountdata.json")
1291 c.Check(content, DeepEquals, []byte(test.out))
1292 os.RemoveAll(cr.ArvMountPoint)
1297 for _, test := range []struct {
1301 {in: "foo", out: `foo`},
1302 {in: nil, out: "error"},
1303 {in: map[string]int64{"foo": 123456789123456789}, out: "error"},
1306 cr.ArvMountPoint = ""
1307 cr.Container.Mounts = map[string]arvados.Mount{
1308 "/mnt/test.txt": {Kind: "text", Content: test.in},
1310 err := cr.SetupMounts()
1311 if test.out == "error" {
1312 c.Check(err.Error(), Equals, "content for mount \"/mnt/test.txt\" must be a string")
1315 sort.StringSlice(cr.Binds).Sort()
1316 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/text2/mountdata.text:/mnt/test.txt:ro"})
1317 content, err := ioutil.ReadFile(realTemp + "/text2/mountdata.text")
1319 c.Check(content, DeepEquals, []byte(test.out))
1321 os.RemoveAll(cr.ArvMountPoint)
1326 // Read-only mount points are allowed underneath output_dir mount point
1329 cr.ArvMountPoint = ""
1330 cr.Container.Mounts = make(map[string]arvados.Mount)
1331 cr.Container.Mounts = map[string]arvados.Mount{
1332 "/tmp": {Kind: "tmp"},
1333 "/tmp/foo": {Kind: "collection"},
1335 cr.OutputPath = "/tmp"
1337 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1339 err := cr.SetupMounts()
1341 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1342 "--read-write", "--crunchstat-interval=5",
1343 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1344 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", realTemp + "/keep1/tmp0:/tmp/foo:ro"})
1345 os.RemoveAll(cr.ArvMountPoint)
1350 // Writable mount points copied to output_dir mount point
1353 cr.ArvMountPoint = ""
1354 cr.Container.Mounts = make(map[string]arvados.Mount)
1355 cr.Container.Mounts = map[string]arvados.Mount{
1356 "/tmp": {Kind: "tmp"},
1357 "/tmp/foo": {Kind: "collection",
1358 PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53",
1360 "/tmp/bar": {Kind: "collection",
1361 PortableDataHash: "59389a8f9ee9d399be35462a0f92541d+53",
1365 cr.OutputPath = "/tmp"
1367 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1368 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz", os.ModePerm)
1370 rf, _ := os.Create(realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz/quux")
1371 rf.Write([]byte("bar"))
1374 err := cr.SetupMounts()
1376 _, err = os.Stat(cr.HostOutputDir + "/foo")
1378 _, err = os.Stat(cr.HostOutputDir + "/bar/quux")
1380 os.RemoveAll(cr.ArvMountPoint)
1385 // Only mount points of kind 'collection' are allowed underneath output_dir mount point
1388 cr.ArvMountPoint = ""
1389 cr.Container.Mounts = make(map[string]arvados.Mount)
1390 cr.Container.Mounts = map[string]arvados.Mount{
1391 "/tmp": {Kind: "tmp"},
1392 "/tmp/foo": {Kind: "tmp"},
1394 cr.OutputPath = "/tmp"
1396 err := cr.SetupMounts()
1397 c.Check(err, NotNil)
1398 c.Check(err, ErrorMatches, `Only mount points of kind 'collection', 'text' or 'json' are supported underneath the output_path.*`)
1399 os.RemoveAll(cr.ArvMountPoint)
1404 // Only mount point of kind 'collection' is allowed for stdin
1407 cr.ArvMountPoint = ""
1408 cr.Container.Mounts = make(map[string]arvados.Mount)
1409 cr.Container.Mounts = map[string]arvados.Mount{
1410 "stdin": {Kind: "tmp"},
1413 err := cr.SetupMounts()
1414 c.Check(err, NotNil)
1415 c.Check(err, ErrorMatches, `Unsupported mount kind 'tmp' for stdin.*`)
1416 os.RemoveAll(cr.ArvMountPoint)
1424 cr.ArvMountPoint = ""
1425 (*GitMountSuite)(nil).useTestGitServer(c)
1426 cr.token = arvadostest.ActiveToken
1427 cr.Container.Mounts = make(map[string]arvados.Mount)
1428 cr.Container.Mounts = map[string]arvados.Mount{
1431 UUID: arvadostest.Repository2UUID,
1432 Commit: "fd3531f42995344f36c30b79f55f27b502f3d344",
1437 UUID: arvadostest.Repository2UUID,
1438 Commit: "5ebfab0522851df01fec11ec55a6d0f4877b542e",
1442 cr.OutputPath = "/tmp"
1444 err := cr.SetupMounts()
1447 // dirMap[mountpoint] == tmpdir
1448 dirMap := make(map[string]string)
1449 for _, bind := range cr.Binds {
1450 tokens := strings.Split(bind, ":")
1451 dirMap[tokens[1]] = tokens[0]
1453 if cr.Container.Mounts[tokens[1]].Writable {
1454 c.Check(len(tokens), Equals, 2)
1456 c.Check(len(tokens), Equals, 3)
1457 c.Check(tokens[2], Equals, "ro")
1461 data, err := ioutil.ReadFile(dirMap["/tip"] + "/dir1/dir2/file with mode 0644")
1463 c.Check(string(data), Equals, "\000\001\002\003")
1464 _, err = ioutil.ReadFile(dirMap["/tip"] + "/file only on testbranch")
1465 c.Check(err, FitsTypeOf, &os.PathError{})
1466 c.Check(os.IsNotExist(err), Equals, true)
1468 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/dir1/dir2/file with mode 0644")
1470 c.Check(string(data), Equals, "\000\001\002\003")
1471 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/file only on testbranch")
1473 c.Check(string(data), Equals, "testfile\n")
1480 func (s *TestSuite) TestStdout(c *C) {
1482 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1483 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1485 "environment": {"FROBIZ": "bilbo"},
1486 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1487 "output_path": "/tmp",
1489 "runtime_constraints": {}
1492 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1493 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1497 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1498 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1499 c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1502 // Used by the TestStdoutWithWrongPath*()
1503 func (s *TestSuite) stdoutErrorRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, err error) {
1504 rec := arvados.Container{}
1505 err = json.Unmarshal([]byte(record), &rec)
1509 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
1511 api = &ArvTestClient{Container: rec}
1512 kc := &KeepTestClient{}
1514 cr, err = NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1515 c.Assert(err, IsNil)
1516 am := &ArvMountCmdLine{}
1517 cr.RunArvMount = am.ArvMountTest
1518 cr.MkArvClient = func(token string) (IArvadosClient, error) {
1519 return &ArvTestClient{}, nil
1526 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1527 _, _, err := s.stdoutErrorRunHelper(c, `{
1528 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1529 "output_path": "/tmp"
1530 }`, func(t *TestDockerClient) {})
1532 c.Check(err, NotNil)
1533 c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
1536 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1537 _, _, err := s.stdoutErrorRunHelper(c, `{
1538 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1539 "output_path": "/tmp"
1540 }`, func(t *TestDockerClient) {})
1542 c.Check(err, NotNil)
1543 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'tmp' for stdout"), Equals, true)
1546 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1547 _, _, err := s.stdoutErrorRunHelper(c, `{
1548 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1549 "output_path": "/tmp"
1550 }`, func(t *TestDockerClient) {})
1552 c.Check(err, NotNil)
1553 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'collection' for stdout"), Equals, true)
1556 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1557 defer os.Setenv("ARVADOS_API_HOST", os.Getenv("ARVADOS_API_HOST"))
1558 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1559 api, _, _ := s.fullRunHelper(c, `{
1560 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1561 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1564 "mounts": {"/tmp": {"kind": "tmp"} },
1565 "output_path": "/tmp",
1567 "runtime_constraints": {"API": true}
1568 }`, nil, 0, func(t *TestDockerClient) {
1569 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
1573 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1574 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1575 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "test.arvados.org\n"), Equals, true)
1576 c.Check(api.CalledWith("container.output", "d41d8cd98f00b204e9800998ecf8427e+0"), NotNil)
1579 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1580 defer os.Setenv("ARVADOS_API_HOST", os.Getenv("ARVADOS_API_HOST"))
1581 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1582 api, _, _ := s.fullRunHelper(c, `{
1583 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1584 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1587 "mounts": {"/tmp": {"kind": "tmp"} },
1588 "output_path": "/tmp",
1590 "runtime_constraints": {"API": true}
1591 }`, nil, 0, func(t *TestDockerClient) {
1592 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
1596 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1597 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1598 c.Check(api.CalledWith("container.output", "d4ab34d3d4f8a72f5c4973051ae69fab+122"), NotNil)
1601 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1603 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1604 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1606 "environment": {"FROBIZ": "bilbo"},
1608 "/tmp": {"kind": "tmp"},
1609 "/tmp/foo": {"kind": "collection",
1610 "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1611 "exclude_from_output": true
1613 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1615 "output_path": "/tmp",
1617 "runtime_constraints": {}
1620 extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1622 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1623 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1627 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1628 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1629 c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1632 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1634 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1635 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1637 "environment": {"FROBIZ": "bilbo"},
1639 "/tmp": {"kind": "tmp"},
1640 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1641 "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1642 "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1643 "/tmp/foo/baz/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1644 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1646 "output_path": "/tmp",
1648 "runtime_constraints": {}
1651 extraMounts := []string{
1652 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1653 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1654 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1657 api, runner, realtemp := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1658 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1662 c.Check(runner.Binds, DeepEquals, []string{realtemp + "/tmp2:/tmp",
1663 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt:/tmp/foo/bar:ro",
1664 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt:/tmp/foo/baz/sub2file2:ro",
1665 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1:/tmp/foo/sub1:ro",
1666 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt:/tmp/foo/sub1file2:ro",
1669 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1670 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1671 for _, v := range api.Content {
1672 if v["collection"] != nil {
1673 c.Check(v["ensure_unique_name"], Equals, true)
1674 collection := v["collection"].(arvadosclient.Dict)
1675 if strings.Index(collection["name"].(string), "output") == 0 {
1676 manifest := collection["manifest_text"].(string)
1678 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1679 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:bar 36:18:sub1file2
1680 ./foo/baz 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2
1681 ./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1682 ./foo/sub1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1689 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
1691 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1692 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1694 "environment": {"FROBIZ": "bilbo"},
1696 "/tmp": {"kind": "tmp"},
1697 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/subdir1/file2_in_subdir1.txt"},
1698 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1700 "output_path": "/tmp",
1702 "runtime_constraints": {}
1705 extraMounts := []string{
1706 "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1709 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1710 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1714 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1715 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1716 for _, v := range api.Content {
1717 if v["collection"] != nil {
1718 collection := v["collection"].(arvadosclient.Dict)
1719 if strings.Index(collection["name"].(string), "output") == 0 {
1720 manifest := collection["manifest_text"].(string)
1722 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1723 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 10:17:bar
1730 func (s *TestSuite) TestOutputError(c *C) {
1732 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1733 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1735 "environment": {"FROBIZ": "bilbo"},
1737 "/tmp": {"kind": "tmp"}
1739 "output_path": "/tmp",
1741 "runtime_constraints": {}
1744 extraMounts := []string{}
1746 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1747 os.Symlink("/etc/hosts", t.realTemp+"/tmp2/baz")
1751 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1754 func (s *TestSuite) TestStdinCollectionMountPoint(c *C) {
1756 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1757 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1759 "environment": {"FROBIZ": "bilbo"},
1761 "/tmp": {"kind": "tmp"},
1762 "stdin": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/file1_in_main.txt"},
1763 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1765 "output_path": "/tmp",
1767 "runtime_constraints": {}
1770 extraMounts := []string{
1771 "b0def87f80dd594d4675809e83bd4f15+367/file1_in_main.txt",
1774 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1775 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1779 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1780 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1781 for _, v := range api.Content {
1782 if v["collection"] != nil {
1783 collection := v["collection"].(arvadosclient.Dict)
1784 if strings.Index(collection["name"].(string), "output") == 0 {
1785 manifest := collection["manifest_text"].(string)
1786 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1793 func (s *TestSuite) TestStdinJsonMountPoint(c *C) {
1795 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1796 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1798 "environment": {"FROBIZ": "bilbo"},
1800 "/tmp": {"kind": "tmp"},
1801 "stdin": {"kind": "json", "content": "foo"},
1802 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1804 "output_path": "/tmp",
1806 "runtime_constraints": {}
1809 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1810 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1814 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1815 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1816 for _, v := range api.Content {
1817 if v["collection"] != nil {
1818 collection := v["collection"].(arvadosclient.Dict)
1819 if strings.Index(collection["name"].(string), "output") == 0 {
1820 manifest := collection["manifest_text"].(string)
1821 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1828 func (s *TestSuite) TestStderrMount(c *C) {
1829 api, _, _ := s.fullRunHelper(c, `{
1830 "command": ["/bin/sh", "-c", "echo hello;exit 1"],
1831 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1834 "mounts": {"/tmp": {"kind": "tmp"},
1835 "stdout": {"kind": "file", "path": "/tmp/a/out.txt"},
1836 "stderr": {"kind": "file", "path": "/tmp/b/err.txt"}},
1837 "output_path": "/tmp",
1839 "runtime_constraints": {}
1840 }`, nil, 1, func(t *TestDockerClient) {
1841 t.logWriter.Write(dockerLog(1, "hello\n"))
1842 t.logWriter.Write(dockerLog(2, "oops\n"))
1846 final := api.CalledWith("container.state", "Complete")
1847 c.Assert(final, NotNil)
1848 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1849 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1851 c.Check(api.CalledWith("collection.manifest_text", "./a b1946ac92492d2347c6235b4d2611184+6 0:6:out.txt\n./b 38af5c54926b620264ab1501150cf189+5 0:5:err.txt\n"), NotNil)
1854 func (s *TestSuite) TestNumberRoundTrip(c *C) {
1855 kc := &KeepTestClient{}
1857 cr, err := NewContainerRunner(s.client, &ArvTestClient{callraw: true}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1858 c.Assert(err, IsNil)
1859 cr.fetchContainerRecord()
1861 jsondata, err := json.Marshal(cr.Container.Mounts["/json"].Content)
1864 c.Check(string(jsondata), Equals, `{"number":123456789123456789}`)
1867 func (s *TestSuite) TestFullBrokenDocker1(c *C) {
1868 tf, err := ioutil.TempFile("", "brokenNodeHook-")
1869 c.Assert(err, IsNil)
1870 defer os.Remove(tf.Name())
1872 tf.Write([]byte(`#!/bin/sh
1876 os.Chmod(tf.Name(), 0700)
1879 brokenNodeHook = &ech
1881 api, _, _ := s.fullRunHelper(c, `{
1882 "command": ["echo", "hello world"],
1883 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1886 "mounts": {"/tmp": {"kind": "tmp"} },
1887 "output_path": "/tmp",
1889 "runtime_constraints": {}
1890 }`, nil, 2, func(t *TestDockerClient) {
1891 t.logWriter.Write(dockerLog(1, "hello world\n"))
1895 c.Check(api.CalledWith("container.state", "Queued"), NotNil)
1896 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1897 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Running broken node hook.*")
1898 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*killme.*")
1902 func (s *TestSuite) TestFullBrokenDocker2(c *C) {
1904 brokenNodeHook = &ech
1906 api, _, _ := s.fullRunHelper(c, `{
1907 "command": ["echo", "hello world"],
1908 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1911 "mounts": {"/tmp": {"kind": "tmp"} },
1912 "output_path": "/tmp",
1914 "runtime_constraints": {}
1915 }`, nil, 2, func(t *TestDockerClient) {
1916 t.logWriter.Write(dockerLog(1, "hello world\n"))
1920 c.Check(api.CalledWith("container.state", "Queued"), NotNil)
1921 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1922 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*No broken node hook.*")
1925 func (s *TestSuite) TestFullBrokenDocker3(c *C) {
1927 brokenNodeHook = &ech
1929 api, _, _ := s.fullRunHelper(c, `{
1930 "command": ["echo", "hello world"],
1931 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1934 "mounts": {"/tmp": {"kind": "tmp"} },
1935 "output_path": "/tmp",
1937 "runtime_constraints": {}
1938 }`, nil, 3, func(t *TestDockerClient) {
1939 t.logWriter.Write(dockerLog(1, "hello world\n"))
1943 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1944 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1947 func (s *TestSuite) TestBadCommand1(c *C) {
1949 brokenNodeHook = &ech
1951 api, _, _ := s.fullRunHelper(c, `{
1952 "command": ["echo", "hello world"],
1953 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1956 "mounts": {"/tmp": {"kind": "tmp"} },
1957 "output_path": "/tmp",
1959 "runtime_constraints": {}
1960 }`, nil, 4, func(t *TestDockerClient) {
1961 t.logWriter.Write(dockerLog(1, "hello world\n"))
1965 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1966 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
1969 func (s *TestSuite) TestBadCommand2(c *C) {
1971 brokenNodeHook = &ech
1973 api, _, _ := s.fullRunHelper(c, `{
1974 "command": ["echo", "hello world"],
1975 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1978 "mounts": {"/tmp": {"kind": "tmp"} },
1979 "output_path": "/tmp",
1981 "runtime_constraints": {}
1982 }`, nil, 5, func(t *TestDockerClient) {
1983 t.logWriter.Write(dockerLog(1, "hello world\n"))
1987 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1988 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
1991 func (s *TestSuite) TestBadCommand3(c *C) {
1993 brokenNodeHook = &ech
1995 api, _, _ := s.fullRunHelper(c, `{
1996 "command": ["echo", "hello world"],
1997 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2000 "mounts": {"/tmp": {"kind": "tmp"} },
2001 "output_path": "/tmp",
2003 "runtime_constraints": {}
2004 }`, nil, 6, func(t *TestDockerClient) {
2005 t.logWriter.Write(dockerLog(1, "hello world\n"))
2009 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2010 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2013 func (s *TestSuite) TestSecretTextMountPoint(c *C) {
2014 // under normal mounts, gets captured in output, oops
2016 "command": ["true"],
2017 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2020 "/tmp": {"kind": "tmp"},
2021 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2025 "output_path": "/tmp",
2027 "runtime_constraints": {}
2030 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2031 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2033 c.Check(content, DeepEquals, []byte("mypassword"))
2037 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2038 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2039 c.Check(api.CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), NotNil)
2040 c.Check(api.CalledWith("collection.manifest_text", ""), IsNil)
2042 // under secret mounts, not captured in output
2044 "command": ["true"],
2045 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2048 "/tmp": {"kind": "tmp"}
2051 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2053 "output_path": "/tmp",
2055 "runtime_constraints": {}
2058 api, _, _ = s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2059 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2061 c.Check(content, DeepEquals, []byte("mypassword"))
2065 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2066 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2067 c.Check(api.CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), IsNil)
2068 c.Check(api.CalledWith("collection.manifest_text", ""), NotNil)
2071 type FakeProcess struct {
2075 func (fp FakeProcess) CmdlineSlice() ([]string, error) {
2076 return fp.cmdLine, nil
2079 func (s *TestSuite) helpCheckContainerd(c *C, lp func() ([]PsProcess, error)) error {
2080 kc := &KeepTestClient{}
2082 cr, err := NewContainerRunner(s.client, &ArvTestClient{callraw: true}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
2083 cr.checkContainerd = time.Duration(100 * time.Millisecond)
2084 c.Assert(err, IsNil)
2085 cr.ListProcesses = lp
2087 s.docker.fn = func(t *TestDockerClient) {
2088 time.Sleep(1 * time.Second)
2092 err = cr.CreateContainer()
2095 err = cr.StartContainer()
2098 err = cr.WaitFinish()
2103 func (s *TestSuite) TestCheckContainerdPresent(c *C) {
2104 err := s.helpCheckContainerd(c, func() ([]PsProcess, error) {
2105 return []PsProcess{FakeProcess{[]string{"docker-containerd"}}}, nil
2110 func (s *TestSuite) TestCheckContainerdMissing(c *C) {
2111 err := s.helpCheckContainerd(c, func() ([]PsProcess, error) {
2112 return []PsProcess{FakeProcess{[]string{"abc"}}}, nil
2114 c.Check(err, ErrorMatches, `'containerd' not found in process list.`)