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))
233 outmap.UUID = fmt.Sprintf("zzzzz-4zz18-%15.15x", md5.Sum([]byte(mt)))
239 func (client *ArvTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
241 case method == "GET" && resourceType == "containers" && action == "auth":
242 return json.Unmarshal([]byte(`{
243 "kind": "arvados#api_client_authorization",
244 "uuid": "`+fakeAuthUUID+`",
245 "api_token": "`+fakeAuthToken+`"
247 case method == "GET" && resourceType == "containers" && action == "secret_mounts":
248 if client.secretMounts != nil {
249 return json.Unmarshal(client.secretMounts, output)
251 return json.Unmarshal([]byte(`{"secret_mounts":{}}`), output)
254 return fmt.Errorf("Not found")
258 func (client *ArvTestClient) CallRaw(method, resourceType, uuid, action string,
259 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
261 if method == "GET" && resourceType == "nodes" && uuid == "" && action == "" {
263 "kind": "arvados#nodeList",
265 "uuid": "zzzzz-7ekkf-2z3mc76g2q73aio",
266 "hostname": "compute2",
267 "properties": {"total_cpu_cores": 16}
269 } else if method == "GET" && resourceType == "containers" && action == "" && !client.callraw {
271 j, err = json.Marshal(map[string]interface{}{
272 "items": []interface{}{client.Container},
273 "kind": "arvados#nodeList",
276 j, err = json.Marshal(client.Container)
280 "command": ["sleep", "1"],
281 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
284 "mounts": {"/tmp": {"kind": "tmp"}, "/json": {"kind": "json", "content": {"number": 123456789123456789}}},
285 "output_path": "/tmp",
287 "runtime_constraints": {}
290 return ioutil.NopCloser(bytes.NewReader(j)), err
293 func (client *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
294 if resourceType == "collections" {
296 output.(*arvados.Collection).ManifestText = hwManifest
297 } else if uuid == otherPDH {
298 output.(*arvados.Collection).ManifestText = otherManifest
299 } else if uuid == normalizedWithSubdirsPDH {
300 output.(*arvados.Collection).ManifestText = normalizedManifestWithSubdirs
301 } else if uuid == denormalizedWithSubdirsPDH {
302 output.(*arvados.Collection).ManifestText = denormalizedManifestWithSubdirs
305 if resourceType == "containers" {
306 (*output.(*arvados.Container)) = client.Container
311 func (client *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
313 defer client.Mutex.Unlock()
315 client.Content = append(client.Content, parameters)
316 if resourceType == "containers" {
317 if parameters["container"].(arvadosclient.Dict)["state"] == "Running" {
318 client.WasSetRunning = true
320 } else if resourceType == "collections" {
321 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
322 output.(*arvados.Collection).UUID = uuid
323 output.(*arvados.Collection).PortableDataHash = fmt.Sprintf("%x", md5.Sum([]byte(mt)))
328 var discoveryMap = map[string]interface{}{
329 "defaultTrashLifetime": float64(1209600),
330 "crunchLimitLogBytesPerJob": float64(67108864),
331 "crunchLogThrottleBytes": float64(65536),
332 "crunchLogThrottlePeriod": float64(60),
333 "crunchLogThrottleLines": float64(1024),
334 "crunchLogPartialLineThrottlePeriod": float64(5),
335 "crunchLogBytesPerEvent": float64(4096),
336 "crunchLogSecondsBetweenEvents": float64(1),
339 func (client *ArvTestClient) Discovery(key string) (interface{}, error) {
340 return discoveryMap[key], nil
343 // CalledWith returns the parameters from the first API call whose
344 // parameters match jpath/string. E.g., CalledWith(c, "foo.bar",
345 // "baz") returns parameters with parameters["foo"]["bar"]=="baz". If
346 // no call matches, it returns nil.
347 func (client *ArvTestClient) CalledWith(jpath string, expect interface{}) arvadosclient.Dict {
349 for _, content := range client.Content {
350 var v interface{} = content
351 for _, k := range strings.Split(jpath, ".") {
352 if dict, ok := v.(arvadosclient.Dict); !ok {
365 func (client *KeepTestClient) PutB(buf []byte) (string, int, error) {
367 return fmt.Sprintf("%x+%d", md5.Sum(buf), len(buf)), len(buf), nil
370 func (client *KeepTestClient) ReadAt(string, []byte, int) (int, error) {
371 return 0, errors.New("not implemented")
374 func (client *KeepTestClient) ClearBlockCache() {
377 func (client *KeepTestClient) Close() {
381 type FileWrapper struct {
386 func (fw FileWrapper) Readdir(n int) ([]os.FileInfo, error) {
387 return nil, errors.New("not implemented")
390 func (fw FileWrapper) Seek(int64, int) (int64, error) {
391 return 0, errors.New("not implemented")
394 func (fw FileWrapper) Size() int64 {
398 func (fw FileWrapper) Stat() (os.FileInfo, error) {
399 return nil, errors.New("not implemented")
402 func (fw FileWrapper) Truncate(int64) error {
403 return errors.New("not implemented")
406 func (fw FileWrapper) Write([]byte) (int, error) {
407 return 0, errors.New("not implemented")
410 func (fw FileWrapper) Sync() error {
411 return errors.New("not implemented")
414 func (client *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
415 if filename == hwImageId+".tar" {
416 rdr := ioutil.NopCloser(&bytes.Buffer{})
418 return FileWrapper{rdr, 1321984}, nil
419 } else if filename == "/file1_in_main.txt" {
420 rdr := ioutil.NopCloser(strings.NewReader("foo"))
422 return FileWrapper{rdr, 3}, nil
427 func (s *TestSuite) TestLoadImage(c *C) {
428 kc := &KeepTestClient{}
430 cr, err := NewContainerRunner(s.client, &ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
433 _, err = cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
436 _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
439 cr.Container.ContainerImage = hwPDH
441 // (1) Test loading image from keep
442 c.Check(kc.Called, Equals, false)
443 c.Check(cr.ContainerConfig.Image, Equals, "")
449 cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
452 c.Check(kc.Called, Equals, true)
453 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
455 _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
458 // (2) Test using image that's already loaded
460 cr.ContainerConfig.Image = ""
464 c.Check(kc.Called, Equals, false)
465 c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
469 type ArvErrorTestClient struct{}
471 func (ArvErrorTestClient) Create(resourceType string,
472 parameters arvadosclient.Dict,
473 output interface{}) error {
477 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
478 return errors.New("ArvError")
481 func (ArvErrorTestClient) CallRaw(method, resourceType, uuid, action string,
482 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
483 return nil, errors.New("ArvError")
486 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
487 return errors.New("ArvError")
490 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
494 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
495 return discoveryMap[key], nil
498 type KeepErrorTestClient struct {
502 func (*KeepErrorTestClient) ManifestFileReader(manifest.Manifest, string) (arvados.File, error) {
503 return nil, errors.New("KeepError")
506 func (*KeepErrorTestClient) PutB(buf []byte) (string, int, error) {
507 return "", 0, errors.New("KeepError")
510 type KeepReadErrorTestClient struct {
514 func (*KeepReadErrorTestClient) ReadAt(string, []byte, int) (int, error) {
515 return 0, errors.New("KeepError")
518 type ErrorReader struct {
522 func (ErrorReader) Read(p []byte) (n int, err error) {
523 return 0, errors.New("ErrorReader")
526 func (ErrorReader) Seek(int64, int) (int64, error) {
527 return 0, errors.New("ErrorReader")
530 func (KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
531 return ErrorReader{}, nil
534 func (s *TestSuite) TestLoadImageArvError(c *C) {
536 kc := &KeepTestClient{}
538 cr, err := NewContainerRunner(s.client, ArvErrorTestClient{}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
540 cr.Container.ContainerImage = hwPDH
543 c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
546 func (s *TestSuite) TestLoadImageKeepError(c *C) {
548 cr, err := NewContainerRunner(s.client, &ArvTestClient{}, &KeepErrorTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
550 cr.Container.ContainerImage = hwPDH
553 c.Assert(err, NotNil)
554 c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
557 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
558 // (3) Collection doesn't contain image
559 cr, err := NewContainerRunner(s.client, &ArvTestClient{}, &KeepReadErrorTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
561 cr.Container.ContainerImage = otherPDH
564 c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
567 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
568 // (4) Collection doesn't contain image
569 cr, err := NewContainerRunner(s.client, &ArvTestClient{}, &KeepReadErrorTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
571 cr.Container.ContainerImage = hwPDH
577 type ClosableBuffer struct {
581 func (*ClosableBuffer) Close() error {
585 type TestLogs struct {
586 Stdout ClosableBuffer
587 Stderr ClosableBuffer
590 func (tl *TestLogs) NewTestLoggingWriter(logstr string) (io.WriteCloser, error) {
591 if logstr == "stdout" {
592 return &tl.Stdout, nil
594 if logstr == "stderr" {
595 return &tl.Stderr, nil
597 return nil, errors.New("???")
600 func dockerLog(fd byte, msg string) []byte {
602 header := make([]byte, 8+len(by))
604 header[7] = byte(len(by))
609 func (s *TestSuite) TestRunContainer(c *C) {
610 s.docker.fn = func(t *TestDockerClient) {
611 t.logWriter.Write(dockerLog(1, "Hello world\n"))
614 kc := &KeepTestClient{}
616 cr, err := NewContainerRunner(s.client, &ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
620 cr.NewLogWriter = logs.NewTestLoggingWriter
621 cr.Container.ContainerImage = hwPDH
622 cr.Container.Command = []string{"./hw"}
626 err = cr.CreateContainer()
629 err = cr.StartContainer()
632 err = cr.WaitFinish()
635 c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
636 c.Check(logs.Stderr.String(), Equals, "")
639 func (s *TestSuite) TestCommitLogs(c *C) {
640 api := &ArvTestClient{}
641 kc := &KeepTestClient{}
643 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
645 cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
647 cr.CrunchLog.Print("Hello world!")
648 cr.CrunchLog.Print("Goodbye")
649 cr.finalState = "Complete"
651 err = cr.CommitLogs()
654 c.Check(api.Calls, Equals, 2)
655 c.Check(api.Content[1]["ensure_unique_name"], Equals, true)
656 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
657 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
658 c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
661 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
662 api := &ArvTestClient{}
663 kc := &KeepTestClient{}
665 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
668 err = cr.UpdateContainerRunning()
671 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
674 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
675 api := &ArvTestClient{}
676 kc := &KeepTestClient{}
678 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
681 cr.LogsPDH = new(string)
682 *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
684 cr.ExitCode = new(int)
686 cr.finalState = "Complete"
688 err = cr.UpdateContainerFinal()
691 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
692 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
693 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
696 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
697 api := &ArvTestClient{}
698 kc := &KeepTestClient{}
700 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
703 cr.finalState = "Cancelled"
705 err = cr.UpdateContainerFinal()
708 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
709 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
710 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
713 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
714 // dress rehearsal of the Run() function, starting from a JSON container record.
715 func (s *TestSuite) fullRunHelper(c *C, record string, extraMounts []string, exitCode int, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, realTemp string) {
716 rec := arvados.Container{}
717 err := json.Unmarshal([]byte(record), &rec)
721 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
723 err = json.Unmarshal([]byte(record), &sm)
725 secretMounts, err := json.Marshal(sm)
726 c.Logf("%s %q", sm, secretMounts)
729 s.docker.exitCode = exitCode
731 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
733 api = &ArvTestClient{Container: rec}
735 kc := &KeepTestClient{}
737 cr, err = NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
739 cr.statInterval = 100 * time.Millisecond
740 am := &ArvMountCmdLine{}
741 cr.RunArvMount = am.ArvMountTest
743 realTemp, err = ioutil.TempDir("", "crunchrun_test1-")
745 defer os.RemoveAll(realTemp)
747 s.docker.realTemp = realTemp
750 cr.MkTempDir = func(_ string, prefix string) (string, error) {
752 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, tempcount)
753 err := os.Mkdir(d, os.ModePerm)
754 if err != nil && strings.Contains(err.Error(), ": file exists") {
755 // Test case must have pre-populated the tempdir
760 cr.MkArvClient = func(token string) (IArvadosClient, error) {
761 return &ArvTestClient{secretMounts: secretMounts}, nil
764 if extraMounts != nil && len(extraMounts) > 0 {
765 err := cr.SetupArvMountPoint("keep")
768 for _, m := range extraMounts {
769 os.MkdirAll(cr.ArvMountPoint+"/by_id/"+m, os.ModePerm)
774 if api.CalledWith("container.state", "Complete") != nil {
778 c.Check(api.WasSetRunning, Equals, true)
779 c.Check(api.Content[api.Calls-2]["container"].(arvadosclient.Dict)["log"], NotNil)
783 for k, v := range api.Logs {
792 func (s *TestSuite) TestFullRunHello(c *C) {
793 api, _, _ := s.fullRunHelper(c, `{
794 "command": ["echo", "hello world"],
795 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
798 "mounts": {"/tmp": {"kind": "tmp"} },
799 "output_path": "/tmp",
801 "runtime_constraints": {}
802 }`, nil, 0, func(t *TestDockerClient) {
803 t.logWriter.Write(dockerLog(1, "hello world\n"))
807 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
808 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
809 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
813 func (s *TestSuite) TestRunTimeExceeded(c *C) {
814 api, _, _ := s.fullRunHelper(c, `{
815 "command": ["sleep", "3"],
816 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
819 "mounts": {"/tmp": {"kind": "tmp"} },
820 "output_path": "/tmp",
822 "runtime_constraints": {},
823 "scheduling_parameters":{"max_run_time": 1}
824 }`, nil, 0, func(t *TestDockerClient) {
825 time.Sleep(3 * time.Second)
829 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
830 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*maximum run time exceeded.*")
833 func (s *TestSuite) TestCrunchstat(c *C) {
834 api, _, _ := s.fullRunHelper(c, `{
835 "command": ["sleep", "1"],
836 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
839 "mounts": {"/tmp": {"kind": "tmp"} },
840 "output_path": "/tmp",
842 "runtime_constraints": {}
843 }`, nil, 0, func(t *TestDockerClient) {
844 time.Sleep(time.Second)
848 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
849 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
851 // We didn't actually start a container, so crunchstat didn't
852 // find accounting files and therefore didn't log any stats.
853 // It should have logged a "can't find accounting files"
854 // message after one poll interval, though, so we can confirm
856 c.Assert(api.Logs["crunchstat"], NotNil)
857 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
859 // The "files never appeared" log assures us that we called
860 // (*crunchstat.Reporter)Stop(), and that we set it up with
861 // the correct container ID "abcde":
862 c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files never appeared for abcde\n`)
865 func (s *TestSuite) TestNodeInfoLog(c *C) {
866 os.Setenv("SLURMD_NODENAME", "compute2")
867 api, _, _ := s.fullRunHelper(c, `{
868 "command": ["sleep", "1"],
869 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
872 "mounts": {"/tmp": {"kind": "tmp"} },
873 "output_path": "/tmp",
875 "runtime_constraints": {}
877 func(t *TestDockerClient) {
878 time.Sleep(time.Second)
882 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
883 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
885 c.Assert(api.Logs["node"], NotNil)
886 json := api.Logs["node"].String()
887 c.Check(json, Matches, `(?ms).*"uuid": *"zzzzz-7ekkf-2z3mc76g2q73aio".*`)
888 c.Check(json, Matches, `(?ms).*"total_cpu_cores": *16.*`)
889 c.Check(json, Not(Matches), `(?ms).*"info":.*`)
891 c.Assert(api.Logs["node-info"], NotNil)
892 json = api.Logs["node-info"].String()
893 c.Check(json, Matches, `(?ms).*Host Information.*`)
894 c.Check(json, Matches, `(?ms).*CPU Information.*`)
895 c.Check(json, Matches, `(?ms).*Memory Information.*`)
896 c.Check(json, Matches, `(?ms).*Disk Space.*`)
897 c.Check(json, Matches, `(?ms).*Disk INodes.*`)
900 func (s *TestSuite) TestContainerRecordLog(c *C) {
901 api, _, _ := s.fullRunHelper(c, `{
902 "command": ["sleep", "1"],
903 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
906 "mounts": {"/tmp": {"kind": "tmp"} },
907 "output_path": "/tmp",
909 "runtime_constraints": {}
911 func(t *TestDockerClient) {
912 time.Sleep(time.Second)
916 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
917 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
919 c.Assert(api.Logs["container"], NotNil)
920 c.Check(api.Logs["container"].String(), Matches, `(?ms).*container_image.*`)
923 func (s *TestSuite) TestFullRunStderr(c *C) {
924 api, _, _ := s.fullRunHelper(c, `{
925 "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
926 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
929 "mounts": {"/tmp": {"kind": "tmp"} },
930 "output_path": "/tmp",
932 "runtime_constraints": {}
933 }`, nil, 1, func(t *TestDockerClient) {
934 t.logWriter.Write(dockerLog(1, "hello\n"))
935 t.logWriter.Write(dockerLog(2, "world\n"))
939 final := api.CalledWith("container.state", "Complete")
940 c.Assert(final, NotNil)
941 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
942 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
944 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
945 c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
948 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
949 api, _, _ := s.fullRunHelper(c, `{
951 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
954 "mounts": {"/tmp": {"kind": "tmp"} },
955 "output_path": "/tmp",
957 "runtime_constraints": {}
958 }`, nil, 0, func(t *TestDockerClient) {
959 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
963 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
964 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
965 c.Log(api.Logs["stdout"])
966 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
969 func (s *TestSuite) TestFullRunSetCwd(c *C) {
970 api, _, _ := s.fullRunHelper(c, `{
972 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
975 "mounts": {"/tmp": {"kind": "tmp"} },
976 "output_path": "/tmp",
978 "runtime_constraints": {}
979 }`, nil, 0, func(t *TestDockerClient) {
980 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
984 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
985 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
986 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
989 func (s *TestSuite) TestStopOnSignal(c *C) {
990 s.testStopContainer(c, func(cr *ContainerRunner) {
992 for !s.docker.calledWait {
993 time.Sleep(time.Millisecond)
995 cr.SigChan <- syscall.SIGINT
1000 func (s *TestSuite) TestStopOnArvMountDeath(c *C) {
1001 s.testStopContainer(c, func(cr *ContainerRunner) {
1002 cr.ArvMountExit = make(chan error)
1004 cr.ArvMountExit <- exec.Command("true").Run()
1005 close(cr.ArvMountExit)
1010 func (s *TestSuite) testStopContainer(c *C, setup func(cr *ContainerRunner)) {
1012 "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
1013 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1016 "mounts": {"/tmp": {"kind": "tmp"} },
1017 "output_path": "/tmp",
1019 "runtime_constraints": {}
1022 rec := arvados.Container{}
1023 err := json.Unmarshal([]byte(record), &rec)
1026 s.docker.fn = func(t *TestDockerClient) {
1028 t.logWriter.Write(dockerLog(1, "foo\n"))
1031 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
1033 api := &ArvTestClient{Container: rec}
1034 kc := &KeepTestClient{}
1036 cr, err := NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1037 c.Assert(err, IsNil)
1038 cr.RunArvMount = func([]string, string) (*exec.Cmd, error) { return nil, nil }
1039 cr.MkArvClient = func(token string) (IArvadosClient, error) {
1040 return &ArvTestClient{}, nil
1044 done := make(chan error)
1049 case <-time.After(20 * time.Second):
1050 pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
1051 c.Fatal("timed out")
1055 for k, v := range api.Logs {
1060 c.Check(api.CalledWith("container.log", nil), NotNil)
1061 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1062 c.Check(api.Logs["stdout"].String(), Matches, "(?ms).*foo\n$")
1065 func (s *TestSuite) TestFullRunSetEnv(c *C) {
1066 api, _, _ := s.fullRunHelper(c, `{
1067 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1068 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1070 "environment": {"FROBIZ": "bilbo"},
1071 "mounts": {"/tmp": {"kind": "tmp"} },
1072 "output_path": "/tmp",
1074 "runtime_constraints": {}
1075 }`, nil, 0, func(t *TestDockerClient) {
1076 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1080 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1081 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1082 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)
1085 type ArvMountCmdLine struct {
1090 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
1096 func stubCert(temp string) string {
1097 path := temp + "/ca-certificates.crt"
1098 crt, _ := os.Create(path)
1100 arvadosclient.CertFiles = []string{path}
1104 func (s *TestSuite) TestSetupMounts(c *C) {
1105 api := &ArvTestClient{}
1106 kc := &KeepTestClient{}
1108 cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1109 c.Assert(err, IsNil)
1110 am := &ArvMountCmdLine{}
1111 cr.RunArvMount = am.ArvMountTest
1113 realTemp, err := ioutil.TempDir("", "crunchrun_test1-")
1114 c.Assert(err, IsNil)
1115 certTemp, err := ioutil.TempDir("", "crunchrun_test2-")
1116 c.Assert(err, IsNil)
1117 stubCertPath := stubCert(certTemp)
1119 cr.parentTemp = realTemp
1121 defer os.RemoveAll(realTemp)
1122 defer os.RemoveAll(certTemp)
1125 cr.MkTempDir = func(_ string, prefix string) (string, error) {
1127 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
1128 err := os.Mkdir(d, os.ModePerm)
1129 if err != nil && strings.Contains(err.Error(), ": file exists") {
1130 // Test case must have pre-populated the tempdir
1136 checkEmpty := func() {
1137 // Should be deleted.
1138 _, err := os.Stat(realTemp)
1139 c.Assert(os.IsNotExist(err), Equals, true)
1141 // Now recreate it for the next test.
1142 c.Assert(os.Mkdir(realTemp, 0777), IsNil)
1147 cr.ArvMountPoint = ""
1148 cr.Container.Mounts = make(map[string]arvados.Mount)
1149 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1150 cr.Container.OutputPath = "/tmp"
1151 cr.statInterval = 5 * time.Second
1152 err := cr.SetupMounts()
1154 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1155 "--read-write", "--crunchstat-interval=5",
1156 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1157 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp"})
1158 os.RemoveAll(cr.ArvMountPoint)
1165 cr.ArvMountPoint = ""
1166 cr.Container.Mounts = make(map[string]arvados.Mount)
1167 cr.Container.Mounts["/out"] = arvados.Mount{Kind: "tmp"}
1168 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1169 cr.Container.OutputPath = "/out"
1171 err := cr.SetupMounts()
1173 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1174 "--read-write", "--crunchstat-interval=5",
1175 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1176 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/out", realTemp + "/tmp3:/tmp"})
1177 os.RemoveAll(cr.ArvMountPoint)
1184 cr.ArvMountPoint = ""
1185 cr.Container.Mounts = make(map[string]arvados.Mount)
1186 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1187 cr.Container.OutputPath = "/tmp"
1190 cr.Container.RuntimeConstraints.API = &apiflag
1192 err := cr.SetupMounts()
1194 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1195 "--read-write", "--crunchstat-interval=5",
1196 "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1197 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", stubCertPath + ":/etc/arvados/ca-certificates.crt:ro"})
1198 os.RemoveAll(cr.ArvMountPoint)
1207 cr.ArvMountPoint = ""
1208 cr.Container.Mounts = map[string]arvados.Mount{
1209 "/keeptmp": {Kind: "collection", Writable: true},
1211 cr.Container.OutputPath = "/keeptmp"
1213 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1215 err := cr.SetupMounts()
1217 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1218 "--read-write", "--crunchstat-interval=5",
1219 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1220 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/tmp0:/keeptmp"})
1221 os.RemoveAll(cr.ArvMountPoint)
1228 cr.ArvMountPoint = ""
1229 cr.Container.Mounts = map[string]arvados.Mount{
1230 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1231 "/keepout": {Kind: "collection", Writable: true},
1233 cr.Container.OutputPath = "/keepout"
1235 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1236 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1238 err := cr.SetupMounts()
1240 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1241 "--read-write", "--crunchstat-interval=5",
1242 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1243 sort.StringSlice(cr.Binds).Sort()
1244 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1245 realTemp + "/keep1/tmp0:/keepout"})
1246 os.RemoveAll(cr.ArvMountPoint)
1253 cr.ArvMountPoint = ""
1254 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
1255 cr.Container.Mounts = map[string]arvados.Mount{
1256 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1257 "/keepout": {Kind: "collection", Writable: true},
1259 cr.Container.OutputPath = "/keepout"
1261 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1262 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1264 err := cr.SetupMounts()
1266 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1267 "--read-write", "--crunchstat-interval=5",
1268 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1269 sort.StringSlice(cr.Binds).Sort()
1270 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1271 realTemp + "/keep1/tmp0:/keepout"})
1272 os.RemoveAll(cr.ArvMountPoint)
1277 for _, test := range []struct {
1281 {in: "foo", out: `"foo"`},
1282 {in: nil, out: `null`},
1283 {in: map[string]int64{"foo": 123456789123456789}, out: `{"foo":123456789123456789}`},
1286 cr.ArvMountPoint = ""
1287 cr.Container.Mounts = map[string]arvados.Mount{
1288 "/mnt/test.json": {Kind: "json", Content: test.in},
1290 err := cr.SetupMounts()
1292 sort.StringSlice(cr.Binds).Sort()
1293 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/json2/mountdata.json:/mnt/test.json:ro"})
1294 content, err := ioutil.ReadFile(realTemp + "/json2/mountdata.json")
1296 c.Check(content, DeepEquals, []byte(test.out))
1297 os.RemoveAll(cr.ArvMountPoint)
1302 for _, test := range []struct {
1306 {in: "foo", out: `foo`},
1307 {in: nil, out: "error"},
1308 {in: map[string]int64{"foo": 123456789123456789}, out: "error"},
1311 cr.ArvMountPoint = ""
1312 cr.Container.Mounts = map[string]arvados.Mount{
1313 "/mnt/test.txt": {Kind: "text", Content: test.in},
1315 err := cr.SetupMounts()
1316 if test.out == "error" {
1317 c.Check(err.Error(), Equals, "content for mount \"/mnt/test.txt\" must be a string")
1320 sort.StringSlice(cr.Binds).Sort()
1321 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/text2/mountdata.text:/mnt/test.txt:ro"})
1322 content, err := ioutil.ReadFile(realTemp + "/text2/mountdata.text")
1324 c.Check(content, DeepEquals, []byte(test.out))
1326 os.RemoveAll(cr.ArvMountPoint)
1331 // Read-only mount points are allowed underneath output_dir mount point
1334 cr.ArvMountPoint = ""
1335 cr.Container.Mounts = make(map[string]arvados.Mount)
1336 cr.Container.Mounts = map[string]arvados.Mount{
1337 "/tmp": {Kind: "tmp"},
1338 "/tmp/foo": {Kind: "collection"},
1340 cr.Container.OutputPath = "/tmp"
1342 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1344 err := cr.SetupMounts()
1346 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1347 "--read-write", "--crunchstat-interval=5",
1348 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1349 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", realTemp + "/keep1/tmp0:/tmp/foo:ro"})
1350 os.RemoveAll(cr.ArvMountPoint)
1355 // Writable mount points copied to output_dir mount point
1358 cr.ArvMountPoint = ""
1359 cr.Container.Mounts = make(map[string]arvados.Mount)
1360 cr.Container.Mounts = map[string]arvados.Mount{
1361 "/tmp": {Kind: "tmp"},
1362 "/tmp/foo": {Kind: "collection",
1363 PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53",
1365 "/tmp/bar": {Kind: "collection",
1366 PortableDataHash: "59389a8f9ee9d399be35462a0f92541d+53",
1370 cr.Container.OutputPath = "/tmp"
1372 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1373 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz", os.ModePerm)
1375 rf, _ := os.Create(realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz/quux")
1376 rf.Write([]byte("bar"))
1379 err := cr.SetupMounts()
1381 _, err = os.Stat(cr.HostOutputDir + "/foo")
1383 _, err = os.Stat(cr.HostOutputDir + "/bar/quux")
1385 os.RemoveAll(cr.ArvMountPoint)
1390 // Only mount points of kind 'collection' are allowed underneath output_dir mount point
1393 cr.ArvMountPoint = ""
1394 cr.Container.Mounts = make(map[string]arvados.Mount)
1395 cr.Container.Mounts = map[string]arvados.Mount{
1396 "/tmp": {Kind: "tmp"},
1397 "/tmp/foo": {Kind: "tmp"},
1399 cr.Container.OutputPath = "/tmp"
1401 err := cr.SetupMounts()
1402 c.Check(err, NotNil)
1403 c.Check(err, ErrorMatches, `Only mount points of kind 'collection', 'text' or 'json' are supported underneath the output_path.*`)
1404 os.RemoveAll(cr.ArvMountPoint)
1409 // Only mount point of kind 'collection' is allowed for stdin
1412 cr.ArvMountPoint = ""
1413 cr.Container.Mounts = make(map[string]arvados.Mount)
1414 cr.Container.Mounts = map[string]arvados.Mount{
1415 "stdin": {Kind: "tmp"},
1418 err := cr.SetupMounts()
1419 c.Check(err, NotNil)
1420 c.Check(err, ErrorMatches, `Unsupported mount kind 'tmp' for stdin.*`)
1421 os.RemoveAll(cr.ArvMountPoint)
1429 cr.ArvMountPoint = ""
1430 (*GitMountSuite)(nil).useTestGitServer(c)
1431 cr.token = arvadostest.ActiveToken
1432 cr.Container.Mounts = make(map[string]arvados.Mount)
1433 cr.Container.Mounts = map[string]arvados.Mount{
1436 UUID: arvadostest.Repository2UUID,
1437 Commit: "fd3531f42995344f36c30b79f55f27b502f3d344",
1442 UUID: arvadostest.Repository2UUID,
1443 Commit: "5ebfab0522851df01fec11ec55a6d0f4877b542e",
1447 cr.Container.OutputPath = "/tmp"
1449 err := cr.SetupMounts()
1452 // dirMap[mountpoint] == tmpdir
1453 dirMap := make(map[string]string)
1454 for _, bind := range cr.Binds {
1455 tokens := strings.Split(bind, ":")
1456 dirMap[tokens[1]] = tokens[0]
1458 if cr.Container.Mounts[tokens[1]].Writable {
1459 c.Check(len(tokens), Equals, 2)
1461 c.Check(len(tokens), Equals, 3)
1462 c.Check(tokens[2], Equals, "ro")
1466 data, err := ioutil.ReadFile(dirMap["/tip"] + "/dir1/dir2/file with mode 0644")
1468 c.Check(string(data), Equals, "\000\001\002\003")
1469 _, err = ioutil.ReadFile(dirMap["/tip"] + "/file only on testbranch")
1470 c.Check(err, FitsTypeOf, &os.PathError{})
1471 c.Check(os.IsNotExist(err), Equals, true)
1473 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/dir1/dir2/file with mode 0644")
1475 c.Check(string(data), Equals, "\000\001\002\003")
1476 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/file only on testbranch")
1478 c.Check(string(data), Equals, "testfile\n")
1485 func (s *TestSuite) TestStdout(c *C) {
1487 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1488 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1490 "environment": {"FROBIZ": "bilbo"},
1491 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1492 "output_path": "/tmp",
1494 "runtime_constraints": {}
1497 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1498 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1502 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1503 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1504 c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1507 // Used by the TestStdoutWithWrongPath*()
1508 func (s *TestSuite) stdoutErrorRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, err error) {
1509 rec := arvados.Container{}
1510 err = json.Unmarshal([]byte(record), &rec)
1514 s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
1516 api = &ArvTestClient{Container: rec}
1517 kc := &KeepTestClient{}
1519 cr, err = NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1520 c.Assert(err, IsNil)
1521 am := &ArvMountCmdLine{}
1522 cr.RunArvMount = am.ArvMountTest
1523 cr.MkArvClient = func(token string) (IArvadosClient, error) {
1524 return &ArvTestClient{}, nil
1531 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1532 _, _, err := s.stdoutErrorRunHelper(c, `{
1533 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1534 "output_path": "/tmp"
1535 }`, func(t *TestDockerClient) {})
1537 c.Check(err, NotNil)
1538 c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
1541 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1542 _, _, err := s.stdoutErrorRunHelper(c, `{
1543 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1544 "output_path": "/tmp"
1545 }`, func(t *TestDockerClient) {})
1547 c.Check(err, NotNil)
1548 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'tmp' for stdout"), Equals, true)
1551 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1552 _, _, err := s.stdoutErrorRunHelper(c, `{
1553 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1554 "output_path": "/tmp"
1555 }`, func(t *TestDockerClient) {})
1557 c.Check(err, NotNil)
1558 c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'collection' for stdout"), Equals, true)
1561 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1562 defer os.Setenv("ARVADOS_API_HOST", os.Getenv("ARVADOS_API_HOST"))
1563 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1564 api, _, _ := s.fullRunHelper(c, `{
1565 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1566 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1569 "mounts": {"/tmp": {"kind": "tmp"} },
1570 "output_path": "/tmp",
1572 "runtime_constraints": {"API": true}
1573 }`, nil, 0, func(t *TestDockerClient) {
1574 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
1578 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1579 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1580 c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "test.arvados.org\n"), Equals, true)
1581 c.Check(api.CalledWith("container.output", "d41d8cd98f00b204e9800998ecf8427e+0"), NotNil)
1584 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1585 defer os.Setenv("ARVADOS_API_HOST", os.Getenv("ARVADOS_API_HOST"))
1586 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1587 api, _, _ := s.fullRunHelper(c, `{
1588 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1589 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1592 "mounts": {"/tmp": {"kind": "tmp"} },
1593 "output_path": "/tmp",
1595 "runtime_constraints": {"API": true}
1596 }`, nil, 0, func(t *TestDockerClient) {
1597 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
1601 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1602 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1603 c.Check(api.CalledWith("container.output", "d4ab34d3d4f8a72f5c4973051ae69fab+122"), NotNil)
1606 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1608 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1609 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1611 "environment": {"FROBIZ": "bilbo"},
1613 "/tmp": {"kind": "tmp"},
1614 "/tmp/foo": {"kind": "collection",
1615 "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1616 "exclude_from_output": true
1618 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1620 "output_path": "/tmp",
1622 "runtime_constraints": {}
1625 extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1627 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1628 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1632 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1633 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1634 c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1637 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1639 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1640 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1642 "environment": {"FROBIZ": "bilbo"},
1644 "/tmp": {"kind": "tmp"},
1645 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1646 "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1647 "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1648 "/tmp/foo/baz/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1649 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1651 "output_path": "/tmp",
1653 "runtime_constraints": {}
1656 extraMounts := []string{
1657 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1658 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1659 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1662 api, runner, realtemp := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1663 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1667 c.Check(runner.Binds, DeepEquals, []string{realtemp + "/tmp2:/tmp",
1668 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt:/tmp/foo/bar:ro",
1669 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt:/tmp/foo/baz/sub2file2:ro",
1670 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1:/tmp/foo/sub1:ro",
1671 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt:/tmp/foo/sub1file2:ro",
1674 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1675 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1676 for _, v := range api.Content {
1677 if v["collection"] != nil {
1678 c.Check(v["ensure_unique_name"], Equals, true)
1679 collection := v["collection"].(arvadosclient.Dict)
1680 if strings.Index(collection["name"].(string), "output") == 0 {
1681 manifest := collection["manifest_text"].(string)
1683 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1684 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:bar 36:18:sub1file2
1685 ./foo/baz 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2
1686 ./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1687 ./foo/sub1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1694 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
1696 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1697 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1699 "environment": {"FROBIZ": "bilbo"},
1701 "/tmp": {"kind": "tmp"},
1702 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/subdir1/file2_in_subdir1.txt"},
1703 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1705 "output_path": "/tmp",
1707 "runtime_constraints": {}
1710 extraMounts := []string{
1711 "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1714 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1715 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1719 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1720 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1721 for _, v := range api.Content {
1722 if v["collection"] != nil {
1723 collection := v["collection"].(arvadosclient.Dict)
1724 if strings.Index(collection["name"].(string), "output") == 0 {
1725 manifest := collection["manifest_text"].(string)
1727 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1728 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 10:17:bar
1735 func (s *TestSuite) TestOutputError(c *C) {
1737 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1738 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1740 "environment": {"FROBIZ": "bilbo"},
1742 "/tmp": {"kind": "tmp"}
1744 "output_path": "/tmp",
1746 "runtime_constraints": {}
1749 extraMounts := []string{}
1751 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1752 os.Symlink("/etc/hosts", t.realTemp+"/tmp2/baz")
1756 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1759 func (s *TestSuite) TestStdinCollectionMountPoint(c *C) {
1761 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1762 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1764 "environment": {"FROBIZ": "bilbo"},
1766 "/tmp": {"kind": "tmp"},
1767 "stdin": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/file1_in_main.txt"},
1768 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1770 "output_path": "/tmp",
1772 "runtime_constraints": {}
1775 extraMounts := []string{
1776 "b0def87f80dd594d4675809e83bd4f15+367/file1_in_main.txt",
1779 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1780 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1784 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1785 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1786 for _, v := range api.Content {
1787 if v["collection"] != nil {
1788 collection := v["collection"].(arvadosclient.Dict)
1789 if strings.Index(collection["name"].(string), "output") == 0 {
1790 manifest := collection["manifest_text"].(string)
1791 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1798 func (s *TestSuite) TestStdinJsonMountPoint(c *C) {
1800 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1801 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1803 "environment": {"FROBIZ": "bilbo"},
1805 "/tmp": {"kind": "tmp"},
1806 "stdin": {"kind": "json", "content": "foo"},
1807 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1809 "output_path": "/tmp",
1811 "runtime_constraints": {}
1814 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1815 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1819 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1820 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1821 for _, v := range api.Content {
1822 if v["collection"] != nil {
1823 collection := v["collection"].(arvadosclient.Dict)
1824 if strings.Index(collection["name"].(string), "output") == 0 {
1825 manifest := collection["manifest_text"].(string)
1826 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1833 func (s *TestSuite) TestStderrMount(c *C) {
1834 api, _, _ := s.fullRunHelper(c, `{
1835 "command": ["/bin/sh", "-c", "echo hello;exit 1"],
1836 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1839 "mounts": {"/tmp": {"kind": "tmp"},
1840 "stdout": {"kind": "file", "path": "/tmp/a/out.txt"},
1841 "stderr": {"kind": "file", "path": "/tmp/b/err.txt"}},
1842 "output_path": "/tmp",
1844 "runtime_constraints": {}
1845 }`, nil, 1, func(t *TestDockerClient) {
1846 t.logWriter.Write(dockerLog(1, "hello\n"))
1847 t.logWriter.Write(dockerLog(2, "oops\n"))
1851 final := api.CalledWith("container.state", "Complete")
1852 c.Assert(final, NotNil)
1853 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1854 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1856 c.Check(api.CalledWith("collection.manifest_text", "./a b1946ac92492d2347c6235b4d2611184+6 0:6:out.txt\n./b 38af5c54926b620264ab1501150cf189+5 0:5:err.txt\n"), NotNil)
1859 func (s *TestSuite) TestNumberRoundTrip(c *C) {
1860 kc := &KeepTestClient{}
1862 cr, err := NewContainerRunner(s.client, &ArvTestClient{callraw: true}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1863 c.Assert(err, IsNil)
1864 cr.fetchContainerRecord()
1866 jsondata, err := json.Marshal(cr.Container.Mounts["/json"].Content)
1869 c.Check(string(jsondata), Equals, `{"number":123456789123456789}`)
1872 func (s *TestSuite) TestFullBrokenDocker1(c *C) {
1873 tf, err := ioutil.TempFile("", "brokenNodeHook-")
1874 c.Assert(err, IsNil)
1875 defer os.Remove(tf.Name())
1877 tf.Write([]byte(`#!/bin/sh
1881 os.Chmod(tf.Name(), 0700)
1884 brokenNodeHook = &ech
1886 api, _, _ := s.fullRunHelper(c, `{
1887 "command": ["echo", "hello world"],
1888 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1891 "mounts": {"/tmp": {"kind": "tmp"} },
1892 "output_path": "/tmp",
1894 "runtime_constraints": {}
1895 }`, nil, 2, func(t *TestDockerClient) {
1896 t.logWriter.Write(dockerLog(1, "hello world\n"))
1900 c.Check(api.CalledWith("container.state", "Queued"), NotNil)
1901 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1902 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Running broken node hook.*")
1903 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*killme.*")
1907 func (s *TestSuite) TestFullBrokenDocker2(c *C) {
1909 brokenNodeHook = &ech
1911 api, _, _ := s.fullRunHelper(c, `{
1912 "command": ["echo", "hello world"],
1913 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1916 "mounts": {"/tmp": {"kind": "tmp"} },
1917 "output_path": "/tmp",
1919 "runtime_constraints": {}
1920 }`, nil, 2, func(t *TestDockerClient) {
1921 t.logWriter.Write(dockerLog(1, "hello world\n"))
1925 c.Check(api.CalledWith("container.state", "Queued"), NotNil)
1926 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1927 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*No broken node hook.*")
1930 func (s *TestSuite) TestFullBrokenDocker3(c *C) {
1932 brokenNodeHook = &ech
1934 api, _, _ := s.fullRunHelper(c, `{
1935 "command": ["echo", "hello world"],
1936 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1939 "mounts": {"/tmp": {"kind": "tmp"} },
1940 "output_path": "/tmp",
1942 "runtime_constraints": {}
1943 }`, nil, 3, func(t *TestDockerClient) {
1944 t.logWriter.Write(dockerLog(1, "hello world\n"))
1948 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1949 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1952 func (s *TestSuite) TestBadCommand1(c *C) {
1954 brokenNodeHook = &ech
1956 api, _, _ := s.fullRunHelper(c, `{
1957 "command": ["echo", "hello world"],
1958 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1961 "mounts": {"/tmp": {"kind": "tmp"} },
1962 "output_path": "/tmp",
1964 "runtime_constraints": {}
1965 }`, nil, 4, func(t *TestDockerClient) {
1966 t.logWriter.Write(dockerLog(1, "hello world\n"))
1970 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1971 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
1974 func (s *TestSuite) TestBadCommand2(c *C) {
1976 brokenNodeHook = &ech
1978 api, _, _ := s.fullRunHelper(c, `{
1979 "command": ["echo", "hello world"],
1980 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1983 "mounts": {"/tmp": {"kind": "tmp"} },
1984 "output_path": "/tmp",
1986 "runtime_constraints": {}
1987 }`, nil, 5, func(t *TestDockerClient) {
1988 t.logWriter.Write(dockerLog(1, "hello world\n"))
1992 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1993 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
1996 func (s *TestSuite) TestBadCommand3(c *C) {
1998 brokenNodeHook = &ech
2000 api, _, _ := s.fullRunHelper(c, `{
2001 "command": ["echo", "hello world"],
2002 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2005 "mounts": {"/tmp": {"kind": "tmp"} },
2006 "output_path": "/tmp",
2008 "runtime_constraints": {}
2009 }`, nil, 6, func(t *TestDockerClient) {
2010 t.logWriter.Write(dockerLog(1, "hello world\n"))
2014 c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2015 c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2018 func (s *TestSuite) TestSecretTextMountPoint(c *C) {
2019 // under normal mounts, gets captured in output, oops
2021 "command": ["true"],
2022 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2025 "/tmp": {"kind": "tmp"},
2026 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2030 "output_path": "/tmp",
2032 "runtime_constraints": {}
2035 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2036 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2038 c.Check(content, DeepEquals, []byte("mypassword"))
2042 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2043 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2044 c.Check(api.CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), NotNil)
2045 c.Check(api.CalledWith("collection.manifest_text", ""), IsNil)
2047 // under secret mounts, not captured in output
2049 "command": ["true"],
2050 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2053 "/tmp": {"kind": "tmp"}
2056 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2058 "output_path": "/tmp",
2060 "runtime_constraints": {}
2063 api, _, _ = s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2064 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2066 c.Check(content, DeepEquals, []byte("mypassword"))
2070 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2071 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2072 c.Check(api.CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), IsNil)
2073 c.Check(api.CalledWith("collection.manifest_text", ""), NotNil)
2076 type FakeProcess struct {
2080 func (fp FakeProcess) CmdlineSlice() ([]string, error) {
2081 return fp.cmdLine, nil
2084 func (s *TestSuite) helpCheckContainerd(c *C, lp func() ([]PsProcess, error)) error {
2085 kc := &KeepTestClient{}
2087 cr, err := NewContainerRunner(s.client, &ArvTestClient{callraw: true}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
2088 cr.checkContainerd = time.Duration(100 * time.Millisecond)
2089 c.Assert(err, IsNil)
2090 cr.ListProcesses = lp
2092 s.docker.fn = func(t *TestDockerClient) {
2093 time.Sleep(1 * time.Second)
2097 err = cr.CreateContainer()
2100 err = cr.StartContainer()
2103 err = cr.WaitFinish()
2108 func (s *TestSuite) TestCheckContainerdPresent(c *C) {
2109 err := s.helpCheckContainerd(c, func() ([]PsProcess, error) {
2110 return []PsProcess{FakeProcess{[]string{"docker-containerd"}}}, nil
2115 func (s *TestSuite) TestCheckContainerdMissing(c *C) {
2116 err := s.helpCheckContainerd(c, func() ([]PsProcess, error) {
2117 return []PsProcess{FakeProcess{[]string{"abc"}}}, nil
2119 c.Check(err, ErrorMatches, `'containerd' not found in process list.`)