1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
25 "git.arvados.org/arvados.git/sdk/go/arvados"
26 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
27 "git.arvados.org/arvados.git/sdk/go/arvadostest"
28 "git.arvados.org/arvados.git/sdk/go/manifest"
29 "golang.org/x/net/context"
34 // Gocheck boilerplate
35 func TestCrunchExec(t *testing.T) {
39 var _ = Suite(&TestSuite{})
41 type TestSuite struct {
42 client *arvados.Client
44 runner *ContainerRunner
45 executor *stubExecutor
48 testDispatcherKeepClient KeepTestClient
49 testContainerKeepClient KeepTestClient
52 func (s *TestSuite) SetUpTest(c *C) {
53 s.client = arvados.NewClientFromEnv()
54 s.executor = &stubExecutor{}
56 s.api = &ArvTestClient{}
57 s.runner, err = NewContainerRunner(s.client, s.api, &s.testDispatcherKeepClient, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
59 s.runner.executor = s.executor
60 s.runner.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
61 return s.api, &s.testContainerKeepClient, s.client, nil
63 s.runner.RunArvMount = func(cmd []string, tok string) (*exec.Cmd, error) {
64 s.runner.ArvMountPoint = s.keepmount
65 for i, opt := range cmd {
66 if opt == "--mount-tmp" {
67 err := os.Mkdir(s.keepmount+"/"+cmd[i+1], 0700)
71 s.keepmountTmp = append(s.keepmountTmp, cmd[i+1])
76 s.keepmount = c.MkDir()
77 err = os.Mkdir(s.keepmount+"/by_id", 0755)
80 err = os.Mkdir(s.keepmount+"/by_id/"+arvadostest.DockerImage112PDH, 0755)
82 err = ioutil.WriteFile(s.keepmount+"/by_id/"+arvadostest.DockerImage112PDH+"/"+arvadostest.DockerImage112Filename, []byte("#notarealtarball"), 0644)
83 err = os.Mkdir(s.keepmount+"/by_id/"+fakeInputCollectionPDH, 0755)
85 err = ioutil.WriteFile(s.keepmount+"/by_id/"+fakeInputCollectionPDH+"/input.json", []byte(`{"input":true}`), 0644)
87 s.runner.ArvMountPoint = s.keepmount
90 type ArvTestClient struct {
93 Content []arvadosclient.Dict
96 Logs map[string]*bytes.Buffer
102 type KeepTestClient struct {
105 StorageClasses []string
108 type stubExecutor struct {
114 created containerSpec
116 waitSleep time.Duration
125 func (e *stubExecutor) LoadImage(imageId string, tarball string, container arvados.Container, keepMount string,
126 containerClient *arvados.Client) error {
130 func (e *stubExecutor) Runtime() string { return "stub" }
131 func (e *stubExecutor) Create(spec containerSpec) error { e.created = spec; return e.createErr }
132 func (e *stubExecutor) Start() error { e.exit = make(chan int, 1); go e.runFunc(); return e.startErr }
133 func (e *stubExecutor) CgroupID() string { return "cgroupid" }
134 func (e *stubExecutor) Stop() error { e.stopped = true; go func() { e.exit <- -1 }(); return e.stopErr }
135 func (e *stubExecutor) Close() { e.closed = true }
136 func (e *stubExecutor) Wait(context.Context) (int, error) {
137 return <-e.exit, e.waitErr
140 const fakeInputCollectionPDH = "ffffffffaaaaaaaa88888888eeeeeeee+1234"
142 var hwManifest = ". 82ab40c24fc8df01798e57ba66795bb1+841216+Aa124ac75e5168396c73c0a18eda641a4f41791c0@569fa8c3 0:841216:9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7.tar\n"
143 var hwPDH = "a45557269dcb65a6b78f9ac061c0850b+120"
144 var hwImageID = "9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7"
146 var otherManifest = ". 68a84f561b1d1708c6baff5e019a9ab3+46+Ae5d0af96944a3690becb1decdf60cc1c937f556d@5693216f 0:46:md5sum.txt\n"
147 var otherPDH = "a3e8f74c6f101eae01fa08bfb4e49b3a+54"
149 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
150 ./subdir1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
151 ./subdir1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
154 var normalizedWithSubdirsPDH = "a0def87f80dd594d4675809e83bd4f15+367"
156 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"
157 var denormalizedWithSubdirsPDH = "b0def87f80dd594d4675809e83bd4f15+367"
159 var fakeAuthUUID = "zzzzz-gj3su-55pqoyepgi2glem"
160 var fakeAuthToken = "a3ltuwzqcu2u4sc0q7yhpc2w7s00fdcqecg5d6e0u3pfohmbjt"
162 func (client *ArvTestClient) Create(resourceType string,
163 parameters arvadosclient.Dict,
164 output interface{}) error {
167 defer client.Mutex.Unlock()
170 client.Content = append(client.Content, parameters)
172 if resourceType == "logs" {
173 et := parameters["log"].(arvadosclient.Dict)["event_type"].(string)
174 if client.Logs == nil {
175 client.Logs = make(map[string]*bytes.Buffer)
177 if client.Logs[et] == nil {
178 client.Logs[et] = &bytes.Buffer{}
180 client.Logs[et].Write([]byte(parameters["log"].(arvadosclient.Dict)["properties"].(map[string]string)["text"]))
183 if resourceType == "collections" && output != nil {
184 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
185 outmap := output.(*arvados.Collection)
186 outmap.PortableDataHash = fmt.Sprintf("%x+%d", md5.Sum([]byte(mt)), len(mt))
187 outmap.UUID = fmt.Sprintf("zzzzz-4zz18-%15.15x", md5.Sum([]byte(mt)))
193 func (client *ArvTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
195 case method == "GET" && resourceType == "containers" && action == "auth":
196 return json.Unmarshal([]byte(`{
197 "kind": "arvados#api_client_authorization",
198 "uuid": "`+fakeAuthUUID+`",
199 "api_token": "`+fakeAuthToken+`"
201 case method == "GET" && resourceType == "containers" && action == "secret_mounts":
202 if client.secretMounts != nil {
203 return json.Unmarshal(client.secretMounts, output)
205 return json.Unmarshal([]byte(`{"secret_mounts":{}}`), output)
207 return fmt.Errorf("Not found")
211 func (client *ArvTestClient) CallRaw(method, resourceType, uuid, action string,
212 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
214 if method == "GET" && resourceType == "nodes" && uuid == "" && action == "" {
216 "kind": "arvados#nodeList",
218 "uuid": "zzzzz-7ekkf-2z3mc76g2q73aio",
219 "hostname": "compute2",
220 "properties": {"total_cpu_cores": 16}
222 } else if method == "GET" && resourceType == "containers" && action == "" && !client.callraw {
224 j, err = json.Marshal(map[string]interface{}{
225 "items": []interface{}{client.Container},
226 "kind": "arvados#nodeList",
229 j, err = json.Marshal(client.Container)
233 "command": ["sleep", "1"],
234 "container_image": "` + arvadostest.DockerImage112PDH + `",
237 "mounts": {"/tmp": {"kind": "tmp"}, "/json": {"kind": "json", "content": {"number": 123456789123456789}}},
238 "output_path": "/tmp",
240 "runtime_constraints": {}
243 return ioutil.NopCloser(bytes.NewReader(j)), err
246 func (client *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
247 if resourceType == "collections" {
249 output.(*arvados.Collection).ManifestText = hwManifest
250 } else if uuid == otherPDH {
251 output.(*arvados.Collection).ManifestText = otherManifest
252 } else if uuid == normalizedWithSubdirsPDH {
253 output.(*arvados.Collection).ManifestText = normalizedManifestWithSubdirs
254 } else if uuid == denormalizedWithSubdirsPDH {
255 output.(*arvados.Collection).ManifestText = denormalizedManifestWithSubdirs
258 if resourceType == "containers" {
259 (*output.(*arvados.Container)) = client.Container
264 func (client *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
266 defer client.Mutex.Unlock()
268 client.Content = append(client.Content, parameters)
269 if resourceType == "containers" {
270 if parameters["container"].(arvadosclient.Dict)["state"] == "Running" {
271 client.WasSetRunning = true
273 } else if resourceType == "collections" {
274 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
275 output.(*arvados.Collection).UUID = uuid
276 output.(*arvados.Collection).PortableDataHash = fmt.Sprintf("%x", md5.Sum([]byte(mt)))
281 var discoveryMap = map[string]interface{}{
282 "defaultTrashLifetime": float64(1209600),
283 "crunchLimitLogBytesPerJob": float64(67108864),
284 "crunchLogThrottleBytes": float64(65536),
285 "crunchLogThrottlePeriod": float64(60),
286 "crunchLogThrottleLines": float64(1024),
287 "crunchLogPartialLineThrottlePeriod": float64(5),
288 "crunchLogBytesPerEvent": float64(4096),
289 "crunchLogSecondsBetweenEvents": float64(1),
292 func (client *ArvTestClient) Discovery(key string) (interface{}, error) {
293 return discoveryMap[key], nil
296 // CalledWith returns the parameters from the first API call whose
297 // parameters match jpath/string. E.g., CalledWith(c, "foo.bar",
298 // "baz") returns parameters with parameters["foo"]["bar"]=="baz". If
299 // no call matches, it returns nil.
300 func (client *ArvTestClient) CalledWith(jpath string, expect interface{}) arvadosclient.Dict {
302 for _, content := range client.Content {
303 var v interface{} = content
304 for _, k := range strings.Split(jpath, ".") {
305 if dict, ok := v.(arvadosclient.Dict); !ok {
318 func (client *KeepTestClient) LocalLocator(locator string) (string, error) {
322 func (client *KeepTestClient) BlockWrite(_ context.Context, opts arvados.BlockWriteOptions) (arvados.BlockWriteResponse, error) {
323 client.Content = opts.Data
324 return arvados.BlockWriteResponse{
325 Locator: fmt.Sprintf("%x+%d", md5.Sum(opts.Data), len(opts.Data)),
329 func (client *KeepTestClient) ReadAt(string, []byte, int) (int, error) {
330 return 0, errors.New("not implemented")
333 func (client *KeepTestClient) ClearBlockCache() {
336 func (client *KeepTestClient) Close() {
340 func (client *KeepTestClient) SetStorageClasses(sc []string) {
341 client.StorageClasses = sc
344 type FileWrapper struct {
349 func (fw FileWrapper) Readdir(n int) ([]os.FileInfo, error) {
350 return nil, errors.New("not implemented")
353 func (fw FileWrapper) Seek(int64, int) (int64, error) {
354 return 0, errors.New("not implemented")
357 func (fw FileWrapper) Size() int64 {
361 func (fw FileWrapper) Stat() (os.FileInfo, error) {
362 return nil, errors.New("not implemented")
365 func (fw FileWrapper) Truncate(int64) error {
366 return errors.New("not implemented")
369 func (fw FileWrapper) Write([]byte) (int, error) {
370 return 0, errors.New("not implemented")
373 func (fw FileWrapper) Sync() error {
374 return errors.New("not implemented")
377 func (fw FileWrapper) Snapshot() (*arvados.Subtree, error) {
378 return nil, errors.New("not implemented")
381 func (fw FileWrapper) Splice(*arvados.Subtree) error {
382 return errors.New("not implemented")
385 func (client *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
386 if filename == hwImageID+".tar" {
387 rdr := ioutil.NopCloser(&bytes.Buffer{})
389 return FileWrapper{rdr, 1321984}, nil
390 } else if filename == "/file1_in_main.txt" {
391 rdr := ioutil.NopCloser(strings.NewReader("foo"))
393 return FileWrapper{rdr, 3}, nil
398 func (s *TestSuite) TestLoadImage(c *C) {
399 s.runner.Container.ContainerImage = arvadostest.DockerImage112PDH
400 s.runner.Container.Mounts = map[string]arvados.Mount{
401 "/out": {Kind: "tmp", Writable: true},
403 s.runner.Container.OutputPath = "/out"
405 _, err := s.runner.SetupMounts()
408 imageID, err := s.runner.LoadImage()
410 c.Check(s.executor.loaded, Matches, ".*"+regexp.QuoteMeta(arvadostest.DockerImage112Filename))
411 c.Check(imageID, Equals, strings.TrimSuffix(arvadostest.DockerImage112Filename, ".tar"))
413 s.runner.Container.ContainerImage = arvadostest.DockerImage112PDH
414 s.executor.imageLoaded = false
415 s.executor.loaded = ""
416 s.executor.loadErr = errors.New("bork")
417 imageID, err = s.runner.LoadImage()
418 c.Check(err, ErrorMatches, ".*bork")
419 c.Check(s.executor.loaded, Matches, ".*"+regexp.QuoteMeta(arvadostest.DockerImage112Filename))
421 s.runner.Container.ContainerImage = fakeInputCollectionPDH
422 s.executor.imageLoaded = false
423 s.executor.loaded = ""
424 s.executor.loadErr = nil
425 imageID, err = s.runner.LoadImage()
426 c.Check(err, ErrorMatches, "image collection does not include a \\.tar image file")
427 c.Check(s.executor.loaded, Equals, "")
430 type ArvErrorTestClient struct{}
432 func (ArvErrorTestClient) Create(resourceType string,
433 parameters arvadosclient.Dict,
434 output interface{}) error {
438 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
439 if method == "GET" && resourceType == "containers" && action == "auth" {
442 return errors.New("ArvError")
445 func (ArvErrorTestClient) CallRaw(method, resourceType, uuid, action string,
446 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
447 return nil, errors.New("ArvError")
450 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
451 return errors.New("ArvError")
454 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
458 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
459 return discoveryMap[key], nil
462 type KeepErrorTestClient struct {
466 func (*KeepErrorTestClient) ManifestFileReader(manifest.Manifest, string) (arvados.File, error) {
467 return nil, errors.New("KeepError")
470 func (*KeepErrorTestClient) BlockWrite(context.Context, arvados.BlockWriteOptions) (arvados.BlockWriteResponse, error) {
471 return arvados.BlockWriteResponse{}, errors.New("KeepError")
474 func (*KeepErrorTestClient) LocalLocator(string) (string, error) {
475 return "", errors.New("KeepError")
478 type KeepReadErrorTestClient struct {
482 func (*KeepReadErrorTestClient) ReadAt(string, []byte, int) (int, error) {
483 return 0, errors.New("KeepError")
486 type ErrorReader struct {
490 func (ErrorReader) Read(p []byte) (n int, err error) {
491 return 0, errors.New("ErrorReader")
494 func (ErrorReader) Seek(int64, int) (int64, error) {
495 return 0, errors.New("ErrorReader")
498 func (KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
499 return ErrorReader{}, nil
502 type ClosableBuffer struct {
506 func (*ClosableBuffer) Close() error {
510 type TestLogs struct {
511 Stdout ClosableBuffer
512 Stderr ClosableBuffer
515 func (tl *TestLogs) NewTestLoggingWriter(logstr string) (io.WriteCloser, error) {
516 if logstr == "stdout" {
517 return &tl.Stdout, nil
519 if logstr == "stderr" {
520 return &tl.Stderr, nil
522 return nil, errors.New("???")
525 func dockerLog(fd byte, msg string) []byte {
527 header := make([]byte, 8+len(by))
529 header[7] = byte(len(by))
534 func (s *TestSuite) TestRunContainer(c *C) {
535 s.executor.runFunc = func() {
536 fmt.Fprintf(s.executor.created.Stdout, "Hello world\n")
541 s.runner.NewLogWriter = logs.NewTestLoggingWriter
542 s.runner.Container.ContainerImage = arvadostest.DockerImage112PDH
543 s.runner.Container.Command = []string{"./hw"}
544 s.runner.Container.OutputStorageClasses = []string{"default"}
546 imageID, err := s.runner.LoadImage()
549 err = s.runner.CreateContainer(imageID, nil)
552 err = s.runner.StartContainer()
555 err = s.runner.WaitFinish()
558 c.Check(logs.Stdout.String(), Matches, ".*Hello world\n")
559 c.Check(logs.Stderr.String(), Equals, "")
562 func (s *TestSuite) TestCommitLogs(c *C) {
563 api := &ArvTestClient{}
564 kc := &KeepTestClient{}
566 cr, err := NewContainerRunner(s.client, api, kc, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
568 cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
570 cr.CrunchLog.Print("Hello world!")
571 cr.CrunchLog.Print("Goodbye")
572 cr.finalState = "Complete"
574 err = cr.CommitLogs()
577 c.Check(api.Calls, Equals, 2)
578 c.Check(api.Content[1]["ensure_unique_name"], Equals, true)
579 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
580 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
581 c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
584 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
585 api := &ArvTestClient{}
586 kc := &KeepTestClient{}
588 cr, err := NewContainerRunner(s.client, api, kc, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
591 err = cr.UpdateContainerRunning()
594 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
597 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
598 api := &ArvTestClient{}
599 kc := &KeepTestClient{}
601 cr, err := NewContainerRunner(s.client, api, kc, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
604 cr.LogsPDH = new(string)
605 *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
607 cr.ExitCode = new(int)
609 cr.finalState = "Complete"
611 err = cr.UpdateContainerFinal()
614 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
615 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
616 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
619 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
620 api := &ArvTestClient{}
621 kc := &KeepTestClient{}
623 cr, err := NewContainerRunner(s.client, api, kc, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
626 cr.finalState = "Cancelled"
628 err = cr.UpdateContainerFinal()
631 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
632 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
633 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
636 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
637 // dress rehearsal of the Run() function, starting from a JSON container record.
638 func (s *TestSuite) fullRunHelper(c *C, record string, extraMounts []string, exitCode int, fn func()) (*ArvTestClient, *ContainerRunner, string) {
639 err := json.Unmarshal([]byte(record), &s.api.Container)
641 initialState := s.api.Container.State
644 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
646 err = json.Unmarshal([]byte(record), &sm)
648 secretMounts, err := json.Marshal(sm)
650 c.Logf("SecretMounts decoded %v json %q", sm, secretMounts)
652 s.executor.runFunc = func() {
654 s.executor.exit <- exitCode
657 s.runner.statInterval = 100 * time.Millisecond
658 s.runner.containerWatchdogInterval = time.Second
660 realTemp := c.MkDir()
662 s.runner.MkTempDir = func(_, prefix string) (string, error) {
664 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, tempcount)
665 err := os.Mkdir(d, os.ModePerm)
666 if err != nil && strings.Contains(err.Error(), ": file exists") {
667 // Test case must have pre-populated the tempdir
672 s.runner.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
673 return &ArvTestClient{secretMounts: secretMounts}, &s.testContainerKeepClient, nil, nil
676 if extraMounts != nil && len(extraMounts) > 0 {
677 err := s.runner.SetupArvMountPoint("keep")
680 for _, m := range extraMounts {
681 os.MkdirAll(s.runner.ArvMountPoint+"/by_id/"+m, os.ModePerm)
686 if s.api.CalledWith("container.state", "Complete") != nil {
689 if s.executor.loadErr == nil && s.executor.createErr == nil && initialState != "Running" {
690 c.Check(s.api.WasSetRunning, Equals, true)
691 var lastupdate arvadosclient.Dict
692 for _, content := range s.api.Content {
693 if content["container"] != nil {
694 lastupdate = content["container"].(arvadosclient.Dict)
697 if lastupdate["log"] == nil {
698 c.Errorf("no container update with non-nil log -- updates were: %v", s.api.Content)
703 for k, v := range s.api.Logs {
709 return s.api, s.runner, realTemp
712 func (s *TestSuite) TestFullRunHello(c *C) {
713 s.runner.enableMemoryLimit = true
714 s.runner.networkMode = "default"
715 s.fullRunHelper(c, `{
716 "command": ["echo", "hello world"],
717 "container_image": "`+arvadostest.DockerImage112PDH+`",
719 "environment": {"foo":"bar","baz":"waz"},
720 "mounts": {"/tmp": {"kind": "tmp"} },
721 "output_path": "/tmp",
723 "runtime_constraints": {"vcpus":1,"ram":1000000},
725 "output_storage_classes": ["default"]
727 c.Check(s.executor.created.Command, DeepEquals, []string{"echo", "hello world"})
728 c.Check(s.executor.created.Image, Equals, "sha256:d8309758b8fe2c81034ffc8a10c36460b77db7bc5e7b448c4e5b684f9d95a678")
729 c.Check(s.executor.created.Env, DeepEquals, map[string]string{"foo": "bar", "baz": "waz"})
730 c.Check(s.executor.created.VCPUs, Equals, 1)
731 c.Check(s.executor.created.RAM, Equals, int64(1000000))
732 c.Check(s.executor.created.NetworkMode, Equals, "default")
733 c.Check(s.executor.created.EnableNetwork, Equals, false)
734 c.Check(s.executor.created.CUDADeviceCount, Equals, 0)
735 fmt.Fprintln(s.executor.created.Stdout, "hello world")
738 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
739 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
740 c.Check(s.api.Logs["stdout"].String(), Matches, ".*hello world\n")
741 c.Check(s.testDispatcherKeepClient.StorageClasses, DeepEquals, []string{"default"})
742 c.Check(s.testContainerKeepClient.StorageClasses, DeepEquals, []string{"default"})
745 func (s *TestSuite) TestRunAlreadyRunning(c *C) {
747 s.fullRunHelper(c, `{
748 "command": ["sleep", "3"],
749 "container_image": "`+arvadostest.DockerImage112PDH+`",
752 "mounts": {"/tmp": {"kind": "tmp"} },
753 "output_path": "/tmp",
755 "runtime_constraints": {},
756 "scheduling_parameters":{"max_run_time": 1},
761 c.Check(s.api.CalledWith("container.state", "Cancelled"), IsNil)
762 c.Check(s.api.CalledWith("container.state", "Complete"), IsNil)
763 c.Check(ran, Equals, false)
766 func (s *TestSuite) TestRunTimeExceeded(c *C) {
767 s.fullRunHelper(c, `{
768 "command": ["sleep", "3"],
769 "container_image": "`+arvadostest.DockerImage112PDH+`",
772 "mounts": {"/tmp": {"kind": "tmp"} },
773 "output_path": "/tmp",
775 "runtime_constraints": {},
776 "scheduling_parameters":{"max_run_time": 1},
779 time.Sleep(3 * time.Second)
782 c.Check(s.api.CalledWith("container.state", "Cancelled"), NotNil)
783 c.Check(s.api.Logs["crunch-run"].String(), Matches, "(?ms).*maximum run time exceeded.*")
786 func (s *TestSuite) TestContainerWaitFails(c *C) {
787 s.fullRunHelper(c, `{
788 "command": ["sleep", "3"],
789 "container_image": "`+arvadostest.DockerImage112PDH+`",
791 "mounts": {"/tmp": {"kind": "tmp"} },
792 "output_path": "/tmp",
796 s.executor.waitErr = errors.New("Container is not running")
799 c.Check(s.api.CalledWith("container.state", "Cancelled"), NotNil)
800 c.Check(s.api.Logs["crunch-run"].String(), Matches, "(?ms).*Container is not running.*")
803 func (s *TestSuite) TestCrunchstat(c *C) {
804 s.fullRunHelper(c, `{
805 "command": ["sleep", "1"],
806 "container_image": "`+arvadostest.DockerImage112PDH+`",
809 "mounts": {"/tmp": {"kind": "tmp"} },
810 "output_path": "/tmp",
812 "runtime_constraints": {},
815 time.Sleep(time.Second)
818 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
819 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
821 // We didn't actually start a container, so crunchstat didn't
822 // find accounting files and therefore didn't log any stats.
823 // It should have logged a "can't find accounting files"
824 // message after one poll interval, though, so we can confirm
826 c.Assert(s.api.Logs["crunchstat"], NotNil)
827 c.Check(s.api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
829 // The "files never appeared" log assures us that we called
830 // (*crunchstat.Reporter)Stop(), and that we set it up with
831 // the correct container ID "abcde":
832 c.Check(s.api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files never appeared for cgroupid\n`)
835 func (s *TestSuite) TestNodeInfoLog(c *C) {
836 os.Setenv("SLURMD_NODENAME", "compute2")
837 s.fullRunHelper(c, `{
838 "command": ["sleep", "1"],
839 "container_image": "`+arvadostest.DockerImage112PDH+`",
842 "mounts": {"/tmp": {"kind": "tmp"} },
843 "output_path": "/tmp",
845 "runtime_constraints": {},
849 time.Sleep(time.Second)
852 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
853 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
855 c.Assert(s.api.Logs["node"], NotNil)
856 json := s.api.Logs["node"].String()
857 c.Check(json, Matches, `(?ms).*"uuid": *"zzzzz-7ekkf-2z3mc76g2q73aio".*`)
858 c.Check(json, Matches, `(?ms).*"total_cpu_cores": *16.*`)
859 c.Check(json, Not(Matches), `(?ms).*"info":.*`)
861 c.Assert(s.api.Logs["node-info"], NotNil)
862 json = s.api.Logs["node-info"].String()
863 c.Check(json, Matches, `(?ms).*Host Information.*`)
864 c.Check(json, Matches, `(?ms).*CPU Information.*`)
865 c.Check(json, Matches, `(?ms).*Memory Information.*`)
866 c.Check(json, Matches, `(?ms).*Disk Space.*`)
867 c.Check(json, Matches, `(?ms).*Disk INodes.*`)
870 func (s *TestSuite) TestLogVersionAndRuntime(c *C) {
871 s.fullRunHelper(c, `{
872 "command": ["sleep", "1"],
873 "container_image": "`+arvadostest.DockerImage112PDH+`",
876 "mounts": {"/tmp": {"kind": "tmp"} },
877 "output_path": "/tmp",
879 "runtime_constraints": {},
885 c.Assert(s.api.Logs["crunch-run"], NotNil)
886 c.Check(s.api.Logs["crunch-run"].String(), Matches, `(?ms).*crunch-run \S+ \(go\S+\) start.*`)
887 c.Check(s.api.Logs["crunch-run"].String(), Matches, `(?ms).*crunch-run process has uid=\d+\(.+\) gid=\d+\(.+\) groups=\d+\(.+\)(,\d+\(.+\))*\n.*`)
888 c.Check(s.api.Logs["crunch-run"].String(), Matches, `(?ms).*Executing container 'zzzzz-zzzzz-zzzzzzzzzzzzzzz' using stub runtime.*`)
891 func (s *TestSuite) TestContainerRecordLog(c *C) {
892 s.fullRunHelper(c, `{
893 "command": ["sleep", "1"],
894 "container_image": "`+arvadostest.DockerImage112PDH+`",
897 "mounts": {"/tmp": {"kind": "tmp"} },
898 "output_path": "/tmp",
900 "runtime_constraints": {},
904 time.Sleep(time.Second)
907 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
908 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
910 c.Assert(s.api.Logs["container"], NotNil)
911 c.Check(s.api.Logs["container"].String(), Matches, `(?ms).*container_image.*`)
914 func (s *TestSuite) TestFullRunStderr(c *C) {
915 s.fullRunHelper(c, `{
916 "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
917 "container_image": "`+arvadostest.DockerImage112PDH+`",
920 "mounts": {"/tmp": {"kind": "tmp"} },
921 "output_path": "/tmp",
923 "runtime_constraints": {},
926 fmt.Fprintln(s.executor.created.Stdout, "hello")
927 fmt.Fprintln(s.executor.created.Stderr, "world")
930 final := s.api.CalledWith("container.state", "Complete")
931 c.Assert(final, NotNil)
932 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
933 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
935 c.Check(s.api.Logs["stdout"].String(), Matches, ".*hello\n")
936 c.Check(s.api.Logs["stderr"].String(), Matches, ".*world\n")
939 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
940 s.fullRunHelper(c, `{
942 "container_image": "`+arvadostest.DockerImage112PDH+`",
945 "mounts": {"/tmp": {"kind": "tmp"} },
946 "output_path": "/tmp",
948 "runtime_constraints": {},
951 fmt.Fprintf(s.executor.created.Stdout, "workdir=%q", s.executor.created.WorkingDir)
954 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
955 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
956 c.Log(s.api.Logs["stdout"])
957 c.Check(s.api.Logs["stdout"].String(), Matches, `.*workdir=""\n`)
960 func (s *TestSuite) TestFullRunSetCwd(c *C) {
961 s.fullRunHelper(c, `{
963 "container_image": "`+arvadostest.DockerImage112PDH+`",
966 "mounts": {"/tmp": {"kind": "tmp"} },
967 "output_path": "/tmp",
969 "runtime_constraints": {},
972 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.WorkingDir)
975 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
976 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
977 c.Check(s.api.Logs["stdout"].String(), Matches, ".*/bin\n")
980 func (s *TestSuite) TestFullRunSetOutputStorageClasses(c *C) {
981 s.fullRunHelper(c, `{
983 "container_image": "`+arvadostest.DockerImage112PDH+`",
986 "mounts": {"/tmp": {"kind": "tmp"} },
987 "output_path": "/tmp",
989 "runtime_constraints": {},
991 "output_storage_classes": ["foo", "bar"]
993 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.WorkingDir)
996 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
997 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
998 c.Check(s.api.Logs["stdout"].String(), Matches, ".*/bin\n")
999 c.Check(s.testDispatcherKeepClient.StorageClasses, DeepEquals, []string{"foo", "bar"})
1000 c.Check(s.testContainerKeepClient.StorageClasses, DeepEquals, []string{"foo", "bar"})
1003 func (s *TestSuite) TestEnableCUDADeviceCount(c *C) {
1004 s.fullRunHelper(c, `{
1006 "container_image": "`+arvadostest.DockerImage112PDH+`",
1009 "mounts": {"/tmp": {"kind": "tmp"} },
1010 "output_path": "/tmp",
1012 "runtime_constraints": {"cuda": {"device_count": 2}},
1014 "output_storage_classes": ["foo", "bar"]
1015 }`, nil, 0, func() {
1016 fmt.Fprintln(s.executor.created.Stdout, "ok")
1018 c.Check(s.executor.created.CUDADeviceCount, Equals, 2)
1021 func (s *TestSuite) TestEnableCUDAHardwareCapability(c *C) {
1022 s.fullRunHelper(c, `{
1024 "container_image": "`+arvadostest.DockerImage112PDH+`",
1027 "mounts": {"/tmp": {"kind": "tmp"} },
1028 "output_path": "/tmp",
1030 "runtime_constraints": {"cuda": {"hardware_capability": "foo"}},
1032 "output_storage_classes": ["foo", "bar"]
1033 }`, nil, 0, func() {
1034 fmt.Fprintln(s.executor.created.Stdout, "ok")
1036 c.Check(s.executor.created.CUDADeviceCount, Equals, 0)
1039 func (s *TestSuite) TestStopOnSignal(c *C) {
1040 s.executor.runFunc = func() {
1041 s.executor.created.Stdout.Write([]byte("foo\n"))
1042 s.runner.SigChan <- syscall.SIGINT
1044 s.testStopContainer(c)
1047 func (s *TestSuite) TestStopOnArvMountDeath(c *C) {
1048 s.executor.runFunc = func() {
1049 s.executor.created.Stdout.Write([]byte("foo\n"))
1050 s.runner.ArvMountExit <- nil
1051 close(s.runner.ArvMountExit)
1053 s.runner.ArvMountExit = make(chan error)
1054 s.testStopContainer(c)
1057 func (s *TestSuite) testStopContainer(c *C) {
1059 "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
1060 "container_image": "` + arvadostest.DockerImage112PDH + `",
1063 "mounts": {"/tmp": {"kind": "tmp"} },
1064 "output_path": "/tmp",
1066 "runtime_constraints": {},
1070 err := json.Unmarshal([]byte(record), &s.api.Container)
1071 c.Assert(err, IsNil)
1073 s.runner.RunArvMount = func([]string, string) (*exec.Cmd, error) { return nil, nil }
1074 s.runner.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1075 return &ArvTestClient{}, &KeepTestClient{}, nil, nil
1078 done := make(chan error)
1080 done <- s.runner.Run()
1083 case <-time.After(20 * time.Second):
1084 pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
1085 c.Fatal("timed out")
1089 for k, v := range s.api.Logs {
1091 c.Log(v.String(), "\n")
1094 c.Check(s.api.CalledWith("container.log", nil), NotNil)
1095 c.Check(s.api.CalledWith("container.state", "Cancelled"), NotNil)
1096 c.Check(s.api.Logs["stdout"].String(), Matches, "(?ms).*foo\n$")
1099 func (s *TestSuite) TestFullRunSetEnv(c *C) {
1100 s.fullRunHelper(c, `{
1101 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1102 "container_image": "`+arvadostest.DockerImage112PDH+`",
1104 "environment": {"FROBIZ": "bilbo"},
1105 "mounts": {"/tmp": {"kind": "tmp"} },
1106 "output_path": "/tmp",
1108 "runtime_constraints": {},
1110 }`, nil, 0, func() {
1111 fmt.Fprintf(s.executor.created.Stdout, "%v", s.executor.created.Env)
1114 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1115 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1116 c.Check(s.api.Logs["stdout"].String(), Matches, `.*map\[FROBIZ:bilbo\]\n`)
1119 type ArvMountCmdLine struct {
1124 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
1130 func stubCert(temp string) string {
1131 path := temp + "/ca-certificates.crt"
1132 crt, _ := os.Create(path)
1134 arvadosclient.CertFiles = []string{path}
1138 func (s *TestSuite) TestSetupMounts(c *C) {
1140 am := &ArvMountCmdLine{}
1141 cr.RunArvMount = am.ArvMountTest
1142 cr.ContainerArvClient = &ArvTestClient{}
1143 cr.ContainerKeepClient = &KeepTestClient{}
1144 cr.Container.OutputStorageClasses = []string{"default"}
1146 realTemp := c.MkDir()
1147 certTemp := c.MkDir()
1148 stubCertPath := stubCert(certTemp)
1149 cr.parentTemp = realTemp
1152 cr.MkTempDir = func(_ string, prefix string) (string, error) {
1154 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
1155 err := os.Mkdir(d, os.ModePerm)
1156 if err != nil && strings.Contains(err.Error(), ": file exists") {
1157 // Test case must have pre-populated the tempdir
1163 checkEmpty := func() {
1164 // Should be deleted.
1165 _, err := os.Stat(realTemp)
1166 c.Assert(os.IsNotExist(err), Equals, true)
1168 // Now recreate it for the next test.
1169 c.Assert(os.Mkdir(realTemp, 0777), IsNil)
1174 cr.ArvMountPoint = ""
1175 cr.Container.Mounts = make(map[string]arvados.Mount)
1176 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1177 cr.Container.OutputPath = "/tmp"
1178 cr.statInterval = 5 * time.Second
1179 bindmounts, err := cr.SetupMounts()
1181 c.Check(am.Cmd, DeepEquals, []string{"arv-mount", "--foreground",
1182 "--read-write", "--storage-classes", "default", "--crunchstat-interval=5",
1183 "--mount-by-pdh", "by_id", "--disable-event-listening", "--mount-by-id", "by_uuid", realTemp + "/keep1"})
1184 c.Check(bindmounts, DeepEquals, map[string]bindmount{"/tmp": {realTemp + "/tmp2", false}})
1185 os.RemoveAll(cr.ArvMountPoint)
1192 cr.ArvMountPoint = ""
1193 cr.Container.Mounts = make(map[string]arvados.Mount)
1194 cr.Container.Mounts["/out"] = arvados.Mount{Kind: "tmp"}
1195 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1196 cr.Container.OutputPath = "/out"
1197 cr.Container.OutputStorageClasses = []string{"foo", "bar"}
1199 bindmounts, err := cr.SetupMounts()
1201 c.Check(am.Cmd, DeepEquals, []string{"arv-mount", "--foreground",
1202 "--read-write", "--storage-classes", "foo,bar", "--crunchstat-interval=5",
1203 "--mount-by-pdh", "by_id", "--disable-event-listening", "--mount-by-id", "by_uuid", realTemp + "/keep1"})
1204 c.Check(bindmounts, DeepEquals, map[string]bindmount{"/out": {realTemp + "/tmp2", false}, "/tmp": {realTemp + "/tmp3", false}})
1205 os.RemoveAll(cr.ArvMountPoint)
1212 cr.ArvMountPoint = ""
1213 cr.Container.Mounts = make(map[string]arvados.Mount)
1214 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1215 cr.Container.OutputPath = "/tmp"
1216 cr.Container.RuntimeConstraints.API = true
1217 cr.Container.OutputStorageClasses = []string{"default"}
1219 bindmounts, err := cr.SetupMounts()
1221 c.Check(am.Cmd, DeepEquals, []string{"arv-mount", "--foreground",
1222 "--read-write", "--storage-classes", "default", "--crunchstat-interval=5",
1223 "--mount-by-pdh", "by_id", "--disable-event-listening", "--mount-by-id", "by_uuid", realTemp + "/keep1"})
1224 c.Check(bindmounts, DeepEquals, map[string]bindmount{"/tmp": {realTemp + "/tmp2", false}, "/etc/arvados/ca-certificates.crt": {stubCertPath, true}})
1225 os.RemoveAll(cr.ArvMountPoint)
1229 cr.Container.RuntimeConstraints.API = false
1234 cr.ArvMountPoint = ""
1235 cr.Container.Mounts = map[string]arvados.Mount{
1236 "/keeptmp": {Kind: "collection", Writable: true},
1238 cr.Container.OutputPath = "/keeptmp"
1240 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1242 bindmounts, err := cr.SetupMounts()
1244 c.Check(am.Cmd, DeepEquals, []string{"arv-mount", "--foreground",
1245 "--read-write", "--storage-classes", "default", "--crunchstat-interval=5",
1246 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", "--disable-event-listening", "--mount-by-id", "by_uuid", realTemp + "/keep1"})
1247 c.Check(bindmounts, DeepEquals, map[string]bindmount{"/keeptmp": {realTemp + "/keep1/tmp0", false}})
1248 os.RemoveAll(cr.ArvMountPoint)
1255 cr.ArvMountPoint = ""
1256 cr.Container.Mounts = map[string]arvados.Mount{
1257 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1258 "/keepout": {Kind: "collection", Writable: true},
1260 cr.Container.OutputPath = "/keepout"
1262 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1263 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1265 bindmounts, err := cr.SetupMounts()
1267 c.Check(am.Cmd, DeepEquals, []string{"arv-mount", "--foreground",
1268 "--read-write", "--storage-classes", "default", "--crunchstat-interval=5",
1269 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", "--disable-event-listening", "--mount-by-id", "by_uuid", realTemp + "/keep1"})
1270 c.Check(bindmounts, DeepEquals, map[string]bindmount{
1271 "/keepinp": {realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", true},
1272 "/keepout": {realTemp + "/keep1/tmp0", false},
1274 os.RemoveAll(cr.ArvMountPoint)
1281 cr.ArvMountPoint = ""
1282 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
1283 cr.Container.Mounts = map[string]arvados.Mount{
1284 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1285 "/keepout": {Kind: "collection", Writable: true},
1287 cr.Container.OutputPath = "/keepout"
1289 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1290 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1292 bindmounts, err := cr.SetupMounts()
1294 c.Check(am.Cmd, DeepEquals, []string{"arv-mount", "--foreground",
1295 "--read-write", "--storage-classes", "default", "--crunchstat-interval=5",
1296 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", "--disable-event-listening", "--mount-by-id", "by_uuid", realTemp + "/keep1"})
1297 c.Check(bindmounts, DeepEquals, map[string]bindmount{
1298 "/keepinp": {realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", true},
1299 "/keepout": {realTemp + "/keep1/tmp0", false},
1301 os.RemoveAll(cr.ArvMountPoint)
1306 for _, test := range []struct {
1310 {in: "foo", out: `"foo"`},
1311 {in: nil, out: `null`},
1312 {in: map[string]int64{"foo": 123456789123456789}, out: `{"foo":123456789123456789}`},
1315 cr.ArvMountPoint = ""
1316 cr.Container.Mounts = map[string]arvados.Mount{
1317 "/mnt/test.json": {Kind: "json", Content: test.in},
1319 bindmounts, err := cr.SetupMounts()
1321 c.Check(bindmounts, DeepEquals, map[string]bindmount{
1322 "/mnt/test.json": {realTemp + "/json2/mountdata.json", true},
1324 content, err := ioutil.ReadFile(realTemp + "/json2/mountdata.json")
1326 c.Check(content, DeepEquals, []byte(test.out))
1327 os.RemoveAll(cr.ArvMountPoint)
1332 for _, test := range []struct {
1336 {in: "foo", out: `foo`},
1337 {in: nil, out: "error"},
1338 {in: map[string]int64{"foo": 123456789123456789}, out: "error"},
1341 cr.ArvMountPoint = ""
1342 cr.Container.Mounts = map[string]arvados.Mount{
1343 "/mnt/test.txt": {Kind: "text", Content: test.in},
1345 bindmounts, err := cr.SetupMounts()
1346 if test.out == "error" {
1347 c.Check(err.Error(), Equals, "content for mount \"/mnt/test.txt\" must be a string")
1350 c.Check(bindmounts, DeepEquals, map[string]bindmount{
1351 "/mnt/test.txt": {realTemp + "/text2/mountdata.text", true},
1353 content, err := ioutil.ReadFile(realTemp + "/text2/mountdata.text")
1355 c.Check(content, DeepEquals, []byte(test.out))
1357 os.RemoveAll(cr.ArvMountPoint)
1362 // Read-only mount points are allowed underneath output_dir mount point
1365 cr.ArvMountPoint = ""
1366 cr.Container.Mounts = make(map[string]arvados.Mount)
1367 cr.Container.Mounts = map[string]arvados.Mount{
1368 "/tmp": {Kind: "tmp"},
1369 "/tmp/foo": {Kind: "collection"},
1371 cr.Container.OutputPath = "/tmp"
1373 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1375 bindmounts, err := cr.SetupMounts()
1377 c.Check(am.Cmd, DeepEquals, []string{"arv-mount", "--foreground",
1378 "--read-write", "--storage-classes", "default", "--crunchstat-interval=5",
1379 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", "--disable-event-listening", "--mount-by-id", "by_uuid", realTemp + "/keep1"})
1380 c.Check(bindmounts, DeepEquals, map[string]bindmount{
1381 "/tmp": {realTemp + "/tmp2", false},
1382 "/tmp/foo": {realTemp + "/keep1/tmp0", true},
1384 os.RemoveAll(cr.ArvMountPoint)
1389 // Writable mount points copied to output_dir mount point
1392 cr.ArvMountPoint = ""
1393 cr.Container.Mounts = make(map[string]arvados.Mount)
1394 cr.Container.Mounts = map[string]arvados.Mount{
1395 "/tmp": {Kind: "tmp"},
1396 "/tmp/foo": {Kind: "collection",
1397 PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53",
1399 "/tmp/bar": {Kind: "collection",
1400 PortableDataHash: "59389a8f9ee9d399be35462a0f92541d+53",
1404 cr.Container.OutputPath = "/tmp"
1406 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1407 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz", os.ModePerm)
1409 rf, _ := os.Create(realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz/quux")
1410 rf.Write([]byte("bar"))
1413 _, err := cr.SetupMounts()
1415 _, err = os.Stat(cr.HostOutputDir + "/foo")
1417 _, err = os.Stat(cr.HostOutputDir + "/bar/quux")
1419 os.RemoveAll(cr.ArvMountPoint)
1424 // Only mount points of kind 'collection' are allowed underneath output_dir mount point
1427 cr.ArvMountPoint = ""
1428 cr.Container.Mounts = make(map[string]arvados.Mount)
1429 cr.Container.Mounts = map[string]arvados.Mount{
1430 "/tmp": {Kind: "tmp"},
1431 "/tmp/foo": {Kind: "tmp"},
1433 cr.Container.OutputPath = "/tmp"
1435 _, err := cr.SetupMounts()
1436 c.Check(err, NotNil)
1437 c.Check(err, ErrorMatches, `only mount points of kind 'collection', 'text' or 'json' are supported underneath the output_path.*`)
1438 os.RemoveAll(cr.ArvMountPoint)
1443 // Only mount point of kind 'collection' is allowed for stdin
1446 cr.ArvMountPoint = ""
1447 cr.Container.Mounts = make(map[string]arvados.Mount)
1448 cr.Container.Mounts = map[string]arvados.Mount{
1449 "stdin": {Kind: "tmp"},
1452 _, err := cr.SetupMounts()
1453 c.Check(err, NotNil)
1454 c.Check(err, ErrorMatches, `unsupported mount kind 'tmp' for stdin.*`)
1455 os.RemoveAll(cr.ArvMountPoint)
1463 cr.ArvMountPoint = ""
1464 (*GitMountSuite)(nil).useTestGitServer(c)
1465 cr.token = arvadostest.ActiveToken
1466 cr.Container.Mounts = make(map[string]arvados.Mount)
1467 cr.Container.Mounts = map[string]arvados.Mount{
1470 UUID: arvadostest.Repository2UUID,
1471 Commit: "fd3531f42995344f36c30b79f55f27b502f3d344",
1476 UUID: arvadostest.Repository2UUID,
1477 Commit: "5ebfab0522851df01fec11ec55a6d0f4877b542e",
1481 cr.Container.OutputPath = "/tmp"
1483 bindmounts, err := cr.SetupMounts()
1486 for path, mount := range bindmounts {
1487 c.Check(mount.ReadOnly, Equals, !cr.Container.Mounts[path].Writable, Commentf("%s %#v", path, mount))
1490 data, err := ioutil.ReadFile(bindmounts["/tip"].HostPath + "/dir1/dir2/file with mode 0644")
1492 c.Check(string(data), Equals, "\000\001\002\003")
1493 _, err = ioutil.ReadFile(bindmounts["/tip"].HostPath + "/file only on testbranch")
1494 c.Check(err, FitsTypeOf, &os.PathError{})
1495 c.Check(os.IsNotExist(err), Equals, true)
1497 data, err = ioutil.ReadFile(bindmounts["/non-tip"].HostPath + "/dir1/dir2/file with mode 0644")
1499 c.Check(string(data), Equals, "\000\001\002\003")
1500 data, err = ioutil.ReadFile(bindmounts["/non-tip"].HostPath + "/file only on testbranch")
1502 c.Check(string(data), Equals, "testfile\n")
1509 func (s *TestSuite) TestStdout(c *C) {
1511 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1512 "container_image": "` + arvadostest.DockerImage112PDH + `",
1514 "environment": {"FROBIZ": "bilbo"},
1515 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1516 "output_path": "/tmp",
1518 "runtime_constraints": {},
1522 s.fullRunHelper(c, helperRecord, nil, 0, func() {
1523 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.Env["FROBIZ"])
1526 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1527 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1528 c.Check(s.runner.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1531 // Used by the TestStdoutWithWrongPath*()
1532 func (s *TestSuite) stdoutErrorRunHelper(c *C, record string, fn func()) (*ArvTestClient, *ContainerRunner, error) {
1533 err := json.Unmarshal([]byte(record), &s.api.Container)
1534 c.Assert(err, IsNil)
1535 s.executor.runFunc = fn
1536 s.runner.RunArvMount = (&ArvMountCmdLine{}).ArvMountTest
1537 s.runner.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1538 return s.api, &KeepTestClient{}, nil, nil
1540 return s.api, s.runner, s.runner.Run()
1543 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1544 _, _, err := s.stdoutErrorRunHelper(c, `{
1545 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1546 "output_path": "/tmp",
1549 c.Check(err, ErrorMatches, ".*Stdout path does not start with OutputPath.*")
1552 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1553 _, _, err := s.stdoutErrorRunHelper(c, `{
1554 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1555 "output_path": "/tmp",
1558 c.Check(err, ErrorMatches, ".*unsupported mount kind 'tmp' for stdout.*")
1561 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1562 _, _, err := s.stdoutErrorRunHelper(c, `{
1563 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1564 "output_path": "/tmp",
1567 c.Check(err, ErrorMatches, ".*unsupported mount kind 'collection' for stdout.*")
1570 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1571 s.fullRunHelper(c, `{
1572 "command": ["/bin/sh", "-c", "true $ARVADOS_API_HOST"],
1573 "container_image": "`+arvadostest.DockerImage112PDH+`",
1576 "mounts": {"/tmp": {"kind": "tmp"} },
1577 "output_path": "/tmp",
1579 "runtime_constraints": {"API": true},
1581 }`, nil, 0, func() {
1582 c.Check(s.executor.created.Env["ARVADOS_API_HOST"], Equals, os.Getenv("ARVADOS_API_HOST"))
1583 s.executor.exit <- 3
1585 c.Check(s.api.CalledWith("container.exit_code", 3), NotNil)
1586 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1587 c.Check(s.api.Logs["crunch-run"].String(), Matches, `(?ms).*status code 3\n.*`)
1590 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1591 defer os.Setenv("ARVADOS_API_HOST", os.Getenv("ARVADOS_API_HOST"))
1592 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1593 s.fullRunHelper(c, `{
1594 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1595 "container_image": "`+arvadostest.DockerImage112PDH+`",
1598 "mounts": {"/tmp": {"kind": "tmp"} },
1599 "output_path": "/tmp",
1601 "runtime_constraints": {"API": true},
1603 }`, nil, 0, func() {
1604 s.api.Container.Output = arvadostest.DockerImage112PDH
1607 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1608 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1609 c.Check(s.api.CalledWith("container.output", arvadostest.DockerImage112PDH), NotNil)
1612 func (s *TestSuite) TestArvMountRuntimeStatusWarning(c *C) {
1613 s.runner.RunArvMount = func([]string, string) (*exec.Cmd, error) {
1614 os.Mkdir(s.runner.ArvMountPoint+"/by_id", 0666)
1615 ioutil.WriteFile(s.runner.ArvMountPoint+"/by_id/README", nil, 0666)
1616 return s.runner.ArvMountCmd([]string{"bash", "-c", "echo >&2 Test: Keep write error: I am a teapot; sleep 3"}, "")
1618 s.executor.runFunc = func() {
1619 time.Sleep(time.Second)
1620 s.executor.exit <- 137
1623 "command": ["sleep", "1"],
1624 "container_image": "` + arvadostest.DockerImage112PDH + `",
1627 "mounts": {"/tmp": {"kind": "tmp"} },
1628 "output_path": "/tmp",
1630 "runtime_constraints": {"API": true},
1633 err := json.Unmarshal([]byte(record), &s.api.Container)
1634 c.Assert(err, IsNil)
1635 err = s.runner.Run()
1636 c.Assert(err, IsNil)
1637 c.Check(s.api.CalledWith("container.exit_code", 137), NotNil)
1638 c.Check(s.api.CalledWith("container.runtime_status.warning", "arv-mount: Keep write error"), NotNil)
1639 c.Check(s.api.CalledWith("container.runtime_status.warningDetail", "Test: Keep write error: I am a teapot"), NotNil)
1640 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1641 c.Check(s.api.Logs["crunch-run"].String(), Matches, `(?ms).*Container exited with status code 137 \(signal 9, SIGKILL\).*`)
1644 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1646 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1647 "container_image": "` + arvadostest.DockerImage112PDH + `",
1649 "environment": {"FROBIZ": "bilbo"},
1651 "/tmp": {"kind": "tmp"},
1652 "/tmp/foo": {"kind": "collection",
1653 "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1654 "exclude_from_output": true
1656 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1658 "output_path": "/tmp",
1660 "runtime_constraints": {},
1664 extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1666 s.fullRunHelper(c, helperRecord, extraMounts, 0, func() {
1667 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.Env["FROBIZ"])
1670 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1671 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1672 c.Check(s.runner.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1675 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1677 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1678 "container_image": "` + arvadostest.DockerImage112PDH + `",
1680 "environment": {"FROBIZ": "bilbo"},
1682 "/tmp": {"kind": "tmp"},
1683 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1684 "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1685 "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1686 "/tmp/foo/baz/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1687 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1689 "output_path": "/tmp",
1691 "runtime_constraints": {},
1695 extraMounts := []string{
1696 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1697 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1698 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1701 api, _, realtemp := s.fullRunHelper(c, helperRecord, extraMounts, 0, func() {
1702 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.Env["FROBIZ"])
1705 c.Check(s.executor.created.BindMounts, DeepEquals, map[string]bindmount{
1706 "/tmp": {realtemp + "/tmp1", false},
1707 "/tmp/foo/bar": {s.keepmount + "/by_id/a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt", true},
1708 "/tmp/foo/baz/sub2file2": {s.keepmount + "/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt", true},
1709 "/tmp/foo/sub1": {s.keepmount + "/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1", true},
1710 "/tmp/foo/sub1file2": {s.keepmount + "/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt", true},
1713 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1714 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1715 for _, v := range api.Content {
1716 if v["collection"] != nil {
1717 c.Check(v["ensure_unique_name"], Equals, true)
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 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:bar 36:18:sub1file2
1724 ./foo/baz 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2
1725 ./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1726 ./foo/sub1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1733 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
1735 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1736 "container_image": "` + arvadostest.DockerImage112PDH + `",
1738 "environment": {"FROBIZ": "bilbo"},
1740 "/tmp": {"kind": "tmp"},
1741 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/subdir1/file2_in_subdir1.txt"},
1742 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1744 "output_path": "/tmp",
1746 "runtime_constraints": {},
1750 extraMounts := []string{
1751 "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1754 s.fullRunHelper(c, helperRecord, extraMounts, 0, func() {
1755 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.Env["FROBIZ"])
1758 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1759 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1760 for _, v := range s.api.Content {
1761 if v["collection"] != nil {
1762 collection := v["collection"].(arvadosclient.Dict)
1763 if strings.Index(collection["name"].(string), "output") == 0 {
1764 manifest := collection["manifest_text"].(string)
1766 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1767 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 10:17:bar
1774 func (s *TestSuite) TestOutputError(c *C) {
1776 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1777 "container_image": "` + arvadostest.DockerImage112PDH + `",
1779 "environment": {"FROBIZ": "bilbo"},
1781 "/tmp": {"kind": "tmp"}
1783 "output_path": "/tmp",
1785 "runtime_constraints": {},
1788 s.fullRunHelper(c, helperRecord, nil, 0, func() {
1789 os.Symlink("/etc/hosts", s.runner.HostOutputDir+"/baz")
1792 c.Check(s.api.CalledWith("container.state", "Cancelled"), NotNil)
1795 func (s *TestSuite) TestStdinCollectionMountPoint(c *C) {
1797 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1798 "container_image": "` + arvadostest.DockerImage112PDH + `",
1800 "environment": {"FROBIZ": "bilbo"},
1802 "/tmp": {"kind": "tmp"},
1803 "stdin": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/file1_in_main.txt"},
1804 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1806 "output_path": "/tmp",
1808 "runtime_constraints": {},
1812 extraMounts := []string{
1813 "b0def87f80dd594d4675809e83bd4f15+367/file1_in_main.txt",
1816 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func() {
1817 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.Env["FROBIZ"])
1820 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1821 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1822 for _, v := range api.Content {
1823 if v["collection"] != nil {
1824 collection := v["collection"].(arvadosclient.Dict)
1825 if strings.Index(collection["name"].(string), "output") == 0 {
1826 manifest := collection["manifest_text"].(string)
1827 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1834 func (s *TestSuite) TestStdinJsonMountPoint(c *C) {
1836 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1837 "container_image": "` + arvadostest.DockerImage112PDH + `",
1839 "environment": {"FROBIZ": "bilbo"},
1841 "/tmp": {"kind": "tmp"},
1842 "stdin": {"kind": "json", "content": "foo"},
1843 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1845 "output_path": "/tmp",
1847 "runtime_constraints": {},
1851 api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func() {
1852 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.Env["FROBIZ"])
1855 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1856 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1857 for _, v := range api.Content {
1858 if v["collection"] != nil {
1859 collection := v["collection"].(arvadosclient.Dict)
1860 if strings.Index(collection["name"].(string), "output") == 0 {
1861 manifest := collection["manifest_text"].(string)
1862 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1869 func (s *TestSuite) TestStderrMount(c *C) {
1870 api, cr, _ := s.fullRunHelper(c, `{
1871 "command": ["/bin/sh", "-c", "echo hello;exit 1"],
1872 "container_image": "`+arvadostest.DockerImage112PDH+`",
1875 "mounts": {"/tmp": {"kind": "tmp"},
1876 "stdout": {"kind": "file", "path": "/tmp/a/out.txt"},
1877 "stderr": {"kind": "file", "path": "/tmp/b/err.txt"}},
1878 "output_path": "/tmp",
1880 "runtime_constraints": {},
1882 }`, nil, 1, func() {
1883 fmt.Fprintln(s.executor.created.Stdout, "hello")
1884 fmt.Fprintln(s.executor.created.Stderr, "oops")
1887 final := api.CalledWith("container.state", "Complete")
1888 c.Assert(final, NotNil)
1889 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1890 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1892 c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", "./a b1946ac92492d2347c6235b4d2611184+6 0:6:out.txt\n./b 38af5c54926b620264ab1501150cf189+5 0:5:err.txt\n"), NotNil)
1895 func (s *TestSuite) TestNumberRoundTrip(c *C) {
1896 s.api.callraw = true
1897 err := s.runner.fetchContainerRecord()
1898 c.Assert(err, IsNil)
1899 jsondata, err := json.Marshal(s.runner.Container.Mounts["/json"].Content)
1900 c.Logf("%#v", s.runner.Container)
1902 c.Check(string(jsondata), Equals, `{"number":123456789123456789}`)
1905 func (s *TestSuite) TestFullBrokenDocker(c *C) {
1907 for _, setup := range []func(){
1909 c.Log("// waitErr = ocl runtime error")
1910 s.executor.waitErr = 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\\\"\""`)
1911 nextState = "Cancelled"
1914 c.Log("// loadErr = cannot connect")
1915 s.executor.loadErr = errors.New("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?")
1916 s.runner.brokenNodeHook = c.MkDir() + "/broken-node-hook"
1917 err := ioutil.WriteFile(s.runner.brokenNodeHook, []byte("#!/bin/sh\nexec echo killme\n"), 0700)
1918 c.Assert(err, IsNil)
1919 nextState = "Queued"
1924 s.fullRunHelper(c, `{
1925 "command": ["echo", "hello world"],
1926 "container_image": "`+arvadostest.DockerImage112PDH+`",
1929 "mounts": {"/tmp": {"kind": "tmp"} },
1930 "output_path": "/tmp",
1932 "runtime_constraints": {},
1934 }`, nil, 0, func() {})
1935 c.Check(s.api.CalledWith("container.state", nextState), NotNil)
1936 c.Check(s.api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1937 if s.runner.brokenNodeHook != "" {
1938 c.Check(s.api.Logs["crunch-run"].String(), Matches, "(?ms).*Running broken node hook.*")
1939 c.Check(s.api.Logs["crunch-run"].String(), Matches, "(?ms).*killme.*")
1940 c.Check(s.api.Logs["crunch-run"].String(), Not(Matches), "(?ms).*Writing /var/lock/crunch-run-broken to mark node as broken.*")
1942 c.Check(s.api.Logs["crunch-run"].String(), Matches, "(?ms).*Writing /var/lock/crunch-run-broken to mark node as broken.*")
1947 func (s *TestSuite) TestBadCommand(c *C) {
1948 for _, startError := range []string{
1949 `panic: standard_init_linux.go:175: exec user process caused "no such file or directory"`,
1950 `Error response from daemon: Cannot start container 41f26cbc43bcc1280f4323efb1830a394ba8660c9d1c2b564ba42bf7f7694845: [8] System error: no such file or directory`,
1951 `Error response from daemon: Cannot start container 58099cd76c834f3dc2a4fb76c8028f049ae6d4fdf0ec373e1f2cfea030670c2d: [8] System error: exec: "foobar": executable file not found in $PATH`,
1954 s.executor.startErr = errors.New(startError)
1955 s.fullRunHelper(c, `{
1956 "command": ["echo", "hello world"],
1957 "container_image": "`+arvadostest.DockerImage112PDH+`",
1960 "mounts": {"/tmp": {"kind": "tmp"} },
1961 "output_path": "/tmp",
1963 "runtime_constraints": {},
1965 }`, nil, 0, func() {})
1966 c.Check(s.api.CalledWith("container.state", "Cancelled"), NotNil)
1967 c.Check(s.api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
1971 func (s *TestSuite) TestSecretTextMountPoint(c *C) {
1973 "command": ["true"],
1974 "container_image": "` + arvadostest.DockerImage112PDH + `",
1977 "/tmp": {"kind": "tmp"},
1978 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
1982 "output_path": "/tmp",
1984 "runtime_constraints": {},
1988 s.fullRunHelper(c, helperRecord, nil, 0, func() {
1989 content, err := ioutil.ReadFile(s.runner.HostOutputDir + "/secret.conf")
1991 c.Check(string(content), Equals, "mypassword")
1994 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1995 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1996 c.Check(s.runner.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), NotNil)
1997 c.Check(s.runner.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ""), IsNil)
1999 // under secret mounts, not captured in output
2001 "command": ["true"],
2002 "container_image": "` + arvadostest.DockerImage112PDH + `",
2005 "/tmp": {"kind": "tmp"}
2008 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2010 "output_path": "/tmp",
2012 "runtime_constraints": {},
2017 s.fullRunHelper(c, helperRecord, nil, 0, func() {
2018 content, err := ioutil.ReadFile(s.runner.HostOutputDir + "/secret.conf")
2020 c.Check(string(content), Equals, "mypassword")
2023 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
2024 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
2025 c.Check(s.runner.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), IsNil)
2026 c.Check(s.runner.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ""), NotNil)
2028 // under secret mounts, output dir is a collection, not captured in output
2030 "command": ["true"],
2031 "container_image": "` + arvadostest.DockerImage112PDH + `",
2034 "/tmp": {"kind": "collection", "writable": true}
2037 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2039 "output_path": "/tmp",
2041 "runtime_constraints": {},
2046 _, _, realtemp := s.fullRunHelper(c, helperRecord, nil, 0, func() {
2047 // secret.conf should be provisioned as a separate
2048 // bind mount, i.e., it should not appear in the
2049 // (fake) fuse filesystem as viewed from the host.
2050 content, err := ioutil.ReadFile(s.runner.HostOutputDir + "/secret.conf")
2051 if !c.Check(errors.Is(err, os.ErrNotExist), Equals, true) {
2052 c.Logf("secret.conf: content %q, err %#v", content, err)
2054 err = ioutil.WriteFile(s.runner.HostOutputDir+"/.arvados#collection", []byte(`{"manifest_text":". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo.txt\n"}`), 0700)
2058 content, err := ioutil.ReadFile(realtemp + "/text1/mountdata.text")
2060 c.Check(string(content), Equals, "mypassword")
2061 c.Check(s.executor.created.BindMounts["/tmp/secret.conf"], DeepEquals, bindmount{realtemp + "/text1/mountdata.text", true})
2062 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
2063 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
2064 c.Check(s.runner.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo.txt\n"), NotNil)
2067 type FakeProcess struct {
2071 func (fp FakeProcess) CmdlineSlice() ([]string, error) {
2072 return fp.cmdLine, nil