1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
34 "git.arvados.org/arvados.git/lib/cloud"
35 "git.arvados.org/arvados.git/lib/cmd"
36 "git.arvados.org/arvados.git/sdk/go/arvados"
37 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
38 "git.arvados.org/arvados.git/sdk/go/arvadostest"
39 "git.arvados.org/arvados.git/sdk/go/manifest"
44 // Gocheck boilerplate
45 func TestCrunchExec(t *testing.T) {
49 const logLineStart = `(?m)(.*\n)*\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d+Z `
51 var _ = Suite(&TestSuite{})
53 type TestSuite struct {
54 client *arvados.Client
56 runner *ContainerRunner
57 executor *stubExecutor
60 testDispatcherKeepClient KeepTestClient
61 testContainerKeepClient KeepTestClient
62 debian12MemoryCurrent int64
63 debian12SwapCurrent int64
66 func (s *TestSuite) SetUpSuite(c *C) {
67 buf, err := os.ReadFile("../crunchstat/testdata/debian12/sys/fs/cgroup/user.slice/user-1000.slice/session-4.scope/memory.current")
69 _, err = fmt.Sscanf(string(buf), "%d", &s.debian12MemoryCurrent)
72 buf, err = os.ReadFile("../crunchstat/testdata/debian12/sys/fs/cgroup/user.slice/user-1000.slice/session-4.scope/memory.swap.current")
74 _, err = fmt.Sscanf(string(buf), "%d", &s.debian12SwapCurrent)
78 func (s *TestSuite) SetUpTest(c *C) {
79 s.client = arvados.NewClientFromEnv()
80 s.executor = &stubExecutor{}
82 s.api = &ArvTestClient{}
83 s.runner, err = NewContainerRunner(s.client, s.api, &s.testDispatcherKeepClient, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
85 s.runner.executor = s.executor
86 s.runner.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
87 return s.api, &s.testContainerKeepClient, s.client, nil
89 s.runner.RunArvMount = func(cmd []string, tok string) (*exec.Cmd, error) {
90 s.runner.ArvMountPoint = s.keepmount
91 for i, opt := range cmd {
92 if opt == "--mount-tmp" {
93 err := os.Mkdir(s.keepmount+"/"+cmd[i+1], 0700)
97 s.keepmountTmp = append(s.keepmountTmp, cmd[i+1])
102 s.keepmount = c.MkDir()
103 err = os.Mkdir(s.keepmount+"/by_id", 0755)
106 err = os.Mkdir(s.keepmount+"/by_id/"+arvadostest.DockerImage112PDH, 0755)
108 err = ioutil.WriteFile(s.keepmount+"/by_id/"+arvadostest.DockerImage112PDH+"/"+arvadostest.DockerImage112Filename, []byte("#notarealtarball"), 0644)
109 err = os.Mkdir(s.keepmount+"/by_id/"+fakeInputCollectionPDH, 0755)
111 err = ioutil.WriteFile(s.keepmount+"/by_id/"+fakeInputCollectionPDH+"/input.json", []byte(`{"input":true}`), 0644)
113 s.runner.ArvMountPoint = s.keepmount
114 os.Setenv("InstanceType", `{"ProviderType":"a1.2xlarge","Price":1.2}`)
117 type ArvTestClient struct {
120 Content []arvadosclient.Dict
128 type KeepTestClient struct {
130 StorageClasses []string
134 type stubExecutor struct {
140 created containerSpec
142 waitSleep time.Duration
151 func (e *stubExecutor) LoadImage(imageId string, tarball string, container arvados.Container, keepMount string,
152 containerClient *arvados.Client) error {
156 func (e *stubExecutor) Runtime() string { return "stub" }
157 func (e *stubExecutor) Version() string { return "stub " + cmd.Version.String() }
158 func (e *stubExecutor) Create(spec containerSpec) error { e.created = spec; return e.createErr }
159 func (e *stubExecutor) Start() error {
160 e.exit = make(chan int, 1)
161 go func() { e.exit <- e.runFunc() }()
164 func (e *stubExecutor) Pid() int { return 1115883 } // matches pid in ../crunchstat/testdata/debian12/proc/
165 func (e *stubExecutor) Stop() error { e.stopped = true; go func() { e.exit <- -1 }(); return e.stopErr }
166 func (e *stubExecutor) Close() { e.closed = true }
167 func (e *stubExecutor) Wait(context.Context) (int, error) {
168 return <-e.exit, e.waitErr
170 func (e *stubExecutor) InjectCommand(ctx context.Context, _, _ string, _ bool, _ []string) (*exec.Cmd, error) {
171 return nil, errors.New("unimplemented")
173 func (e *stubExecutor) IPAddress() (string, error) { return "", errors.New("unimplemented") }
175 const fakeInputCollectionPDH = "ffffffffaaaaaaaa88888888eeeeeeee+1234"
177 var hwManifest = ". 82ab40c24fc8df01798e57ba66795bb1+841216+Aa124ac75e5168396c73c0a18eda641a4f41791c0@569fa8c3 0:841216:9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7.tar\n"
178 var hwPDH = "a45557269dcb65a6b78f9ac061c0850b+120"
179 var hwImageID = "9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7"
181 var otherManifest = ". 68a84f561b1d1708c6baff5e019a9ab3+46+Ae5d0af96944a3690becb1decdf60cc1c937f556d@5693216f 0:46:md5sum.txt\n"
182 var otherPDH = "a3e8f74c6f101eae01fa08bfb4e49b3a+54"
184 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
185 ./subdir1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
186 ./subdir1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
189 var normalizedWithSubdirsPDH = "a0def87f80dd594d4675809e83bd4f15+367"
191 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"
192 var denormalizedWithSubdirsPDH = "b0def87f80dd594d4675809e83bd4f15+367"
194 var fakeAuthUUID = "zzzzz-gj3su-55pqoyepgi2glem"
195 var fakeAuthToken = "a3ltuwzqcu2u4sc0q7yhpc2w7s00fdcqecg5d6e0u3pfohmbjt"
197 func (client *ArvTestClient) Create(resourceType string,
198 parameters arvadosclient.Dict,
199 output interface{}) error {
202 defer client.Mutex.Unlock()
205 client.Content = append(client.Content, parameters)
207 if resourceType == "logs" {
208 panic("logs.create called")
211 if resourceType == "collections" && output != nil {
212 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
213 md5sum := md5.Sum([]byte(mt))
214 outmap := output.(*arvados.Collection)
215 outmap.PortableDataHash = fmt.Sprintf("%x+%d", md5sum, len(mt))
216 outmap.UUID = fmt.Sprintf("zzzzz-4zz18-%015x", md5sum[:7])
222 func (client *ArvTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
224 case method == "GET" && resourceType == "containers" && action == "auth":
225 return json.Unmarshal([]byte(`{
226 "kind": "arvados#api_client_authorization",
227 "uuid": "`+fakeAuthUUID+`",
228 "api_token": "`+fakeAuthToken+`"
230 case method == "GET" && resourceType == "containers" && action == "secret_mounts":
231 if client.secretMounts != nil {
232 return json.Unmarshal(client.secretMounts, output)
234 return json.Unmarshal([]byte(`{"secret_mounts":{}}`), output)
236 return fmt.Errorf("Not found")
240 func (client *ArvTestClient) CallRaw(method, resourceType, uuid, action string,
241 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
243 if method == "GET" && resourceType == "nodes" && uuid == "" && action == "" {
245 "kind": "arvados#nodeList",
247 "uuid": "zzzzz-7ekkf-2z3mc76g2q73aio",
248 "hostname": "compute2",
249 "properties": {"total_cpu_cores": 16}
251 } else if method == "GET" && resourceType == "containers" && action == "" && !client.callraw {
253 j, err = json.Marshal(map[string]interface{}{
254 "items": []interface{}{client.Container},
255 "kind": "arvados#nodeList",
258 j, err = json.Marshal(client.Container)
262 "command": ["sleep", "1"],
263 "container_image": "` + arvadostest.DockerImage112PDH + `",
266 "mounts": {"/tmp": {"kind": "tmp"}, "/json": {"kind": "json", "content": {"number": 123456789123456789}}},
267 "output_path": "/tmp",
269 "runtime_constraints": {}
272 return ioutil.NopCloser(bytes.NewReader(j)), err
275 func (client *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
276 if resourceType == "collections" {
278 output.(*arvados.Collection).ManifestText = hwManifest
279 } else if uuid == otherPDH {
280 output.(*arvados.Collection).ManifestText = otherManifest
281 } else if uuid == normalizedWithSubdirsPDH {
282 output.(*arvados.Collection).ManifestText = normalizedManifestWithSubdirs
283 } else if uuid == denormalizedWithSubdirsPDH {
284 output.(*arvados.Collection).ManifestText = denormalizedManifestWithSubdirs
287 if resourceType == "containers" {
288 (*output.(*arvados.Container)) = client.Container
293 func (client *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
295 defer client.Mutex.Unlock()
297 client.Content = append(client.Content, parameters)
298 if resourceType == "containers" {
299 if parameters["container"].(arvadosclient.Dict)["state"] == "Running" {
300 client.WasSetRunning = true
302 } else if resourceType == "collections" && output != nil {
303 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
304 output.(*arvados.Collection).UUID = uuid
305 output.(*arvados.Collection).PortableDataHash = arvados.PortableDataHash(mt)
310 var discoveryMap = map[string]interface{}{
311 "crunchLogUpdateSize": float64(crunchLogUpdateSize),
312 "crunchLogUpdatePeriod": float64(crunchLogUpdatePeriod.Seconds()),
315 func (client *ArvTestClient) Discovery(key string) (interface{}, error) {
316 return discoveryMap[key], nil
319 // CalledWith returns the parameters from the first API call whose
320 // parameters match jpath/string. E.g., CalledWith(c, "foo.bar",
321 // "baz") returns parameters with parameters["foo"]["bar"]=="baz". If
322 // no call matches, it returns nil.
323 func (client *ArvTestClient) CalledWith(jpath string, expect interface{}) arvadosclient.Dict {
325 for _, content := range client.Content {
326 var v interface{} = content
327 for _, k := range strings.Split(jpath, ".") {
328 if dict, ok := v.(arvadosclient.Dict); !ok {
341 func (client *KeepTestClient) LocalLocator(locator string) (string, error) {
345 func (client *KeepTestClient) BlockWrite(_ context.Context, opts arvados.BlockWriteOptions) (arvados.BlockWriteResponse, error) {
346 locator := fmt.Sprintf("%x+%d", md5.Sum(opts.Data), len(opts.Data))
347 client.blocks.Store(locator, append([]byte(nil), opts.Data...))
348 return arvados.BlockWriteResponse{
353 func (client *KeepTestClient) ReadAt(locator string, dst []byte, offset int) (int, error) {
354 loaded, ok := client.blocks.Load(locator)
356 return 0, os.ErrNotExist
358 data := loaded.([]byte)
359 if offset >= len(data) {
362 return copy(dst, data[offset:]), nil
365 func (client *KeepTestClient) Close() {
366 client.blocks.Range(func(locator, value interface{}) bool {
367 client.blocks.Delete(locator)
372 func (client *KeepTestClient) SetStorageClasses(sc []string) {
373 client.StorageClasses = sc
376 type FileWrapper struct {
381 func (fw FileWrapper) Readdir(n int) ([]os.FileInfo, error) {
382 return nil, errors.New("not implemented")
385 func (fw FileWrapper) Seek(int64, int) (int64, error) {
386 return 0, errors.New("not implemented")
389 func (fw FileWrapper) Size() int64 {
393 func (fw FileWrapper) Stat() (os.FileInfo, error) {
394 return nil, errors.New("not implemented")
397 func (fw FileWrapper) Truncate(int64) error {
398 return errors.New("not implemented")
401 func (fw FileWrapper) Write([]byte) (int, error) {
402 return 0, errors.New("not implemented")
405 func (fw FileWrapper) Sync() error {
406 return errors.New("not implemented")
409 func (fw FileWrapper) Snapshot() (*arvados.Subtree, error) {
410 return nil, errors.New("not implemented")
413 func (fw FileWrapper) Splice(*arvados.Subtree) error {
414 return errors.New("not implemented")
417 func (client *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
418 if filename == hwImageID+".tar" {
419 rdr := ioutil.NopCloser(&bytes.Buffer{})
421 return FileWrapper{rdr, 1321984}, nil
422 } else if filename == "/file1_in_main.txt" {
423 rdr := ioutil.NopCloser(strings.NewReader("foo"))
425 return FileWrapper{rdr, 3}, nil
430 type apiStubServer struct {
431 server *httptest.Server
432 proxy *httputil.ReverseProxy
433 intercept func(http.ResponseWriter, *http.Request) bool
435 container arvados.Container
436 logs map[string]string
439 func apiStub() (*arvados.Client, *apiStubServer) {
440 client := arvados.NewClientFromEnv()
441 apistub := &apiStubServer{}
442 apistub.server = httptest.NewTLSServer(apistub)
443 apistub.proxy = httputil.NewSingleHostReverseProxy(&url.URL{Scheme: "https", Host: client.APIHost})
445 apistub.proxy.Transport = arvados.InsecureHTTPClient.Transport
447 client.APIHost = apistub.server.Listener.Addr().String()
448 return client, apistub
451 func (apistub *apiStubServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
452 if apistub.intercept != nil && apistub.intercept(w, r) {
455 if r.Method == "POST" && r.URL.Path == "/arvados/v1/logs" {
458 EventType string `json:"event_type"`
464 json.NewDecoder(r.Body).Decode(&body)
465 apistub.logs[body.Log.EventType] += body.Log.Properties.Text
468 if r.Method == "GET" && r.URL.Path == "/arvados/v1/collections/"+hwPDH {
469 json.NewEncoder(w).Encode(arvados.Collection{ManifestText: hwManifest})
472 if r.Method == "GET" && r.URL.Path == "/arvados/v1/collections/"+otherPDH {
473 json.NewEncoder(w).Encode(arvados.Collection{ManifestText: otherManifest})
476 if r.Method == "GET" && r.URL.Path == "/arvados/v1/collections/"+normalizedWithSubdirsPDH {
477 json.NewEncoder(w).Encode(arvados.Collection{ManifestText: normalizedManifestWithSubdirs})
480 if r.Method == "GET" && r.URL.Path == "/arvados/v1/collections/"+denormalizedWithSubdirsPDH {
481 json.NewEncoder(w).Encode(arvados.Collection{ManifestText: denormalizedManifestWithSubdirs})
484 if r.Method == "GET" && r.URL.Path == "/arvados/v1/containers/"+apistub.container.UUID {
485 json.NewEncoder(w).Encode(apistub.container)
488 apistub.proxy.ServeHTTP(w, r)
491 func (s *TestSuite) TestLoadImage(c *C) {
492 s.runner.Container.ContainerImage = arvadostest.DockerImage112PDH
493 s.runner.Container.Mounts = map[string]arvados.Mount{
494 "/out": {Kind: "tmp", Writable: true},
496 s.runner.Container.OutputPath = "/out"
498 _, err := s.runner.SetupMounts()
501 imageID, err := s.runner.LoadImage()
503 c.Check(s.executor.loaded, Matches, ".*"+regexp.QuoteMeta(arvadostest.DockerImage112Filename))
504 c.Check(imageID, Equals, strings.TrimSuffix(arvadostest.DockerImage112Filename, ".tar"))
506 s.runner.Container.ContainerImage = arvadostest.DockerImage112PDH
507 s.executor.imageLoaded = false
508 s.executor.loaded = ""
509 s.executor.loadErr = errors.New("bork")
510 imageID, err = s.runner.LoadImage()
511 c.Check(err, ErrorMatches, ".*bork")
512 c.Check(s.executor.loaded, Matches, ".*"+regexp.QuoteMeta(arvadostest.DockerImage112Filename))
514 s.runner.Container.ContainerImage = fakeInputCollectionPDH
515 s.executor.imageLoaded = false
516 s.executor.loaded = ""
517 s.executor.loadErr = nil
518 imageID, err = s.runner.LoadImage()
519 c.Check(err, ErrorMatches, "image collection does not include a \\.tar image file")
520 c.Check(s.executor.loaded, Equals, "")
523 type ArvErrorTestClient struct{}
525 func (ArvErrorTestClient) Create(resourceType string,
526 parameters arvadosclient.Dict,
527 output interface{}) error {
531 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
532 if method == "GET" && resourceType == "containers" && action == "auth" {
535 return errors.New("ArvError")
538 func (ArvErrorTestClient) CallRaw(method, resourceType, uuid, action string,
539 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
540 return nil, errors.New("ArvError")
543 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
544 return errors.New("ArvError")
547 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
551 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
552 return discoveryMap[key], nil
555 type KeepErrorTestClient struct {
559 func (*KeepErrorTestClient) ManifestFileReader(manifest.Manifest, string) (arvados.File, error) {
560 return nil, errors.New("KeepError")
563 func (*KeepErrorTestClient) BlockWrite(context.Context, arvados.BlockWriteOptions) (arvados.BlockWriteResponse, error) {
564 return arvados.BlockWriteResponse{}, errors.New("KeepError")
567 func (*KeepErrorTestClient) LocalLocator(string) (string, error) {
568 return "", errors.New("KeepError")
571 type KeepReadErrorTestClient struct {
575 func (*KeepReadErrorTestClient) ReadAt(string, []byte, int) (int, error) {
576 return 0, errors.New("KeepError")
579 type ErrorReader struct {
583 func (ErrorReader) Read(p []byte) (n int, err error) {
584 return 0, errors.New("ErrorReader")
587 func (ErrorReader) Seek(int64, int) (int64, error) {
588 return 0, errors.New("ErrorReader")
591 func (*KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
592 return ErrorReader{}, nil
595 func dockerLog(fd byte, msg string) []byte {
597 header := make([]byte, 8+len(by))
599 header[7] = byte(len(by))
604 func (s *TestSuite) TestRunContainer(c *C) {
605 s.executor.runFunc = func() int {
606 fmt.Fprintf(s.executor.created.Stdout, "Hello world\n")
610 s.runner.Container.ContainerImage = arvadostest.DockerImage112PDH
611 s.runner.Container.Command = []string{"./hw"}
612 s.runner.Container.OutputStorageClasses = []string{"default"}
614 imageID, err := s.runner.LoadImage()
617 err = s.runner.CreateContainer(imageID, nil)
620 err = s.runner.StartContainer()
623 err = s.runner.WaitFinish()
626 c.Check(logFileContent(c, s.runner, "stdout.txt"), Matches, `2\S+Z Hello world\n`)
627 c.Check(logFileContent(c, s.runner, "stderr.txt"), Matches, ``)
630 func (s *TestSuite) TestCommitLogs(c *C) {
631 api := &ArvTestClient{}
632 kc := &KeepTestClient{}
634 cr, err := NewContainerRunner(s.client, api, kc, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
636 f, err := cr.openLogFile("crunch-run")
638 cr.CrunchLog = newLogWriter(newTestTimestamper(f))
640 cr.CrunchLog.Print("Hello world!")
641 cr.CrunchLog.Print("Goodbye")
642 cr.finalState = "Complete"
644 err = cr.CommitLogs()
647 c.Check(api.Calls, Equals, 1)
648 c.Check(api.Content[0]["ensure_unique_name"], Equals, true)
649 c.Check(api.Content[0]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
650 c.Check(api.Content[0]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
651 c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
654 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
655 api := &ArvTestClient{}
656 kc := &KeepTestClient{}
658 cr, err := NewContainerRunner(s.client, api, kc, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
661 err = cr.UpdateContainerRunning("")
664 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
667 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
668 api := &ArvTestClient{}
669 kc := &KeepTestClient{}
671 cr, err := NewContainerRunner(s.client, api, kc, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
674 cr.LogsPDH = new(string)
675 *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
677 cr.ExitCode = new(int)
679 cr.finalState = "Complete"
681 err = cr.UpdateContainerFinal()
684 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
685 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
686 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
689 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
690 api := &ArvTestClient{}
691 kc := &KeepTestClient{}
693 cr, err := NewContainerRunner(s.client, api, kc, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
696 cr.finalState = "Cancelled"
698 err = cr.UpdateContainerFinal()
701 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
702 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
703 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
706 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
707 // dress rehearsal of the Run() function, starting from a JSON container record.
708 func (s *TestSuite) fullRunHelper(c *C, record string, extraMounts []string, fn func() int) (*ArvTestClient, *ContainerRunner, string) {
709 err := json.Unmarshal([]byte(record), &s.api.Container)
711 initialState := s.api.Container.State
714 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
716 err = json.Unmarshal([]byte(record), &sm)
718 secretMounts, err := json.Marshal(sm)
720 c.Logf("SecretMounts decoded %v json %q", sm, secretMounts)
722 s.executor.runFunc = fn
724 s.runner.statInterval = 100 * time.Millisecond
725 s.runner.containerWatchdogInterval = time.Second
727 realTemp := c.MkDir()
729 s.runner.MkTempDir = func(_, prefix string) (string, error) {
731 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, tempcount)
732 err := os.Mkdir(d, os.ModePerm)
733 if err != nil && strings.Contains(err.Error(), ": file exists") {
734 // Test case must have pre-populated the tempdir
739 client, _ := apiStub()
740 s.runner.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
741 return &ArvTestClient{secretMounts: secretMounts}, &s.testContainerKeepClient, client, nil
744 if extraMounts != nil && len(extraMounts) > 0 {
745 err := s.runner.SetupArvMountPoint("keep")
748 for _, m := range extraMounts {
749 os.MkdirAll(s.runner.ArvMountPoint+"/by_id/"+m, os.ModePerm)
754 if s.api.CalledWith("container.state", "Complete") != nil {
757 if s.executor.loadErr == nil && s.executor.createErr == nil && initialState != "Running" {
758 c.Check(s.api.WasSetRunning, Equals, true)
759 var lastupdate arvadosclient.Dict
760 for _, content := range s.api.Content {
761 if content["container"] != nil {
762 lastupdate = content["container"].(arvadosclient.Dict)
765 if lastupdate["log"] == nil {
766 c.Errorf("no container update with non-nil log -- updates were: %v", s.api.Content)
771 dumpAllLogFiles(c, s.runner)
774 return s.api, s.runner, realTemp
777 func (s *TestSuite) TestFullRunHello(c *C) {
778 s.runner.enableMemoryLimit = true
779 s.runner.networkMode = "default"
780 s.fullRunHelper(c, `{
781 "command": ["echo", "hello world"],
782 "container_image": "`+arvadostest.DockerImage112PDH+`",
784 "environment": {"foo":"bar","baz":"waz"},
785 "mounts": {"/tmp": {"kind": "tmp"} },
786 "output_path": "/tmp",
788 "runtime_constraints": {"vcpus":1,"ram":1000000},
790 "output_storage_classes": ["default"]
791 }`, nil, func() int {
792 c.Check(s.executor.created.Command, DeepEquals, []string{"echo", "hello world"})
793 c.Check(s.executor.created.Image, Equals, "sha256:d8309758b8fe2c81034ffc8a10c36460b77db7bc5e7b448c4e5b684f9d95a678")
794 c.Check(s.executor.created.Env, DeepEquals, map[string]string{"foo": "bar", "baz": "waz"})
795 c.Check(s.executor.created.VCPUs, Equals, 1)
796 c.Check(s.executor.created.RAM, Equals, int64(1000000))
797 c.Check(s.executor.created.NetworkMode, Equals, "default")
798 c.Check(s.executor.created.EnableNetwork, Equals, false)
799 c.Check(s.executor.created.CUDADeviceCount, Equals, 0)
800 fmt.Fprintln(s.executor.created.Stdout, "hello world")
804 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
805 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
806 c.Check(logFileContent(c, s.runner, "stdout.txt"), Matches, `2\S+Z hello world\n`)
807 c.Check(s.testDispatcherKeepClient.StorageClasses, DeepEquals, []string{"default"})
808 c.Check(s.testContainerKeepClient.StorageClasses, DeepEquals, []string{"default"})
811 func (s *TestSuite) TestRunAlreadyRunning(c *C) {
813 s.fullRunHelper(c, `{
814 "command": ["sleep", "3"],
815 "container_image": "`+arvadostest.DockerImage112PDH+`",
818 "mounts": {"/tmp": {"kind": "tmp"} },
819 "output_path": "/tmp",
821 "runtime_constraints": {},
822 "scheduling_parameters":{"max_run_time": 1},
824 }`, nil, func() int {
828 c.Check(s.api.CalledWith("container.state", "Cancelled"), IsNil)
829 c.Check(s.api.CalledWith("container.state", "Complete"), IsNil)
830 c.Check(ran, Equals, false)
833 func ec2MetadataServerStub(c *C, token *string, failureRate float64, stoptime *atomic.Value) *httptest.Server {
835 return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
836 if !failedOnce || rand.Float64() < failureRate {
837 w.WriteHeader(http.StatusServiceUnavailable)
842 case "/latest/api/token":
843 fmt.Fprintln(w, *token)
844 case "/latest/meta-data/spot/instance-action":
845 if r.Header.Get("X-aws-ec2-metadata-token") != *token {
846 w.WriteHeader(http.StatusUnauthorized)
847 } else if t, _ := stoptime.Load().(time.Time); t.IsZero() {
848 w.WriteHeader(http.StatusNotFound)
850 fmt.Fprintf(w, `{"action":"stop","time":"%s"}`, t.Format(time.RFC3339))
853 w.WriteHeader(http.StatusNotFound)
858 func (s *TestSuite) TestSpotInterruptionNotice(c *C) {
859 s.testSpotInterruptionNotice(c, 0.1)
862 func (s *TestSuite) TestSpotInterruptionNoticeNotAvailable(c *C) {
863 s.testSpotInterruptionNotice(c, 1)
866 func (s *TestSuite) testSpotInterruptionNotice(c *C, failureRate float64) {
867 var stoptime atomic.Value
868 token := "fake-ec2-metadata-token"
869 stub := ec2MetadataServerStub(c, &token, failureRate, &stoptime)
872 defer func(i time.Duration, u string) {
873 spotInterruptionCheckInterval = i
874 ec2MetadataBaseURL = u
875 }(spotInterruptionCheckInterval, ec2MetadataBaseURL)
876 spotInterruptionCheckInterval = time.Second / 8
877 ec2MetadataBaseURL = stub.URL
880 checkLogs := func() {
882 c.Check(logFileContent(c, s.runner, "crunch-run.txt"), Matches, `(?ms).*Checking for spot interruptions every 125ms using instance metadata at http://.*`)
883 c.Check(logFileContent(c, s.runner, "crunch-run.txt"), Matches, `(?ms).*Error checking spot interruptions: 503 Service Unavailable.*`)
884 if failureRate == 1 {
885 c.Check(logFileContent(c, s.runner, "crunch-run.txt"), Matches, `(?ms).*Giving up on checking spot interruptions after too many consecutive failures.*`)
888 text := `Cloud provider scheduled instance stop at ` + stoptime.Load().(time.Time).Format(time.RFC3339)
889 c.Check(logFileContent(c, s.runner, "crunch-run.txt"), Matches, `(?ms).*`+text+`.*`)
890 c.Check(s.api.CalledWith("container.runtime_status.warning", "preemption notice"), NotNil)
891 c.Check(s.api.CalledWith("container.runtime_status.warningDetail", text), NotNil)
892 c.Check(s.api.CalledWith("container.runtime_status.preemptionNotice", text), NotNil)
894 // Check that the log collection was saved, and the
895 // container record updated with the new PDH,
896 // immediately after the preemption notice was
897 // received -- i.e., while the container is still
900 saved := make(map[string]string) // pdh => manifest_text
901 for _, call := range s.api.Content {
902 if ctr, ok := call["container"].(arvadosclient.Dict); ok {
903 if pdh, ok := ctr["log"].(string); ok {
907 if coll, ok := call["collection"].(arvadosclient.Dict); ok {
908 mt, _ := coll["manifest_text"].(string)
909 if strings.Contains(mt, ":crunch-run.txt") {
910 saved[arvados.PortableDataHash(mt)] = mt
914 logfs, err := (&arvados.Collection{ManifestText: saved[lastpdh]}).FileSystem(s.runner.dispatcherClient, s.runner.DispatcherKeepClient)
916 log, err := fs.ReadFile(arvados.FS(logfs), "crunch-run.txt")
918 c.Check(string(log), Matches, `(?ms).*\Q`+text+`\E.*`)
921 go s.runner.checkSpotInterruptionNotices()
922 s.fullRunHelper(c, `{
923 "command": ["sleep", "3"],
924 "container_image": "`+arvadostest.DockerImage112PDH+`",
927 "mounts": {"/tmp": {"kind": "tmp"} },
928 "output_path": "/tmp",
930 "runtime_constraints": {},
932 }`, nil, func() int {
933 time.Sleep(time.Second)
934 stoptime.Store(time.Now().Add(time.Minute).UTC())
935 token = "different-fake-ec2-metadata-token"
936 time.Sleep(time.Second)
940 c.Check(checkedLogs, Equals, true)
943 func (s *TestSuite) TestRunTimeExceeded(c *C) {
944 s.fullRunHelper(c, `{
945 "command": ["sleep", "3"],
946 "container_image": "`+arvadostest.DockerImage112PDH+`",
949 "mounts": {"/tmp": {"kind": "tmp"} },
950 "output_path": "/tmp",
952 "runtime_constraints": {},
953 "scheduling_parameters":{"max_run_time": 1},
955 }`, nil, func() int {
956 time.Sleep(3 * time.Second)
960 c.Check(s.api.CalledWith("container.state", "Cancelled"), NotNil)
961 c.Check(logFileContent(c, s.runner, "crunch-run.txt"), Matches, "(?ms).*maximum run time exceeded.*")
964 func (s *TestSuite) TestContainerWaitFails(c *C) {
965 s.fullRunHelper(c, `{
966 "command": ["sleep", "3"],
967 "container_image": "`+arvadostest.DockerImage112PDH+`",
969 "mounts": {"/tmp": {"kind": "tmp"} },
970 "output_path": "/tmp",
973 }`, nil, func() int {
974 s.executor.waitErr = errors.New("Container is not running")
978 c.Check(s.api.CalledWith("container.state", "Cancelled"), NotNil)
979 c.Check(logFileContent(c, s.runner, "crunch-run.txt"), Matches, "(?ms).*Container is not running.*")
982 func (s *TestSuite) TestCrunchstat(c *C) {
983 s.runner.crunchstatFakeFS = os.DirFS("../crunchstat/testdata/debian12")
984 s.fullRunHelper(c, `{
985 "command": ["sleep", "1"],
986 "container_image": "`+arvadostest.DockerImage112PDH+`",
989 "mounts": {"/tmp": {"kind": "tmp"} },
990 "output_path": "/tmp",
992 "runtime_constraints": {},
994 }`, nil, func() int {
995 time.Sleep(time.Second)
999 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1000 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1002 c.Check(logFileContent(c, s.runner, "crunchstat.txt"), Matches, `(?ms).*mem \d+ swap \d+ pgmajfault \d+ rss.*`)
1004 // Check that we called (*crunchstat.Reporter)Stop().
1005 c.Check(logFileContent(c, s.runner, "crunch-run.txt"), Matches, `(?ms).*Maximum crunch-run memory rss usage was \d+ bytes\n.*`)
1008 func (s *TestSuite) TestNodeInfoLog(c *C) {
1009 s.fullRunHelper(c, `{
1010 "command": ["true"],
1011 "container_image": "`+arvadostest.DockerImage112PDH+`",
1014 "mounts": {"/tmp": {"kind": "tmp"} },
1015 "output_path": "/tmp",
1017 "runtime_constraints": {},
1019 }`, nil, func() int {
1023 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1024 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1026 json := logFileContent(c, s.runner, "node.json")
1027 c.Check(json, Matches, `(?ms).*"ProviderType": *"a1\.2xlarge".*`)
1028 c.Check(json, Matches, `(?ms).*"Price": *1\.2.*`)
1030 nodeinfo := logFileContent(c, s.runner, "node-info.txt")
1031 c.Check(nodeinfo, Matches, `(?ms).*Host Information.*`)
1032 c.Check(nodeinfo, Matches, `(?ms).*CPU Information.*`)
1033 c.Check(nodeinfo, Matches, `(?ms).*Memory Information.*`)
1034 c.Check(nodeinfo, Matches, `(?ms).*Disk Space.*`)
1035 c.Check(nodeinfo, Matches, `(?ms).*Disk INodes.*`)
1038 func (s *TestSuite) TestLogVersionAndRuntime(c *C) {
1039 s.fullRunHelper(c, `{
1040 "command": ["sleep", "1"],
1041 "container_image": "`+arvadostest.DockerImage112PDH+`",
1044 "mounts": {"/tmp": {"kind": "tmp"} },
1045 "output_path": "/tmp",
1047 "runtime_constraints": {},
1049 }`, nil, func() int {
1053 c.Check(logFileContent(c, s.runner, "crunch-run.txt"), Matches, `(?ms).*crunch-run \S+ \(go\S+\) start.*`)
1054 c.Check(logFileContent(c, s.runner, "crunch-run.txt"), Matches, `(?ms).*crunch-run process has uid=\d+\(.+\) gid=\d+\(.+\) groups=\d+\(.+\)(,\d+\(.+\))*\n.*`)
1055 c.Check(logFileContent(c, s.runner, "crunch-run.txt"), Matches, `(?ms).*Executing container: zzzzz-zzzzz-zzzzzzzzzzzzzzz.*`)
1056 c.Check(logFileContent(c, s.runner, "crunch-run.txt"), Matches, `(?ms).*Using container runtime: stub.*`)
1059 func (s *TestSuite) testLogRSSThresholds(c *C, ram int64, expected []int, notExpected int) {
1060 s.runner.crunchstatFakeFS = os.DirFS("../crunchstat/testdata/debian12")
1061 s.fullRunHelper(c, `{
1062 "command": ["true"],
1063 "container_image": "`+arvadostest.DockerImage112PDH+`",
1066 "mounts": {"/tmp": {"kind": "tmp"} },
1067 "output_path": "/tmp",
1069 "runtime_constraints": {"ram": `+fmt.Sprintf("%d", ram)+`},
1071 }`, nil, func() int { return 0 })
1072 logs := logFileContent(c, s.runner, "crunch-run.txt")
1073 c.Log("=== crunchstat logs")
1075 pattern := logLineStart + `Container using over %d%% of memory \(rss %d/%d bytes\)`
1077 for _, threshold = range expected {
1078 c.Check(logs, Matches, fmt.Sprintf(pattern, threshold, s.debian12MemoryCurrent, ram))
1080 if notExpected > threshold {
1081 c.Check(logs, Not(Matches), fmt.Sprintf(pattern, notExpected, s.debian12MemoryCurrent, ram))
1085 func (s *TestSuite) TestLogNoRSSThresholds(c *C) {
1086 s.testLogRSSThresholds(c, s.debian12MemoryCurrent*10, []int{}, 90)
1089 func (s *TestSuite) TestLogSomeRSSThresholds(c *C) {
1090 onePercentRSS := s.debian12MemoryCurrent / 100
1091 s.testLogRSSThresholds(c, 102*onePercentRSS, []int{90, 95}, 99)
1094 func (s *TestSuite) TestLogAllRSSThresholds(c *C) {
1095 s.testLogRSSThresholds(c, s.debian12MemoryCurrent, []int{90, 95, 99}, 0)
1098 func (s *TestSuite) TestLogMaximaAfterRun(c *C) {
1099 s.runner.crunchstatFakeFS = os.DirFS("../crunchstat/testdata/debian12")
1100 s.runner.parentTemp = c.MkDir()
1101 s.fullRunHelper(c, `{
1102 "command": ["true"],
1103 "container_image": "`+arvadostest.DockerImage112PDH+`",
1106 "mounts": {"/tmp": {"kind": "tmp"} },
1107 "output_path": "/tmp",
1109 "runtime_constraints": {"ram": `+fmt.Sprintf("%d", s.debian12MemoryCurrent*10)+`},
1111 }`, nil, func() int { return 0 })
1112 logs := logFileContent(c, s.runner, "crunch-run.txt")
1113 for _, expected := range []string{
1114 `Maximum disk usage was \d+%, \d+/\d+ bytes`,
1115 fmt.Sprintf(`Maximum container memory swap usage was %d bytes`, s.debian12SwapCurrent),
1116 `Maximum container memory pgmajfault usage was \d+ faults`,
1117 fmt.Sprintf(`Maximum container memory rss usage was 10%%, %d/%d bytes`, s.debian12MemoryCurrent, s.debian12MemoryCurrent*10),
1118 `Maximum crunch-run memory rss usage was \d+ bytes`,
1120 c.Check(logs, Matches, logLineStart+expected)
1124 func (s *TestSuite) TestCommitNodeInfoBeforeStart(c *C) {
1125 var collection_create, container_update arvadosclient.Dict
1126 s.fullRunHelper(c, `{
1127 "command": ["true"],
1128 "container_image": "`+arvadostest.DockerImage112PDH+`",
1131 "mounts": {"/tmp": {"kind": "tmp"} },
1132 "output_path": "/tmp",
1134 "runtime_constraints": {},
1136 "uuid": "zzzzz-dz642-202301121543210"
1137 }`, nil, func() int {
1138 collection_create = s.api.CalledWith("ensure_unique_name", true)
1139 container_update = s.api.CalledWith("container.state", "Running")
1143 c.Assert(collection_create, NotNil)
1144 log_collection := collection_create["collection"].(arvadosclient.Dict)
1145 c.Check(log_collection["name"], Equals, "logs for zzzzz-dz642-202301121543210")
1146 manifest_text := log_collection["manifest_text"].(string)
1147 // We check that the file size is at least two digits as an easy way to
1148 // check the file isn't empty.
1149 c.Check(manifest_text, Matches, `\. .+ \d+:\d{2,}:node-info\.txt( .+)?\n`)
1150 c.Check(manifest_text, Matches, `\. .+ \d+:\d{2,}:node\.json( .+)?\n`)
1152 c.Assert(container_update, NotNil)
1153 // As of Arvados 2.5.0, the container update must specify its log in PDH
1154 // format for the API server to propagate it to container requests, which
1155 // is what we care about for this test.
1156 expect_pdh := fmt.Sprintf("%x+%d", md5.Sum([]byte(manifest_text)), len(manifest_text))
1157 c.Check(container_update["container"].(arvadosclient.Dict)["log"], Equals, expect_pdh)
1160 func (s *TestSuite) TestContainerRecordLog(c *C) {
1161 s.fullRunHelper(c, `{
1162 "command": ["sleep", "1"],
1163 "container_image": "`+arvadostest.DockerImage112PDH+`",
1166 "mounts": {"/tmp": {"kind": "tmp"} },
1167 "output_path": "/tmp",
1169 "runtime_constraints": {},
1173 time.Sleep(time.Second)
1177 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1178 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1180 c.Check(logFileContent(c, s.runner, "container.json"), Matches, `(?ms).*container_image.*`)
1183 func (s *TestSuite) TestFullRunStderr(c *C) {
1184 s.fullRunHelper(c, `{
1185 "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
1186 "container_image": "`+arvadostest.DockerImage112PDH+`",
1189 "mounts": {"/tmp": {"kind": "tmp"} },
1190 "output_path": "/tmp",
1192 "runtime_constraints": {},
1194 }`, nil, func() int {
1195 fmt.Fprintln(s.executor.created.Stdout, "hello")
1196 fmt.Fprintln(s.executor.created.Stderr, "world")
1200 final := s.api.CalledWith("container.state", "Complete")
1201 c.Assert(final, NotNil)
1202 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1203 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1205 c.Check(logFileContent(c, s.runner, "stdout.txt"), Matches, ".*hello\n")
1206 c.Check(logFileContent(c, s.runner, "stderr.txt"), Matches, ".*world\n")
1209 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
1210 s.fullRunHelper(c, `{
1212 "container_image": "`+arvadostest.DockerImage112PDH+`",
1215 "mounts": {"/tmp": {"kind": "tmp"} },
1216 "output_path": "/tmp",
1218 "runtime_constraints": {},
1220 }`, nil, func() int {
1221 fmt.Fprintf(s.executor.created.Stdout, "workdir=%q", s.executor.created.WorkingDir)
1225 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1226 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1227 c.Check(logFileContent(c, s.runner, "stdout.txt"), Matches, `.*workdir=""`)
1230 func (s *TestSuite) TestFullRunSetCwd(c *C) {
1231 s.fullRunHelper(c, `{
1233 "container_image": "`+arvadostest.DockerImage112PDH+`",
1236 "mounts": {"/tmp": {"kind": "tmp"} },
1237 "output_path": "/tmp",
1239 "runtime_constraints": {},
1241 }`, nil, func() int {
1242 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.WorkingDir)
1246 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1247 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1248 c.Check(logFileContent(c, s.runner, "stdout.txt"), Matches, ".*/bin\n")
1251 func (s *TestSuite) TestFullRunSetOutputStorageClasses(c *C) {
1252 s.fullRunHelper(c, `{
1254 "container_image": "`+arvadostest.DockerImage112PDH+`",
1257 "mounts": {"/tmp": {"kind": "tmp"} },
1258 "output_path": "/tmp",
1260 "runtime_constraints": {},
1262 "output_storage_classes": ["foo", "bar"]
1263 }`, nil, func() int {
1264 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.WorkingDir)
1268 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1269 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1270 c.Check(logFileContent(c, s.runner, "stdout.txt"), Matches, ".*/bin\n")
1271 c.Check(s.testDispatcherKeepClient.StorageClasses, DeepEquals, []string{"foo", "bar"})
1272 c.Check(s.testContainerKeepClient.StorageClasses, DeepEquals, []string{"foo", "bar"})
1275 func (s *TestSuite) TestEnableCUDADeviceCount(c *C) {
1276 s.fullRunHelper(c, `{
1278 "container_image": "`+arvadostest.DockerImage112PDH+`",
1281 "mounts": {"/tmp": {"kind": "tmp"} },
1282 "output_path": "/tmp",
1284 "runtime_constraints": {"cuda": {"device_count": 2}},
1286 "output_storage_classes": ["foo", "bar"]
1287 }`, nil, func() int {
1288 fmt.Fprintln(s.executor.created.Stdout, "ok")
1291 c.Check(s.executor.created.CUDADeviceCount, Equals, 2)
1294 func (s *TestSuite) TestEnableCUDAHardwareCapability(c *C) {
1295 s.fullRunHelper(c, `{
1297 "container_image": "`+arvadostest.DockerImage112PDH+`",
1300 "mounts": {"/tmp": {"kind": "tmp"} },
1301 "output_path": "/tmp",
1303 "runtime_constraints": {"cuda": {"hardware_capability": "foo"}},
1305 "output_storage_classes": ["foo", "bar"]
1306 }`, nil, func() int {
1307 fmt.Fprintln(s.executor.created.Stdout, "ok")
1310 c.Check(s.executor.created.CUDADeviceCount, Equals, 0)
1313 func (s *TestSuite) TestStopOnSignal(c *C) {
1314 s.executor.runFunc = func() int {
1315 s.executor.created.Stdout.Write([]byte("foo\n"))
1316 s.runner.SigChan <- syscall.SIGINT
1317 time.Sleep(10 * time.Second)
1320 s.testStopContainer(c)
1323 func (s *TestSuite) TestStopOnArvMountDeath(c *C) {
1324 s.executor.runFunc = func() int {
1325 s.executor.created.Stdout.Write([]byte("foo\n"))
1326 s.runner.ArvMountExit <- nil
1327 close(s.runner.ArvMountExit)
1328 time.Sleep(10 * time.Second)
1331 s.runner.ArvMountExit = make(chan error)
1332 s.testStopContainer(c)
1335 func (s *TestSuite) testStopContainer(c *C) {
1337 "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
1338 "container_image": "` + arvadostest.DockerImage112PDH + `",
1341 "mounts": {"/tmp": {"kind": "tmp"} },
1342 "output_path": "/tmp",
1344 "runtime_constraints": {},
1348 err := json.Unmarshal([]byte(record), &s.api.Container)
1349 c.Assert(err, IsNil)
1351 s.runner.RunArvMount = func([]string, string) (*exec.Cmd, error) { return nil, nil }
1352 s.runner.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1353 return &ArvTestClient{}, &KeepTestClient{}, nil, nil
1356 done := make(chan error)
1358 done <- s.runner.Run()
1361 case <-time.After(20 * time.Second):
1362 pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
1363 c.Fatal("timed out")
1367 dumpAllLogFiles(c, s.runner)
1369 c.Check(s.api.CalledWith("container.log", nil), NotNil)
1370 c.Check(s.api.CalledWith("container.state", "Cancelled"), NotNil)
1371 c.Check(logFileContent(c, s.runner, "stdout.txt"), Matches, "(?ms).*foo\n$")
1374 func (s *TestSuite) TestFullRunSetEnv(c *C) {
1375 s.fullRunHelper(c, `{
1376 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1377 "container_image": "`+arvadostest.DockerImage112PDH+`",
1379 "environment": {"FROBIZ": "bilbo"},
1380 "mounts": {"/tmp": {"kind": "tmp"} },
1381 "output_path": "/tmp",
1383 "runtime_constraints": {},
1385 }`, nil, func() int {
1386 fmt.Fprintf(s.executor.created.Stdout, "%v", s.executor.created.Env)
1390 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1391 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1392 c.Check(logFileContent(c, s.runner, "stdout.txt"), Matches, `.*map\[FROBIZ:bilbo\]`)
1395 type ArvMountCmdLine struct {
1400 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
1406 func stubCert(c *C, temp string) string {
1407 path := temp + "/ca-certificates.crt"
1408 err := os.WriteFile(path, []byte{}, 0666)
1409 c.Assert(err, IsNil)
1410 os.Setenv("SSL_CERT_FILE", path)
1414 func (s *TestSuite) TestSetupMounts(c *C) {
1416 am := &ArvMountCmdLine{}
1417 cr.RunArvMount = am.ArvMountTest
1418 cr.containerClient, _ = apiStub()
1419 cr.ContainerArvClient = &ArvTestClient{}
1420 cr.ContainerKeepClient = &KeepTestClient{}
1421 cr.Container.OutputStorageClasses = []string{"default"}
1423 realTemp := c.MkDir()
1424 certTemp := c.MkDir()
1425 stubCertPath := stubCert(c, certTemp)
1426 cr.parentTemp = realTemp
1429 cr.MkTempDir = func(_ string, prefix string) (string, error) {
1431 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
1432 err := os.Mkdir(d, os.ModePerm)
1433 if err != nil && strings.Contains(err.Error(), ": file exists") {
1434 // Test case must have pre-populated the tempdir
1440 checkEmpty := func() {
1441 // Should be deleted.
1442 _, err := os.Stat(realTemp)
1443 c.Assert(os.IsNotExist(err), Equals, true)
1445 // Now recreate it for the next test.
1446 c.Assert(os.Mkdir(realTemp, 0777), IsNil)
1451 cr.ArvMountPoint = ""
1452 cr.Container.Mounts = make(map[string]arvados.Mount)
1453 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1454 cr.Container.OutputPath = "/tmp"
1455 cr.statInterval = 5 * time.Second
1456 bindmounts, err := cr.SetupMounts()
1458 c.Check(am.Cmd, DeepEquals, []string{"arv-mount", "--foreground",
1459 "--read-write", "--storage-classes", "default", "--crunchstat-interval=5",
1460 "--mount-by-pdh", "by_id", "--disable-event-listening", "--mount-by-id", "by_uuid", realTemp + "/keep1"})
1461 c.Check(bindmounts, DeepEquals, map[string]bindmount{"/tmp": {realTemp + "/tmp2", false}})
1462 os.RemoveAll(cr.ArvMountPoint)
1469 cr.ArvMountPoint = ""
1470 cr.Container.Mounts = make(map[string]arvados.Mount)
1471 cr.Container.Mounts["/out"] = arvados.Mount{Kind: "tmp"}
1472 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1473 cr.Container.OutputPath = "/out"
1474 cr.Container.OutputStorageClasses = []string{"foo", "bar"}
1476 bindmounts, err := cr.SetupMounts()
1478 c.Check(am.Cmd, DeepEquals, []string{"arv-mount", "--foreground",
1479 "--read-write", "--storage-classes", "foo,bar", "--crunchstat-interval=5",
1480 "--mount-by-pdh", "by_id", "--disable-event-listening", "--mount-by-id", "by_uuid", realTemp + "/keep1"})
1481 c.Check(bindmounts, DeepEquals, map[string]bindmount{"/out": {realTemp + "/tmp2", false}, "/tmp": {realTemp + "/tmp3", false}})
1482 os.RemoveAll(cr.ArvMountPoint)
1489 cr.ArvMountPoint = ""
1490 cr.Container.Mounts = make(map[string]arvados.Mount)
1491 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1492 cr.Container.OutputPath = "/tmp"
1493 cr.Container.RuntimeConstraints.API = true
1494 cr.Container.OutputStorageClasses = []string{"default"}
1496 bindmounts, err := cr.SetupMounts()
1498 c.Check(am.Cmd, DeepEquals, []string{"arv-mount", "--foreground",
1499 "--read-write", "--storage-classes", "default", "--crunchstat-interval=5",
1500 "--mount-by-pdh", "by_id", "--disable-event-listening", "--mount-by-id", "by_uuid", realTemp + "/keep1"})
1501 c.Check(bindmounts, DeepEquals, map[string]bindmount{"/tmp": {realTemp + "/tmp2", false}, "/etc/arvados/ca-certificates.crt": {stubCertPath, true}})
1502 os.RemoveAll(cr.ArvMountPoint)
1506 cr.Container.RuntimeConstraints.API = false
1511 cr.ArvMountPoint = ""
1512 cr.Container.Mounts = map[string]arvados.Mount{
1513 "/keeptmp": {Kind: "collection", Writable: true},
1515 cr.Container.OutputPath = "/keeptmp"
1517 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1519 bindmounts, err := cr.SetupMounts()
1521 c.Check(am.Cmd, DeepEquals, []string{"arv-mount", "--foreground",
1522 "--read-write", "--storage-classes", "default", "--crunchstat-interval=5",
1523 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", "--disable-event-listening", "--mount-by-id", "by_uuid", realTemp + "/keep1"})
1524 c.Check(bindmounts, DeepEquals, map[string]bindmount{"/keeptmp": {realTemp + "/keep1/tmp0", false}})
1525 os.RemoveAll(cr.ArvMountPoint)
1532 cr.ArvMountPoint = ""
1533 cr.Container.Mounts = map[string]arvados.Mount{
1534 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1535 "/keepout": {Kind: "collection", Writable: true},
1537 cr.Container.OutputPath = "/keepout"
1539 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1540 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1542 bindmounts, err := cr.SetupMounts()
1544 c.Check(am.Cmd, DeepEquals, []string{"arv-mount", "--foreground",
1545 "--read-write", "--storage-classes", "default", "--crunchstat-interval=5",
1546 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", "--disable-event-listening", "--mount-by-id", "by_uuid", realTemp + "/keep1"})
1547 c.Check(bindmounts, DeepEquals, map[string]bindmount{
1548 "/keepinp": {realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", true},
1549 "/keepout": {realTemp + "/keep1/tmp0", false},
1551 os.RemoveAll(cr.ArvMountPoint)
1558 cr.ArvMountPoint = ""
1559 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
1560 cr.Container.Mounts = map[string]arvados.Mount{
1561 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1562 "/keepout": {Kind: "collection", Writable: true},
1564 cr.Container.OutputPath = "/keepout"
1566 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1567 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1569 bindmounts, err := cr.SetupMounts()
1571 c.Check(am.Cmd, DeepEquals, []string{"arv-mount", "--foreground",
1572 "--read-write", "--storage-classes", "default", "--crunchstat-interval=5", "--ram-cache",
1573 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", "--disable-event-listening", "--mount-by-id", "by_uuid", realTemp + "/keep1"})
1574 c.Check(bindmounts, DeepEquals, map[string]bindmount{
1575 "/keepinp": {realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", true},
1576 "/keepout": {realTemp + "/keep1/tmp0", false},
1578 os.RemoveAll(cr.ArvMountPoint)
1583 for _, test := range []struct {
1587 {in: "foo", out: `"foo"`},
1588 {in: nil, out: `null`},
1589 {in: map[string]int64{"foo": 123456789123456789}, out: `{"foo":123456789123456789}`},
1592 cr.ArvMountPoint = ""
1593 cr.Container.Mounts = map[string]arvados.Mount{
1594 "/mnt/test.json": {Kind: "json", Content: test.in},
1596 bindmounts, err := cr.SetupMounts()
1598 c.Check(bindmounts, DeepEquals, map[string]bindmount{
1599 "/mnt/test.json": {realTemp + "/json2/mountdata.json", true},
1601 content, err := ioutil.ReadFile(realTemp + "/json2/mountdata.json")
1603 c.Check(content, DeepEquals, []byte(test.out))
1604 os.RemoveAll(cr.ArvMountPoint)
1609 for _, test := range []struct {
1613 {in: "foo", out: `foo`},
1614 {in: nil, out: "error"},
1615 {in: map[string]int64{"foo": 123456789123456789}, out: "error"},
1618 cr.ArvMountPoint = ""
1619 cr.Container.Mounts = map[string]arvados.Mount{
1620 "/mnt/test.txt": {Kind: "text", Content: test.in},
1622 bindmounts, err := cr.SetupMounts()
1623 if test.out == "error" {
1624 c.Check(err.Error(), Equals, "content for mount \"/mnt/test.txt\" must be a string")
1627 c.Check(bindmounts, DeepEquals, map[string]bindmount{
1628 "/mnt/test.txt": {realTemp + "/text2/mountdata.text", true},
1630 content, err := ioutil.ReadFile(realTemp + "/text2/mountdata.text")
1632 c.Check(content, DeepEquals, []byte(test.out))
1634 os.RemoveAll(cr.ArvMountPoint)
1639 // Read-only mount points are allowed underneath output_dir mount point
1642 cr.ArvMountPoint = ""
1643 cr.Container.Mounts = make(map[string]arvados.Mount)
1644 cr.Container.Mounts = map[string]arvados.Mount{
1645 "/tmp": {Kind: "tmp"},
1646 "/tmp/foo": {Kind: "collection"},
1648 cr.Container.OutputPath = "/tmp"
1650 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1652 bindmounts, err := cr.SetupMounts()
1654 c.Check(am.Cmd, DeepEquals, []string{"arv-mount", "--foreground",
1655 "--read-write", "--storage-classes", "default", "--crunchstat-interval=5", "--ram-cache",
1656 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", "--disable-event-listening", "--mount-by-id", "by_uuid", realTemp + "/keep1"})
1657 c.Check(bindmounts, DeepEquals, map[string]bindmount{
1658 "/tmp": {realTemp + "/tmp2", false},
1659 "/tmp/foo": {realTemp + "/keep1/tmp0", true},
1661 os.RemoveAll(cr.ArvMountPoint)
1666 // Writable mount points copied to output_dir mount point
1669 cr.ArvMountPoint = ""
1670 cr.Container.Mounts = make(map[string]arvados.Mount)
1671 cr.Container.Mounts = map[string]arvados.Mount{
1672 "/tmp": {Kind: "tmp"},
1673 "/tmp/foo": {Kind: "collection",
1674 PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53",
1676 "/tmp/bar": {Kind: "collection",
1677 PortableDataHash: "59389a8f9ee9d399be35462a0f92541d+53",
1681 cr.Container.OutputPath = "/tmp"
1683 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1684 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz", os.ModePerm)
1686 rf, _ := os.Create(realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz/quux")
1687 rf.Write([]byte("bar"))
1690 _, err := cr.SetupMounts()
1692 _, err = os.Stat(cr.HostOutputDir + "/foo")
1694 _, err = os.Stat(cr.HostOutputDir + "/bar/quux")
1696 os.RemoveAll(cr.ArvMountPoint)
1701 // Only mount points of kind 'collection' are allowed underneath output_dir mount point
1704 cr.ArvMountPoint = ""
1705 cr.Container.Mounts = make(map[string]arvados.Mount)
1706 cr.Container.Mounts = map[string]arvados.Mount{
1707 "/tmp": {Kind: "tmp"},
1708 "/tmp/foo": {Kind: "tmp"},
1710 cr.Container.OutputPath = "/tmp"
1712 _, err := cr.SetupMounts()
1713 c.Check(err, NotNil)
1714 c.Check(err, ErrorMatches, `only mount points of kind 'collection', 'text' or 'json' are supported underneath the output_path.*`)
1715 os.RemoveAll(cr.ArvMountPoint)
1720 // Only mount point of kind 'collection' is allowed for stdin
1723 cr.ArvMountPoint = ""
1724 cr.Container.Mounts = make(map[string]arvados.Mount)
1725 cr.Container.Mounts = map[string]arvados.Mount{
1726 "stdin": {Kind: "tmp"},
1729 _, err := cr.SetupMounts()
1730 c.Check(err, NotNil)
1731 c.Check(err, ErrorMatches, `unsupported mount kind 'tmp' for stdin.*`)
1732 os.RemoveAll(cr.ArvMountPoint)
1738 func (s *TestSuite) TestStdout(c *C) {
1740 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1741 "container_image": "` + arvadostest.DockerImage112PDH + `",
1743 "environment": {"FROBIZ": "bilbo"},
1744 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1745 "output_path": "/tmp",
1747 "runtime_constraints": {},
1751 s.fullRunHelper(c, helperRecord, nil, func() int {
1752 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.Env["FROBIZ"])
1756 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1757 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1758 c.Check(s.runner.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1761 // Used by the TestStdoutWithWrongPath*()
1762 func (s *TestSuite) stdoutErrorRunHelper(c *C, record string, fn func() int) (*ArvTestClient, *ContainerRunner, error) {
1763 err := json.Unmarshal([]byte(record), &s.api.Container)
1764 c.Assert(err, IsNil)
1765 s.executor.runFunc = fn
1766 s.runner.RunArvMount = (&ArvMountCmdLine{}).ArvMountTest
1767 s.runner.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1768 return s.api, &KeepTestClient{}, nil, nil
1770 return s.api, s.runner, s.runner.Run()
1773 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1774 _, _, err := s.stdoutErrorRunHelper(c, `{
1775 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1776 "output_path": "/tmp",
1778 }`, func() int { return 0 })
1779 c.Check(err, ErrorMatches, ".*Stdout path does not start with OutputPath.*")
1782 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1783 _, _, err := s.stdoutErrorRunHelper(c, `{
1784 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1785 "output_path": "/tmp",
1787 }`, func() int { return 0 })
1788 c.Check(err, ErrorMatches, ".*unsupported mount kind 'tmp' for stdout.*")
1791 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1792 _, _, err := s.stdoutErrorRunHelper(c, `{
1793 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1794 "output_path": "/tmp",
1796 }`, func() int { return 0 })
1797 c.Check(err, ErrorMatches, ".*unsupported mount kind 'collection' for stdout.*")
1800 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1801 s.fullRunHelper(c, `{
1802 "command": ["/bin/sh", "-c", "true $ARVADOS_API_HOST"],
1803 "container_image": "`+arvadostest.DockerImage112PDH+`",
1806 "mounts": {"/tmp": {"kind": "tmp"} },
1807 "output_path": "/tmp",
1809 "runtime_constraints": {"API": true},
1811 }`, nil, func() int {
1812 c.Check(s.executor.created.Env["ARVADOS_API_HOST"], Equals, os.Getenv("ARVADOS_API_HOST"))
1815 c.Check(s.api.CalledWith("container.exit_code", 3), NotNil)
1816 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1817 c.Check(logFileContent(c, s.runner, "crunch-run.txt"), Matches, `(?ms).*status code 3\n.*`)
1820 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1821 defer os.Setenv("ARVADOS_API_HOST", os.Getenv("ARVADOS_API_HOST"))
1822 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1823 s.fullRunHelper(c, `{
1824 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1825 "container_image": "`+arvadostest.DockerImage112PDH+`",
1828 "mounts": {"/tmp": {"kind": "tmp"} },
1829 "output_path": "/tmp",
1831 "runtime_constraints": {"API": true},
1833 }`, nil, func() int {
1834 s.api.Container.Output = arvadostest.DockerImage112PDH
1838 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1839 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1840 c.Check(s.api.CalledWith("container.output", arvadostest.DockerImage112PDH), NotNil)
1843 func (s *TestSuite) TestArvMountRuntimeStatusWarning(c *C) {
1844 s.runner.RunArvMount = func([]string, string) (*exec.Cmd, error) {
1845 os.Mkdir(s.runner.ArvMountPoint+"/by_id", 0666)
1846 ioutil.WriteFile(s.runner.ArvMountPoint+"/by_id/README", nil, 0666)
1847 return s.runner.ArvMountCmd([]string{"bash", "-c", "echo >&2 Test: Keep write error: I am a teapot; sleep 3"}, "")
1849 s.executor.runFunc = func() int {
1850 time.Sleep(time.Second)
1854 "command": ["sleep", "1"],
1855 "container_image": "` + arvadostest.DockerImage112PDH + `",
1858 "mounts": {"/tmp": {"kind": "tmp"} },
1859 "output_path": "/tmp",
1861 "runtime_constraints": {"API": true},
1864 err := json.Unmarshal([]byte(record), &s.api.Container)
1865 c.Assert(err, IsNil)
1866 err = s.runner.Run()
1867 c.Assert(err, IsNil)
1868 c.Check(s.api.CalledWith("container.exit_code", 137), NotNil)
1869 c.Check(s.api.CalledWith("container.runtime_status.warning", "arv-mount: Keep write error"), NotNil)
1870 c.Check(s.api.CalledWith("container.runtime_status.warningDetail", "Test: Keep write error: I am a teapot"), NotNil)
1871 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1872 c.Check(logFileContent(c, s.runner, "crunch-run.txt"), Matches, `(?ms).*Container exited with status code 137 \(signal 9, SIGKILL\).*`)
1875 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1877 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1878 "container_image": "` + arvadostest.DockerImage112PDH + `",
1880 "environment": {"FROBIZ": "bilbo"},
1882 "/tmp": {"kind": "tmp"},
1883 "/tmp/foo": {"kind": "collection",
1884 "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1885 "exclude_from_output": true
1887 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1889 "output_path": "/tmp",
1891 "runtime_constraints": {},
1895 extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1897 s.fullRunHelper(c, helperRecord, extraMounts, func() int {
1898 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.Env["FROBIZ"])
1902 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1903 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1904 c.Check(s.runner.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1907 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1909 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1910 "container_image": "` + arvadostest.DockerImage112PDH + `",
1912 "environment": {"FROBIZ": "bilbo"},
1914 "/tmp": {"kind": "tmp"},
1915 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1916 "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1917 "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1918 "/tmp/foo/baz/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1919 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1921 "output_path": "/tmp",
1923 "runtime_constraints": {},
1925 "uuid": "zzzzz-dz642-202301130848001"
1928 extraMounts := []string{
1929 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1930 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1931 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1934 api, _, realtemp := s.fullRunHelper(c, helperRecord, extraMounts, func() int {
1935 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.Env["FROBIZ"])
1939 c.Check(s.executor.created.BindMounts, DeepEquals, map[string]bindmount{
1940 "/tmp": {realtemp + "/tmp1", false},
1941 "/tmp/foo/bar": {s.keepmount + "/by_id/a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt", true},
1942 "/tmp/foo/baz/sub2file2": {s.keepmount + "/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt", true},
1943 "/tmp/foo/sub1": {s.keepmount + "/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1", true},
1944 "/tmp/foo/sub1file2": {s.keepmount + "/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt", true},
1947 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1948 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1949 output_count := uint(0)
1950 for _, v := range s.runner.ContainerArvClient.(*ArvTestClient).Content {
1951 if v["collection"] == nil {
1954 collection := v["collection"].(arvadosclient.Dict)
1955 if collection["name"].(string) != "output for zzzzz-dz642-202301130848001" {
1958 c.Check(v["ensure_unique_name"], Equals, true)
1959 c.Check(collection["manifest_text"].(string), Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1960 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:bar 36:18:sub1file2
1961 ./foo/baz 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2
1962 ./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1963 ./foo/sub1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1967 c.Check(output_count, Not(Equals), uint(0))
1970 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
1972 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1973 "container_image": "` + arvadostest.DockerImage112PDH + `",
1975 "environment": {"FROBIZ": "bilbo"},
1977 "/tmp": {"kind": "tmp"},
1978 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/subdir1/file2_in_subdir1.txt"},
1979 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1981 "output_path": "/tmp",
1983 "runtime_constraints": {},
1985 "uuid": "zzzzz-dz642-202301130848002"
1988 extraMounts := []string{
1989 "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1992 s.fullRunHelper(c, helperRecord, extraMounts, func() int {
1993 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.Env["FROBIZ"])
1997 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1998 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1999 output_count := uint(0)
2000 for _, v := range s.runner.ContainerArvClient.(*ArvTestClient).Content {
2001 if v["collection"] == nil {
2004 collection := v["collection"].(arvadosclient.Dict)
2005 if collection["name"].(string) != "output for zzzzz-dz642-202301130848002" {
2008 c.Check(collection["manifest_text"].(string), Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
2009 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 10:17:bar
2013 c.Check(output_count, Not(Equals), uint(0))
2016 func (s *TestSuite) TestOutputError(c *C) {
2018 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
2019 "container_image": "` + arvadostest.DockerImage112PDH + `",
2021 "environment": {"FROBIZ": "bilbo"},
2023 "/tmp": {"kind": "tmp"}
2025 "output_path": "/tmp",
2027 "runtime_constraints": {},
2030 s.fullRunHelper(c, helperRecord, nil, func() int {
2031 os.Symlink("/etc/hosts", s.runner.HostOutputDir+"/baz")
2035 c.Check(s.api.CalledWith("container.state", "Cancelled"), NotNil)
2038 func (s *TestSuite) TestStdinCollectionMountPoint(c *C) {
2040 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
2041 "container_image": "` + arvadostest.DockerImage112PDH + `",
2043 "environment": {"FROBIZ": "bilbo"},
2045 "/tmp": {"kind": "tmp"},
2046 "stdin": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/file1_in_main.txt"},
2047 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
2049 "output_path": "/tmp",
2051 "runtime_constraints": {},
2055 extraMounts := []string{
2056 "b0def87f80dd594d4675809e83bd4f15+367/file1_in_main.txt",
2059 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, func() int {
2060 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.Env["FROBIZ"])
2064 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2065 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2066 for _, v := range api.Content {
2067 if v["collection"] != nil {
2068 collection := v["collection"].(arvadosclient.Dict)
2069 if strings.Index(collection["name"].(string), "output") == 0 {
2070 manifest := collection["manifest_text"].(string)
2071 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
2078 func (s *TestSuite) TestStdinJsonMountPoint(c *C) {
2080 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
2081 "container_image": "` + arvadostest.DockerImage112PDH + `",
2083 "environment": {"FROBIZ": "bilbo"},
2085 "/tmp": {"kind": "tmp"},
2086 "stdin": {"kind": "json", "content": "foo"},
2087 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
2089 "output_path": "/tmp",
2091 "runtime_constraints": {},
2095 api, _, _ := s.fullRunHelper(c, helperRecord, nil, func() int {
2096 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.Env["FROBIZ"])
2100 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2101 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2102 for _, v := range api.Content {
2103 if v["collection"] != nil {
2104 collection := v["collection"].(arvadosclient.Dict)
2105 if strings.Index(collection["name"].(string), "output") == 0 {
2106 manifest := collection["manifest_text"].(string)
2107 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
2114 func (s *TestSuite) TestStderrMount(c *C) {
2115 api, cr, _ := s.fullRunHelper(c, `{
2116 "command": ["/bin/sh", "-c", "echo hello;exit 1"],
2117 "container_image": "`+arvadostest.DockerImage112PDH+`",
2120 "mounts": {"/tmp": {"kind": "tmp"},
2121 "stdout": {"kind": "file", "path": "/tmp/a/out.txt"},
2122 "stderr": {"kind": "file", "path": "/tmp/b/err.txt"}},
2123 "output_path": "/tmp",
2125 "runtime_constraints": {},
2127 }`, nil, func() int {
2128 fmt.Fprintln(s.executor.created.Stdout, "hello")
2129 fmt.Fprintln(s.executor.created.Stderr, "oops")
2133 final := api.CalledWith("container.state", "Complete")
2134 c.Assert(final, NotNil)
2135 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
2136 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
2138 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)
2141 func (s *TestSuite) TestNumberRoundTrip(c *C) {
2142 s.api.callraw = true
2143 err := s.runner.fetchContainerRecord()
2144 c.Assert(err, IsNil)
2145 jsondata, err := json.Marshal(s.runner.Container.Mounts["/json"].Content)
2146 c.Logf("%#v", s.runner.Container)
2148 c.Check(string(jsondata), Equals, `{"number":123456789123456789}`)
2151 func (s *TestSuite) TestFullBrokenDocker(c *C) {
2153 for _, setup := range []func(){
2155 c.Log("// waitErr = ocl runtime error")
2156 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\\\"\""`)
2157 nextState = "Cancelled"
2160 c.Log("// loadErr = cannot connect")
2161 s.executor.loadErr = errors.New("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?")
2162 s.runner.brokenNodeHook = c.MkDir() + "/broken-node-hook"
2163 err := ioutil.WriteFile(s.runner.brokenNodeHook, []byte("#!/bin/sh\nexec echo killme\n"), 0700)
2164 c.Assert(err, IsNil)
2165 nextState = "Queued"
2170 s.fullRunHelper(c, `{
2171 "command": ["echo", "hello world"],
2172 "container_image": "`+arvadostest.DockerImage112PDH+`",
2175 "mounts": {"/tmp": {"kind": "tmp"} },
2176 "output_path": "/tmp",
2178 "runtime_constraints": {},
2180 }`, nil, func() int { return 0 })
2181 c.Check(s.api.CalledWith("container.state", nextState), NotNil)
2182 logs := logFileContent(c, s.runner, "crunch-run.txt")
2183 c.Check(logs, Matches, "(?ms).*unable to run containers.*")
2184 if s.runner.brokenNodeHook != "" {
2185 c.Check(logs, Matches, "(?ms).*Running broken node hook.*")
2186 c.Check(logs, Matches, "(?ms).*killme.*")
2187 c.Check(logs, Not(Matches), "(?ms).*Writing /var/lock/crunch-run-broken to mark node as broken.*")
2189 c.Check(logs, Matches, "(?ms).*Writing /var/lock/crunch-run-broken to mark node as broken.*")
2194 func (s *TestSuite) TestBadCommand(c *C) {
2195 for _, startError := range []string{
2196 `panic: standard_init_linux.go:175: exec user process caused "no such file or directory"`,
2197 `Error response from daemon: Cannot start container 41f26cbc43bcc1280f4323efb1830a394ba8660c9d1c2b564ba42bf7f7694845: [8] System error: no such file or directory`,
2198 `Error response from daemon: Cannot start container 58099cd76c834f3dc2a4fb76c8028f049ae6d4fdf0ec373e1f2cfea030670c2d: [8] System error: exec: "foobar": executable file not found in $PATH`,
2201 s.executor.startErr = errors.New(startError)
2202 s.fullRunHelper(c, `{
2203 "command": ["echo", "hello world"],
2204 "container_image": "`+arvadostest.DockerImage112PDH+`",
2207 "mounts": {"/tmp": {"kind": "tmp"} },
2208 "output_path": "/tmp",
2210 "runtime_constraints": {},
2212 }`, nil, func() int { return 0 })
2213 c.Check(s.api.CalledWith("container.state", "Cancelled"), NotNil)
2214 c.Check(logFileContent(c, s.runner, "crunch-run.txt"), Matches, "(?ms).*Possible causes:.*is missing.*")
2218 func (s *TestSuite) TestSecretTextMountPoint(c *C) {
2220 "command": ["true"],
2221 "container_image": "` + arvadostest.DockerImage112PDH + `",
2224 "/tmp": {"kind": "tmp"},
2225 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2229 "output_path": "/tmp",
2231 "runtime_constraints": {},
2235 s.fullRunHelper(c, helperRecord, nil, func() int {
2236 content, err := ioutil.ReadFile(s.runner.HostOutputDir + "/secret.conf")
2238 c.Check(string(content), Equals, "mypassword")
2242 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
2243 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
2244 c.Check(s.runner.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), NotNil)
2245 c.Check(s.runner.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ""), IsNil)
2247 // under secret mounts, not captured in output
2249 "command": ["true"],
2250 "container_image": "` + arvadostest.DockerImage112PDH + `",
2253 "/tmp": {"kind": "tmp"}
2256 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2258 "output_path": "/tmp",
2260 "runtime_constraints": {},
2265 s.fullRunHelper(c, helperRecord, nil, func() int {
2266 content, err := ioutil.ReadFile(s.runner.HostOutputDir + "/secret.conf")
2268 c.Check(string(content), Equals, "mypassword")
2272 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
2273 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
2274 c.Check(s.runner.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), IsNil)
2275 c.Check(s.runner.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ""), NotNil)
2277 // under secret mounts, output dir is a collection, not captured in output
2279 "command": ["true"],
2280 "container_image": "` + arvadostest.DockerImage112PDH + `",
2283 "/tmp": {"kind": "collection", "writable": true}
2286 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2288 "output_path": "/tmp",
2290 "runtime_constraints": {},
2295 _, _, realtemp := s.fullRunHelper(c, helperRecord, nil, func() int {
2296 // secret.conf should be provisioned as a separate
2297 // bind mount, i.e., it should not appear in the
2298 // (fake) fuse filesystem as viewed from the host.
2299 content, err := ioutil.ReadFile(s.runner.HostOutputDir + "/secret.conf")
2300 if !c.Check(errors.Is(err, os.ErrNotExist), Equals, true) {
2301 c.Logf("secret.conf: content %q, err %#v", content, err)
2303 err = ioutil.WriteFile(s.runner.HostOutputDir+"/.arvados#collection", []byte(`{"manifest_text":". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo.txt\n"}`), 0700)
2308 content, err := ioutil.ReadFile(realtemp + "/text1/mountdata.text")
2310 c.Check(string(content), Equals, "mypassword")
2311 c.Check(s.executor.created.BindMounts["/tmp/secret.conf"], DeepEquals, bindmount{realtemp + "/text1/mountdata.text", true})
2312 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
2313 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
2314 c.Check(s.runner.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo.txt\n"), NotNil)
2317 func (s *TestSuite) TestCalculateCost(c *C) {
2318 defer func(s string) { lockdir = s }(lockdir)
2322 cr.costStartTime = now.Add(-time.Hour)
2323 var logbuf bytes.Buffer
2324 cr.CrunchLog = newLogWriter(&logbuf)
2326 // if there's no InstanceType env var, cost is calculated as 0
2327 os.Unsetenv("InstanceType")
2328 cost := cr.calculateCost(now)
2329 c.Check(cost, Equals, 0.0)
2331 // with InstanceType env var and loadPrices() hasn't run (or
2332 // hasn't found any data), cost is calculated based on
2333 // InstanceType env var
2334 os.Setenv("InstanceType", `{"Price":1.2}`)
2335 cost = cr.calculateCost(now)
2336 c.Check(cost, Equals, 1.2)
2338 // first update tells us the spot price was $1/h until 30
2339 // minutes ago when it increased to $2/h
2340 j, err := json.Marshal([]cloud.InstancePrice{
2341 {StartTime: now.Add(-4 * time.Hour), Price: 1.0},
2342 {StartTime: now.Add(-time.Hour / 2), Price: 2.0},
2344 c.Assert(err, IsNil)
2345 os.WriteFile(lockdir+"/"+pricesfile, j, 0777)
2347 cost = cr.calculateCost(now)
2348 c.Check(cost, Equals, 1.5)
2350 // next update (via --list + SIGUSR2) tells us the spot price
2351 // increased to $3/h 15 minutes ago
2352 j, err = json.Marshal([]cloud.InstancePrice{
2353 {StartTime: now.Add(-time.Hour / 3), Price: 2.0}, // dup of -time.Hour/2 price
2354 {StartTime: now.Add(-time.Hour / 4), Price: 3.0},
2356 c.Assert(err, IsNil)
2357 os.WriteFile(lockdir+"/"+pricesfile, j, 0777)
2359 cost = cr.calculateCost(now)
2360 c.Check(cost, Equals, 1.0/2+2.0/4+3.0/4)
2362 cost = cr.calculateCost(now.Add(-time.Hour / 2))
2363 c.Check(cost, Equals, 0.5)
2365 c.Logf("%s", logbuf.String())
2366 c.Check(logbuf.String(), Matches, `(?ms).*Instance price changed to 1\.00 at 20.* changed to 2\.00 .* changed to 3\.00 .*`)
2367 c.Check(logbuf.String(), Not(Matches), `(?ms).*changed to 2\.00 .* changed to 2\.00 .*`)
2370 func (s *TestSuite) TestSIGUSR2CostUpdate(c *C) {
2373 pricesJSON, err := json.Marshal([]cloud.InstancePrice{
2374 {StartTime: now.Add(-4 * time.Hour), Price: 2.4},
2375 {StartTime: now.Add(-2 * time.Hour), Price: 2.6},
2377 c.Assert(err, IsNil)
2379 os.Setenv("InstanceType", `{"Price":2.2}`)
2380 defer func(s string) { lockdir = s }(lockdir)
2383 // We can't use s.api.CalledWith because timing differences will yield
2384 // different cost values across runs. getCostUpdate iterates over API
2385 // calls until it finds one that sets the cost, then writes that value
2386 // to the next index of costUpdates.
2387 deadline := now.Add(time.Second)
2388 costUpdates := make([]float64, 2)
2391 getCostUpdate := func() {
2392 for ; time.Now().Before(deadline); time.Sleep(time.Second / 10) {
2393 for apiIndex < len(s.api.Content) {
2394 update := s.api.Content[apiIndex]
2398 if update, ok = update["container"].(arvadosclient.Dict); !ok {
2401 if cost, ok = update["cost"].(float64); !ok {
2404 c.Logf("API call #%d updates cost to %v", apiIndex-1, cost)
2405 costUpdates[costIndex] = cost
2412 s.fullRunHelper(c, `{
2413 "command": ["true"],
2414 "container_image": "`+arvadostest.DockerImage112PDH+`",
2417 "mounts": {"/tmp": {"kind": "tmp"} },
2418 "output_path": "/tmp",
2420 "runtime_constraints": {},
2422 "uuid": "zzzzz-dz642-20230320101530a"
2423 }`, nil, func() int {
2424 s.runner.costStartTime = now.Add(-3 * time.Hour)
2425 err := syscall.Kill(pid, syscall.SIGUSR2)
2426 c.Check(err, IsNil, Commentf("error sending first SIGUSR2 to runner"))
2429 err = os.WriteFile(path.Join(lockdir, pricesfile), pricesJSON, 0o700)
2430 c.Check(err, IsNil, Commentf("error writing JSON prices file"))
2431 err = syscall.Kill(pid, syscall.SIGUSR2)
2432 c.Check(err, IsNil, Commentf("error sending second SIGUSR2 to runner"))
2437 // Comparing with format strings makes it easy to ignore minor variations
2438 // in cost across runs while keeping diagnostics pretty.
2439 c.Check(fmt.Sprintf("%.3f", costUpdates[0]), Equals, "6.600")
2440 c.Check(fmt.Sprintf("%.3f", costUpdates[1]), Equals, "7.600")
2443 type FakeProcess struct {
2447 func (fp FakeProcess) CmdlineSlice() ([]string, error) {
2448 return fp.cmdLine, nil
2451 func logFileContent(c *C, cr *ContainerRunner, fnm string) string {
2452 buf, err := fs.ReadFile(arvados.FS(cr.LogCollection), fnm)
2453 c.Assert(err, IsNil)
2457 func dumpAllLogFiles(c *C, cr *ContainerRunner) {
2458 d, err := cr.LogCollection.OpenFile("/", os.O_RDONLY, 0)
2459 c.Assert(err, IsNil)
2460 fis, err := d.Readdir(-1)
2461 c.Assert(err, IsNil)
2462 for _, fi := range fis {
2463 c.Logf("=== %s", fi.Name())
2464 c.Log(logFileContent(c, cr, fi.Name()))