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"
42 git_client "gopkg.in/src-d/go-git.v4/plumbing/transport/client"
43 git_http "gopkg.in/src-d/go-git.v4/plumbing/transport/http"
46 // Gocheck boilerplate
47 func TestCrunchExec(t *testing.T) {
51 const logLineStart = `(?m)(.*\n)*\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d+Z `
53 var _ = Suite(&TestSuite{})
55 type TestSuite struct {
56 client *arvados.Client
58 runner *ContainerRunner
59 executor *stubExecutor
62 testDispatcherKeepClient KeepTestClient
63 testContainerKeepClient KeepTestClient
64 debian12MemoryCurrent int64
65 debian12SwapCurrent int64
68 func (s *TestSuite) SetUpSuite(c *C) {
69 buf, err := os.ReadFile("../crunchstat/testdata/debian12/sys/fs/cgroup/user.slice/user-1000.slice/session-4.scope/memory.current")
71 _, err = fmt.Sscanf(string(buf), "%d", &s.debian12MemoryCurrent)
74 buf, err = os.ReadFile("../crunchstat/testdata/debian12/sys/fs/cgroup/user.slice/user-1000.slice/session-4.scope/memory.swap.current")
76 _, err = fmt.Sscanf(string(buf), "%d", &s.debian12SwapCurrent)
80 func (s *TestSuite) SetUpTest(c *C) {
81 s.client = arvados.NewClientFromEnv()
82 s.executor = &stubExecutor{}
84 s.api = &ArvTestClient{}
85 s.runner, err = NewContainerRunner(s.client, s.api, &s.testDispatcherKeepClient, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
87 s.runner.executor = s.executor
88 s.runner.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
89 return s.api, &s.testContainerKeepClient, s.client, nil
91 s.runner.RunArvMount = func(cmd []string, tok string) (*exec.Cmd, error) {
92 s.runner.ArvMountPoint = s.keepmount
93 for i, opt := range cmd {
94 if opt == "--mount-tmp" {
95 err := os.Mkdir(s.keepmount+"/"+cmd[i+1], 0700)
99 s.keepmountTmp = append(s.keepmountTmp, cmd[i+1])
104 s.keepmount = c.MkDir()
105 err = os.Mkdir(s.keepmount+"/by_id", 0755)
108 err = os.Mkdir(s.keepmount+"/by_id/"+arvadostest.DockerImage112PDH, 0755)
110 err = ioutil.WriteFile(s.keepmount+"/by_id/"+arvadostest.DockerImage112PDH+"/"+arvadostest.DockerImage112Filename, []byte("#notarealtarball"), 0644)
111 err = os.Mkdir(s.keepmount+"/by_id/"+fakeInputCollectionPDH, 0755)
113 err = ioutil.WriteFile(s.keepmount+"/by_id/"+fakeInputCollectionPDH+"/input.json", []byte(`{"input":true}`), 0644)
115 s.runner.ArvMountPoint = s.keepmount
118 type ArvTestClient struct {
121 Content []arvadosclient.Dict
124 Logs map[string]*bytes.Buffer
130 type KeepTestClient struct {
133 StorageClasses []string
136 type stubExecutor struct {
142 created containerSpec
144 waitSleep time.Duration
153 func (e *stubExecutor) LoadImage(imageId string, tarball string, container arvados.Container, keepMount string,
154 containerClient *arvados.Client) error {
158 func (e *stubExecutor) Runtime() string { return "stub" }
159 func (e *stubExecutor) Version() string { return "stub " + cmd.Version.String() }
160 func (e *stubExecutor) Create(spec containerSpec) error { e.created = spec; return e.createErr }
161 func (e *stubExecutor) Start() error {
162 e.exit = make(chan int, 1)
163 go func() { e.exit <- e.runFunc() }()
166 func (e *stubExecutor) Pid() int { return 1115883 } // matches pid in ../crunchstat/testdata/debian12/proc/
167 func (e *stubExecutor) Stop() error { e.stopped = true; go func() { e.exit <- -1 }(); return e.stopErr }
168 func (e *stubExecutor) Close() { e.closed = true }
169 func (e *stubExecutor) Wait(context.Context) (int, error) {
170 return <-e.exit, e.waitErr
172 func (e *stubExecutor) InjectCommand(ctx context.Context, _, _ string, _ bool, _ []string) (*exec.Cmd, error) {
173 return nil, errors.New("unimplemented")
175 func (e *stubExecutor) IPAddress() (string, error) { return "", errors.New("unimplemented") }
177 const fakeInputCollectionPDH = "ffffffffaaaaaaaa88888888eeeeeeee+1234"
179 var hwManifest = ". 82ab40c24fc8df01798e57ba66795bb1+841216+Aa124ac75e5168396c73c0a18eda641a4f41791c0@569fa8c3 0:841216:9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7.tar\n"
180 var hwPDH = "a45557269dcb65a6b78f9ac061c0850b+120"
181 var hwImageID = "9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7"
183 var otherManifest = ". 68a84f561b1d1708c6baff5e019a9ab3+46+Ae5d0af96944a3690becb1decdf60cc1c937f556d@5693216f 0:46:md5sum.txt\n"
184 var otherPDH = "a3e8f74c6f101eae01fa08bfb4e49b3a+54"
186 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
187 ./subdir1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
188 ./subdir1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
191 var normalizedWithSubdirsPDH = "a0def87f80dd594d4675809e83bd4f15+367"
193 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"
194 var denormalizedWithSubdirsPDH = "b0def87f80dd594d4675809e83bd4f15+367"
196 var fakeAuthUUID = "zzzzz-gj3su-55pqoyepgi2glem"
197 var fakeAuthToken = "a3ltuwzqcu2u4sc0q7yhpc2w7s00fdcqecg5d6e0u3pfohmbjt"
199 func (client *ArvTestClient) Create(resourceType string,
200 parameters arvadosclient.Dict,
201 output interface{}) error {
204 defer client.Mutex.Unlock()
207 client.Content = append(client.Content, parameters)
209 if resourceType == "logs" {
210 et := parameters["log"].(arvadosclient.Dict)["event_type"].(string)
211 if client.Logs == nil {
212 client.Logs = make(map[string]*bytes.Buffer)
214 if client.Logs[et] == nil {
215 client.Logs[et] = &bytes.Buffer{}
217 client.Logs[et].Write([]byte(parameters["log"].(arvadosclient.Dict)["properties"].(map[string]string)["text"]))
220 if resourceType == "collections" && output != nil {
221 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
222 md5sum := md5.Sum([]byte(mt))
223 outmap := output.(*arvados.Collection)
224 outmap.PortableDataHash = fmt.Sprintf("%x+%d", md5sum, len(mt))
225 outmap.UUID = fmt.Sprintf("zzzzz-4zz18-%015x", md5sum[:7])
231 func (client *ArvTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
233 case method == "GET" && resourceType == "containers" && action == "auth":
234 return json.Unmarshal([]byte(`{
235 "kind": "arvados#api_client_authorization",
236 "uuid": "`+fakeAuthUUID+`",
237 "api_token": "`+fakeAuthToken+`"
239 case method == "GET" && resourceType == "containers" && action == "secret_mounts":
240 if client.secretMounts != nil {
241 return json.Unmarshal(client.secretMounts, output)
243 return json.Unmarshal([]byte(`{"secret_mounts":{}}`), output)
245 return fmt.Errorf("Not found")
249 func (client *ArvTestClient) CallRaw(method, resourceType, uuid, action string,
250 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
252 if method == "GET" && resourceType == "nodes" && uuid == "" && action == "" {
254 "kind": "arvados#nodeList",
256 "uuid": "zzzzz-7ekkf-2z3mc76g2q73aio",
257 "hostname": "compute2",
258 "properties": {"total_cpu_cores": 16}
260 } else if method == "GET" && resourceType == "containers" && action == "" && !client.callraw {
262 j, err = json.Marshal(map[string]interface{}{
263 "items": []interface{}{client.Container},
264 "kind": "arvados#nodeList",
267 j, err = json.Marshal(client.Container)
271 "command": ["sleep", "1"],
272 "container_image": "` + arvadostest.DockerImage112PDH + `",
275 "mounts": {"/tmp": {"kind": "tmp"}, "/json": {"kind": "json", "content": {"number": 123456789123456789}}},
276 "output_path": "/tmp",
278 "runtime_constraints": {}
281 return ioutil.NopCloser(bytes.NewReader(j)), err
284 func (client *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
285 if resourceType == "collections" {
287 output.(*arvados.Collection).ManifestText = hwManifest
288 } else if uuid == otherPDH {
289 output.(*arvados.Collection).ManifestText = otherManifest
290 } else if uuid == normalizedWithSubdirsPDH {
291 output.(*arvados.Collection).ManifestText = normalizedManifestWithSubdirs
292 } else if uuid == denormalizedWithSubdirsPDH {
293 output.(*arvados.Collection).ManifestText = denormalizedManifestWithSubdirs
296 if resourceType == "containers" {
297 (*output.(*arvados.Container)) = client.Container
302 func (client *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
304 defer client.Mutex.Unlock()
306 client.Content = append(client.Content, parameters)
307 if resourceType == "containers" {
308 if parameters["container"].(arvadosclient.Dict)["state"] == "Running" {
309 client.WasSetRunning = true
311 } else if resourceType == "collections" && output != nil {
312 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
313 output.(*arvados.Collection).UUID = uuid
314 output.(*arvados.Collection).PortableDataHash = fmt.Sprintf("%x", md5.Sum([]byte(mt)))
319 var discoveryMap = map[string]interface{}{
320 "defaultTrashLifetime": float64(1209600),
321 "crunchLimitLogBytesPerJob": float64(67108864),
322 "crunchLogThrottleBytes": float64(65536),
323 "crunchLogThrottlePeriod": float64(60),
324 "crunchLogThrottleLines": float64(1024),
325 "crunchLogPartialLineThrottlePeriod": float64(5),
326 "crunchLogBytesPerEvent": float64(4096),
327 "crunchLogSecondsBetweenEvents": float64(1),
330 func (client *ArvTestClient) Discovery(key string) (interface{}, error) {
331 return discoveryMap[key], nil
334 // CalledWith returns the parameters from the first API call whose
335 // parameters match jpath/string. E.g., CalledWith(c, "foo.bar",
336 // "baz") returns parameters with parameters["foo"]["bar"]=="baz". If
337 // no call matches, it returns nil.
338 func (client *ArvTestClient) CalledWith(jpath string, expect interface{}) arvadosclient.Dict {
340 for _, content := range client.Content {
341 var v interface{} = content
342 for _, k := range strings.Split(jpath, ".") {
343 if dict, ok := v.(arvadosclient.Dict); !ok {
356 func (client *KeepTestClient) LocalLocator(locator string) (string, error) {
360 func (client *KeepTestClient) BlockWrite(_ context.Context, opts arvados.BlockWriteOptions) (arvados.BlockWriteResponse, error) {
361 client.Content = opts.Data
362 return arvados.BlockWriteResponse{
363 Locator: fmt.Sprintf("%x+%d", md5.Sum(opts.Data), len(opts.Data)),
367 func (client *KeepTestClient) ReadAt(string, []byte, int) (int, error) {
368 return 0, errors.New("not implemented")
371 func (client *KeepTestClient) ClearBlockCache() {
374 func (client *KeepTestClient) Close() {
378 func (client *KeepTestClient) SetStorageClasses(sc []string) {
379 client.StorageClasses = sc
382 type FileWrapper struct {
387 func (fw FileWrapper) Readdir(n int) ([]os.FileInfo, error) {
388 return nil, errors.New("not implemented")
391 func (fw FileWrapper) Seek(int64, int) (int64, error) {
392 return 0, errors.New("not implemented")
395 func (fw FileWrapper) Size() int64 {
399 func (fw FileWrapper) Stat() (os.FileInfo, error) {
400 return nil, errors.New("not implemented")
403 func (fw FileWrapper) Truncate(int64) error {
404 return errors.New("not implemented")
407 func (fw FileWrapper) Write([]byte) (int, error) {
408 return 0, errors.New("not implemented")
411 func (fw FileWrapper) Sync() error {
412 return errors.New("not implemented")
415 func (fw FileWrapper) Snapshot() (*arvados.Subtree, error) {
416 return nil, errors.New("not implemented")
419 func (fw FileWrapper) Splice(*arvados.Subtree) error {
420 return errors.New("not implemented")
423 func (client *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
424 if filename == hwImageID+".tar" {
425 rdr := ioutil.NopCloser(&bytes.Buffer{})
427 return FileWrapper{rdr, 1321984}, nil
428 } else if filename == "/file1_in_main.txt" {
429 rdr := ioutil.NopCloser(strings.NewReader("foo"))
431 return FileWrapper{rdr, 3}, nil
436 type apiStubServer struct {
437 server *httptest.Server
438 proxy *httputil.ReverseProxy
439 intercept func(http.ResponseWriter, *http.Request) bool
441 container arvados.Container
442 logs map[string]string
445 func apiStub() (*arvados.Client, *apiStubServer) {
446 client := arvados.NewClientFromEnv()
447 apistub := &apiStubServer{}
448 apistub.server = httptest.NewTLSServer(apistub)
449 apistub.proxy = httputil.NewSingleHostReverseProxy(&url.URL{Scheme: "https", Host: client.APIHost})
451 apistub.proxy.Transport = arvados.InsecureHTTPClient.Transport
453 client.APIHost = apistub.server.Listener.Addr().String()
454 return client, apistub
457 func (apistub *apiStubServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
458 if apistub.intercept != nil && apistub.intercept(w, r) {
461 if r.Method == "POST" && r.URL.Path == "/arvados/v1/logs" {
464 EventType string `json:"event_type"`
470 json.NewDecoder(r.Body).Decode(&body)
471 apistub.logs[body.Log.EventType] += body.Log.Properties.Text
474 if r.Method == "GET" && r.URL.Path == "/arvados/v1/collections/"+hwPDH {
475 json.NewEncoder(w).Encode(arvados.Collection{ManifestText: hwManifest})
478 if r.Method == "GET" && r.URL.Path == "/arvados/v1/collections/"+otherPDH {
479 json.NewEncoder(w).Encode(arvados.Collection{ManifestText: otherManifest})
482 if r.Method == "GET" && r.URL.Path == "/arvados/v1/collections/"+normalizedWithSubdirsPDH {
483 json.NewEncoder(w).Encode(arvados.Collection{ManifestText: normalizedManifestWithSubdirs})
486 if r.Method == "GET" && r.URL.Path == "/arvados/v1/collections/"+denormalizedWithSubdirsPDH {
487 json.NewEncoder(w).Encode(arvados.Collection{ManifestText: denormalizedManifestWithSubdirs})
490 if r.Method == "GET" && r.URL.Path == "/arvados/v1/containers/"+apistub.container.UUID {
491 json.NewEncoder(w).Encode(apistub.container)
494 apistub.proxy.ServeHTTP(w, r)
497 func (s *TestSuite) TestLoadImage(c *C) {
498 s.runner.Container.ContainerImage = arvadostest.DockerImage112PDH
499 s.runner.Container.Mounts = map[string]arvados.Mount{
500 "/out": {Kind: "tmp", Writable: true},
502 s.runner.Container.OutputPath = "/out"
504 _, err := s.runner.SetupMounts()
507 imageID, err := s.runner.LoadImage()
509 c.Check(s.executor.loaded, Matches, ".*"+regexp.QuoteMeta(arvadostest.DockerImage112Filename))
510 c.Check(imageID, Equals, strings.TrimSuffix(arvadostest.DockerImage112Filename, ".tar"))
512 s.runner.Container.ContainerImage = arvadostest.DockerImage112PDH
513 s.executor.imageLoaded = false
514 s.executor.loaded = ""
515 s.executor.loadErr = errors.New("bork")
516 imageID, err = s.runner.LoadImage()
517 c.Check(err, ErrorMatches, ".*bork")
518 c.Check(s.executor.loaded, Matches, ".*"+regexp.QuoteMeta(arvadostest.DockerImage112Filename))
520 s.runner.Container.ContainerImage = fakeInputCollectionPDH
521 s.executor.imageLoaded = false
522 s.executor.loaded = ""
523 s.executor.loadErr = nil
524 imageID, err = s.runner.LoadImage()
525 c.Check(err, ErrorMatches, "image collection does not include a \\.tar image file")
526 c.Check(s.executor.loaded, Equals, "")
529 type ArvErrorTestClient struct{}
531 func (ArvErrorTestClient) Create(resourceType string,
532 parameters arvadosclient.Dict,
533 output interface{}) error {
537 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
538 if method == "GET" && resourceType == "containers" && action == "auth" {
541 return errors.New("ArvError")
544 func (ArvErrorTestClient) CallRaw(method, resourceType, uuid, action string,
545 parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
546 return nil, errors.New("ArvError")
549 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
550 return errors.New("ArvError")
553 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
557 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
558 return discoveryMap[key], nil
561 type KeepErrorTestClient struct {
565 func (*KeepErrorTestClient) ManifestFileReader(manifest.Manifest, string) (arvados.File, error) {
566 return nil, errors.New("KeepError")
569 func (*KeepErrorTestClient) BlockWrite(context.Context, arvados.BlockWriteOptions) (arvados.BlockWriteResponse, error) {
570 return arvados.BlockWriteResponse{}, errors.New("KeepError")
573 func (*KeepErrorTestClient) LocalLocator(string) (string, error) {
574 return "", errors.New("KeepError")
577 type KeepReadErrorTestClient struct {
581 func (*KeepReadErrorTestClient) ReadAt(string, []byte, int) (int, error) {
582 return 0, errors.New("KeepError")
585 type ErrorReader struct {
589 func (ErrorReader) Read(p []byte) (n int, err error) {
590 return 0, errors.New("ErrorReader")
593 func (ErrorReader) Seek(int64, int) (int64, error) {
594 return 0, errors.New("ErrorReader")
597 func (KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
598 return ErrorReader{}, nil
601 type ClosableBuffer struct {
605 func (*ClosableBuffer) Close() error {
609 type TestLogs struct {
610 Stdout ClosableBuffer
611 Stderr ClosableBuffer
614 func (tl *TestLogs) NewTestLoggingWriter(logstr string) (io.WriteCloser, error) {
615 if logstr == "stdout" {
616 return &tl.Stdout, nil
618 if logstr == "stderr" {
619 return &tl.Stderr, nil
621 return nil, errors.New("???")
624 func dockerLog(fd byte, msg string) []byte {
626 header := make([]byte, 8+len(by))
628 header[7] = byte(len(by))
633 func (s *TestSuite) TestRunContainer(c *C) {
634 s.executor.runFunc = func() int {
635 fmt.Fprintf(s.executor.created.Stdout, "Hello world\n")
640 s.runner.NewLogWriter = logs.NewTestLoggingWriter
641 s.runner.Container.ContainerImage = arvadostest.DockerImage112PDH
642 s.runner.Container.Command = []string{"./hw"}
643 s.runner.Container.OutputStorageClasses = []string{"default"}
645 imageID, err := s.runner.LoadImage()
648 err = s.runner.CreateContainer(imageID, nil)
651 err = s.runner.StartContainer()
654 err = s.runner.WaitFinish()
657 c.Check(logs.Stdout.String(), Matches, ".*Hello world\n")
658 c.Check(logs.Stderr.String(), Equals, "")
661 func (s *TestSuite) TestCommitLogs(c *C) {
662 api := &ArvTestClient{}
663 kc := &KeepTestClient{}
665 cr, err := NewContainerRunner(s.client, api, kc, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
667 cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
669 cr.CrunchLog.Print("Hello world!")
670 cr.CrunchLog.Print("Goodbye")
671 cr.finalState = "Complete"
673 err = cr.CommitLogs()
676 c.Check(api.Calls, Equals, 2)
677 c.Check(api.Content[1]["ensure_unique_name"], Equals, true)
678 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
679 c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
680 c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
683 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
684 api := &ArvTestClient{}
685 kc := &KeepTestClient{}
687 cr, err := NewContainerRunner(s.client, api, kc, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
690 err = cr.UpdateContainerRunning("")
693 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
696 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
697 api := &ArvTestClient{}
698 kc := &KeepTestClient{}
700 cr, err := NewContainerRunner(s.client, api, kc, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
703 cr.LogsPDH = new(string)
704 *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
706 cr.ExitCode = new(int)
708 cr.finalState = "Complete"
710 err = cr.UpdateContainerFinal()
713 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
714 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
715 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
718 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
719 api := &ArvTestClient{}
720 kc := &KeepTestClient{}
722 cr, err := NewContainerRunner(s.client, api, kc, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
725 cr.finalState = "Cancelled"
727 err = cr.UpdateContainerFinal()
730 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
731 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
732 c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
735 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
736 // dress rehearsal of the Run() function, starting from a JSON container record.
737 func (s *TestSuite) fullRunHelper(c *C, record string, extraMounts []string, fn func() int) (*ArvTestClient, *ContainerRunner, string) {
738 err := json.Unmarshal([]byte(record), &s.api.Container)
740 initialState := s.api.Container.State
743 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
745 err = json.Unmarshal([]byte(record), &sm)
747 secretMounts, err := json.Marshal(sm)
749 c.Logf("SecretMounts decoded %v json %q", sm, secretMounts)
751 s.executor.runFunc = fn
753 s.runner.statInterval = 100 * time.Millisecond
754 s.runner.containerWatchdogInterval = time.Second
756 realTemp := c.MkDir()
758 s.runner.MkTempDir = func(_, prefix string) (string, error) {
760 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, tempcount)
761 err := os.Mkdir(d, os.ModePerm)
762 if err != nil && strings.Contains(err.Error(), ": file exists") {
763 // Test case must have pre-populated the tempdir
768 client, _ := apiStub()
769 s.runner.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
770 return &ArvTestClient{secretMounts: secretMounts}, &s.testContainerKeepClient, client, nil
773 if extraMounts != nil && len(extraMounts) > 0 {
774 err := s.runner.SetupArvMountPoint("keep")
777 for _, m := range extraMounts {
778 os.MkdirAll(s.runner.ArvMountPoint+"/by_id/"+m, os.ModePerm)
783 if s.api.CalledWith("container.state", "Complete") != nil {
786 if s.executor.loadErr == nil && s.executor.createErr == nil && initialState != "Running" {
787 c.Check(s.api.WasSetRunning, Equals, true)
788 var lastupdate arvadosclient.Dict
789 for _, content := range s.api.Content {
790 if content["container"] != nil {
791 lastupdate = content["container"].(arvadosclient.Dict)
794 if lastupdate["log"] == nil {
795 c.Errorf("no container update with non-nil log -- updates were: %v", s.api.Content)
800 for k, v := range s.api.Logs {
806 return s.api, s.runner, realTemp
809 func (s *TestSuite) TestFullRunHello(c *C) {
810 s.runner.enableMemoryLimit = true
811 s.runner.networkMode = "default"
812 s.fullRunHelper(c, `{
813 "command": ["echo", "hello world"],
814 "container_image": "`+arvadostest.DockerImage112PDH+`",
816 "environment": {"foo":"bar","baz":"waz"},
817 "mounts": {"/tmp": {"kind": "tmp"} },
818 "output_path": "/tmp",
820 "runtime_constraints": {"vcpus":1,"ram":1000000},
822 "output_storage_classes": ["default"]
823 }`, nil, func() int {
824 c.Check(s.executor.created.Command, DeepEquals, []string{"echo", "hello world"})
825 c.Check(s.executor.created.Image, Equals, "sha256:d8309758b8fe2c81034ffc8a10c36460b77db7bc5e7b448c4e5b684f9d95a678")
826 c.Check(s.executor.created.Env, DeepEquals, map[string]string{"foo": "bar", "baz": "waz"})
827 c.Check(s.executor.created.VCPUs, Equals, 1)
828 c.Check(s.executor.created.RAM, Equals, int64(1000000))
829 c.Check(s.executor.created.NetworkMode, Equals, "default")
830 c.Check(s.executor.created.EnableNetwork, Equals, false)
831 c.Check(s.executor.created.CUDADeviceCount, Equals, 0)
832 fmt.Fprintln(s.executor.created.Stdout, "hello world")
836 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
837 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
838 c.Check(s.api.Logs["stdout"].String(), Matches, ".*hello world\n")
839 c.Check(s.testDispatcherKeepClient.StorageClasses, DeepEquals, []string{"default"})
840 c.Check(s.testContainerKeepClient.StorageClasses, DeepEquals, []string{"default"})
843 func (s *TestSuite) TestRunAlreadyRunning(c *C) {
845 s.fullRunHelper(c, `{
846 "command": ["sleep", "3"],
847 "container_image": "`+arvadostest.DockerImage112PDH+`",
850 "mounts": {"/tmp": {"kind": "tmp"} },
851 "output_path": "/tmp",
853 "runtime_constraints": {},
854 "scheduling_parameters":{"max_run_time": 1},
856 }`, nil, func() int {
860 c.Check(s.api.CalledWith("container.state", "Cancelled"), IsNil)
861 c.Check(s.api.CalledWith("container.state", "Complete"), IsNil)
862 c.Check(ran, Equals, false)
865 func ec2MetadataServerStub(c *C, token *string, failureRate float64, stoptime *atomic.Value) *httptest.Server {
867 return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
868 if !failedOnce || rand.Float64() < failureRate {
869 w.WriteHeader(http.StatusServiceUnavailable)
874 case "/latest/api/token":
875 fmt.Fprintln(w, *token)
876 case "/latest/meta-data/spot/instance-action":
877 if r.Header.Get("X-aws-ec2-metadata-token") != *token {
878 w.WriteHeader(http.StatusUnauthorized)
879 } else if t, _ := stoptime.Load().(time.Time); t.IsZero() {
880 w.WriteHeader(http.StatusNotFound)
882 fmt.Fprintf(w, `{"action":"stop","time":"%s"}`, t.Format(time.RFC3339))
885 w.WriteHeader(http.StatusNotFound)
890 func (s *TestSuite) TestSpotInterruptionNotice(c *C) {
891 s.testSpotInterruptionNotice(c, 0.1)
894 func (s *TestSuite) TestSpotInterruptionNoticeNotAvailable(c *C) {
895 s.testSpotInterruptionNotice(c, 1)
898 func (s *TestSuite) testSpotInterruptionNotice(c *C, failureRate float64) {
899 var stoptime atomic.Value
900 token := "fake-ec2-metadata-token"
901 stub := ec2MetadataServerStub(c, &token, failureRate, &stoptime)
904 defer func(i time.Duration, u string) {
905 spotInterruptionCheckInterval = i
906 ec2MetadataBaseURL = u
907 }(spotInterruptionCheckInterval, ec2MetadataBaseURL)
908 spotInterruptionCheckInterval = time.Second / 8
909 ec2MetadataBaseURL = stub.URL
911 go s.runner.checkSpotInterruptionNotices()
912 s.fullRunHelper(c, `{
913 "command": ["sleep", "3"],
914 "container_image": "`+arvadostest.DockerImage112PDH+`",
917 "mounts": {"/tmp": {"kind": "tmp"} },
918 "output_path": "/tmp",
920 "runtime_constraints": {},
922 }`, nil, func() int {
923 time.Sleep(time.Second)
924 stoptime.Store(time.Now().Add(time.Minute).UTC())
925 token = "different-fake-ec2-metadata-token"
926 time.Sleep(time.Second)
929 c.Check(s.api.Logs["crunch-run"].String(), Matches, `(?ms).*Checking for spot interruptions every 125ms using instance metadata at http://.*`)
930 c.Check(s.api.Logs["crunch-run"].String(), Matches, `(?ms).*Error checking spot interruptions: 503 Service Unavailable.*`)
931 if failureRate == 1 {
932 c.Check(s.api.Logs["crunch-run"].String(), Matches, `(?ms).*Giving up on checking spot interruptions after too many consecutive failures.*`)
934 text := `Cloud provider scheduled instance stop at ` + stoptime.Load().(time.Time).Format(time.RFC3339)
935 c.Check(s.api.Logs["crunch-run"].String(), Matches, `(?ms).*`+text+`.*`)
936 c.Check(s.api.CalledWith("container.runtime_status.warning", "preemption notice"), NotNil)
937 c.Check(s.api.CalledWith("container.runtime_status.warningDetail", text), NotNil)
938 c.Check(s.api.CalledWith("container.runtime_status.preemptionNotice", text), NotNil)
942 func (s *TestSuite) TestRunTimeExceeded(c *C) {
943 s.fullRunHelper(c, `{
944 "command": ["sleep", "3"],
945 "container_image": "`+arvadostest.DockerImage112PDH+`",
948 "mounts": {"/tmp": {"kind": "tmp"} },
949 "output_path": "/tmp",
951 "runtime_constraints": {},
952 "scheduling_parameters":{"max_run_time": 1},
954 }`, nil, func() int {
955 time.Sleep(3 * time.Second)
959 c.Check(s.api.CalledWith("container.state", "Cancelled"), NotNil)
960 c.Check(s.api.Logs["crunch-run"].String(), Matches, "(?ms).*maximum run time exceeded.*")
963 func (s *TestSuite) TestContainerWaitFails(c *C) {
964 s.fullRunHelper(c, `{
965 "command": ["sleep", "3"],
966 "container_image": "`+arvadostest.DockerImage112PDH+`",
968 "mounts": {"/tmp": {"kind": "tmp"} },
969 "output_path": "/tmp",
972 }`, nil, func() int {
973 s.executor.waitErr = errors.New("Container is not running")
977 c.Check(s.api.CalledWith("container.state", "Cancelled"), NotNil)
978 c.Check(s.api.Logs["crunch-run"].String(), Matches, "(?ms).*Container is not running.*")
981 func (s *TestSuite) TestCrunchstat(c *C) {
982 s.runner.crunchstatFakeFS = os.DirFS("../crunchstat/testdata/debian12")
983 s.fullRunHelper(c, `{
984 "command": ["sleep", "1"],
985 "container_image": "`+arvadostest.DockerImage112PDH+`",
988 "mounts": {"/tmp": {"kind": "tmp"} },
989 "output_path": "/tmp",
991 "runtime_constraints": {},
993 }`, nil, func() int {
994 time.Sleep(time.Second)
998 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
999 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1001 c.Assert(s.api.Logs["crunchstat"], NotNil)
1002 c.Check(s.api.Logs["crunchstat"].String(), Matches, `(?ms).*mem \d+ swap \d+ pgmajfault \d+ rss.*`)
1004 // Check that we called (*crunchstat.Reporter)Stop().
1005 c.Check(s.api.Logs["crunch-run"].String(), Matches, `(?ms).*Maximum crunch-run memory rss usage was \d+ bytes\n.*`)
1008 func (s *TestSuite) TestNodeInfoLog(c *C) {
1009 os.Setenv("SLURMD_NODENAME", "compute2")
1010 s.fullRunHelper(c, `{
1011 "command": ["sleep", "1"],
1012 "container_image": "`+arvadostest.DockerImage112PDH+`",
1015 "mounts": {"/tmp": {"kind": "tmp"} },
1016 "output_path": "/tmp",
1018 "runtime_constraints": {},
1020 }`, nil, func() int {
1021 time.Sleep(time.Second)
1025 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1026 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1028 c.Assert(s.api.Logs["node"], NotNil)
1029 json := s.api.Logs["node"].String()
1030 c.Check(json, Matches, `(?ms).*"uuid": *"zzzzz-7ekkf-2z3mc76g2q73aio".*`)
1031 c.Check(json, Matches, `(?ms).*"total_cpu_cores": *16.*`)
1032 c.Check(json, Not(Matches), `(?ms).*"info":.*`)
1034 c.Assert(s.api.Logs["node-info"], NotNil)
1035 json = s.api.Logs["node-info"].String()
1036 c.Check(json, Matches, `(?ms).*Host Information.*`)
1037 c.Check(json, Matches, `(?ms).*CPU Information.*`)
1038 c.Check(json, Matches, `(?ms).*Memory Information.*`)
1039 c.Check(json, Matches, `(?ms).*Disk Space.*`)
1040 c.Check(json, Matches, `(?ms).*Disk INodes.*`)
1043 func (s *TestSuite) TestLogVersionAndRuntime(c *C) {
1044 s.fullRunHelper(c, `{
1045 "command": ["sleep", "1"],
1046 "container_image": "`+arvadostest.DockerImage112PDH+`",
1049 "mounts": {"/tmp": {"kind": "tmp"} },
1050 "output_path": "/tmp",
1052 "runtime_constraints": {},
1054 }`, nil, func() int {
1058 c.Assert(s.api.Logs["crunch-run"], NotNil)
1059 c.Check(s.api.Logs["crunch-run"].String(), Matches, `(?ms).*crunch-run \S+ \(go\S+\) start.*`)
1060 c.Check(s.api.Logs["crunch-run"].String(), Matches, `(?ms).*crunch-run process has uid=\d+\(.+\) gid=\d+\(.+\) groups=\d+\(.+\)(,\d+\(.+\))*\n.*`)
1061 c.Check(s.api.Logs["crunch-run"].String(), Matches, `(?ms).*Executing container: zzzzz-zzzzz-zzzzzzzzzzzzzzz.*`)
1062 c.Check(s.api.Logs["crunch-run"].String(), Matches, `(?ms).*Using container runtime: stub.*`)
1065 func (s *TestSuite) testLogRSSThresholds(c *C, ram int64, expected []int, notExpected int) {
1066 s.runner.crunchstatFakeFS = os.DirFS("../crunchstat/testdata/debian12")
1067 s.fullRunHelper(c, `{
1068 "command": ["true"],
1069 "container_image": "`+arvadostest.DockerImage112PDH+`",
1072 "mounts": {"/tmp": {"kind": "tmp"} },
1073 "output_path": "/tmp",
1075 "runtime_constraints": {"ram": `+fmt.Sprintf("%d", ram)+`},
1077 }`, nil, func() int { return 0 })
1078 c.Logf("=== crunchstat logs\n%s\n", s.api.Logs["crunchstat"].String())
1079 logs := s.api.Logs["crunch-run"].String()
1080 pattern := logLineStart + `Container using over %d%% of memory \(rss %d/%d bytes\)`
1082 for _, threshold = range expected {
1083 c.Check(logs, Matches, fmt.Sprintf(pattern, threshold, s.debian12MemoryCurrent, ram))
1085 if notExpected > threshold {
1086 c.Check(logs, Not(Matches), fmt.Sprintf(pattern, notExpected, s.debian12MemoryCurrent, ram))
1090 func (s *TestSuite) TestLogNoRSSThresholds(c *C) {
1091 s.testLogRSSThresholds(c, s.debian12MemoryCurrent*10, []int{}, 90)
1094 func (s *TestSuite) TestLogSomeRSSThresholds(c *C) {
1095 onePercentRSS := s.debian12MemoryCurrent / 100
1096 s.testLogRSSThresholds(c, 102*onePercentRSS, []int{90, 95}, 99)
1099 func (s *TestSuite) TestLogAllRSSThresholds(c *C) {
1100 s.testLogRSSThresholds(c, s.debian12MemoryCurrent, []int{90, 95, 99}, 0)
1103 func (s *TestSuite) TestLogMaximaAfterRun(c *C) {
1104 s.runner.crunchstatFakeFS = os.DirFS("../crunchstat/testdata/debian12")
1105 s.runner.parentTemp = c.MkDir()
1106 s.fullRunHelper(c, `{
1107 "command": ["true"],
1108 "container_image": "`+arvadostest.DockerImage112PDH+`",
1111 "mounts": {"/tmp": {"kind": "tmp"} },
1112 "output_path": "/tmp",
1114 "runtime_constraints": {"ram": `+fmt.Sprintf("%d", s.debian12MemoryCurrent*10)+`},
1116 }`, nil, func() int { return 0 })
1117 logs := s.api.Logs["crunch-run"].String()
1118 for _, expected := range []string{
1119 `Maximum disk usage was \d+%, \d+/\d+ bytes`,
1120 fmt.Sprintf(`Maximum container memory swap usage was %d bytes`, s.debian12SwapCurrent),
1121 `Maximum container memory pgmajfault usage was \d+ faults`,
1122 fmt.Sprintf(`Maximum container memory rss usage was 10%%, %d/%d bytes`, s.debian12MemoryCurrent, s.debian12MemoryCurrent*10),
1123 `Maximum crunch-run memory rss usage was \d+ bytes`,
1125 c.Check(logs, Matches, logLineStart+expected)
1129 func (s *TestSuite) TestCommitNodeInfoBeforeStart(c *C) {
1130 var collection_create, container_update arvadosclient.Dict
1131 s.fullRunHelper(c, `{
1132 "command": ["true"],
1133 "container_image": "`+arvadostest.DockerImage112PDH+`",
1136 "mounts": {"/tmp": {"kind": "tmp"} },
1137 "output_path": "/tmp",
1139 "runtime_constraints": {},
1141 "uuid": "zzzzz-dz642-202301121543210"
1142 }`, nil, func() int {
1143 collection_create = s.api.CalledWith("ensure_unique_name", true)
1144 container_update = s.api.CalledWith("container.state", "Running")
1148 c.Assert(collection_create, NotNil)
1149 log_collection := collection_create["collection"].(arvadosclient.Dict)
1150 c.Check(log_collection["name"], Equals, "logs for zzzzz-dz642-202301121543210")
1151 manifest_text := log_collection["manifest_text"].(string)
1152 // We check that the file size is at least two digits as an easy way to
1153 // check the file isn't empty.
1154 c.Check(manifest_text, Matches, `\. .+ \d+:\d{2,}:node-info\.txt( .+)?\n`)
1155 c.Check(manifest_text, Matches, `\. .+ \d+:\d{2,}:node\.json( .+)?\n`)
1157 c.Assert(container_update, NotNil)
1158 // As of Arvados 2.5.0, the container update must specify its log in PDH
1159 // format for the API server to propagate it to container requests, which
1160 // is what we care about for this test.
1161 expect_pdh := fmt.Sprintf("%x+%d", md5.Sum([]byte(manifest_text)), len(manifest_text))
1162 c.Check(container_update["container"].(arvadosclient.Dict)["log"], Equals, expect_pdh)
1165 func (s *TestSuite) TestContainerRecordLog(c *C) {
1166 s.fullRunHelper(c, `{
1167 "command": ["sleep", "1"],
1168 "container_image": "`+arvadostest.DockerImage112PDH+`",
1171 "mounts": {"/tmp": {"kind": "tmp"} },
1172 "output_path": "/tmp",
1174 "runtime_constraints": {},
1178 time.Sleep(time.Second)
1182 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1183 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1185 c.Assert(s.api.Logs["container"], NotNil)
1186 c.Check(s.api.Logs["container"].String(), Matches, `(?ms).*container_image.*`)
1189 func (s *TestSuite) TestFullRunStderr(c *C) {
1190 s.fullRunHelper(c, `{
1191 "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
1192 "container_image": "`+arvadostest.DockerImage112PDH+`",
1195 "mounts": {"/tmp": {"kind": "tmp"} },
1196 "output_path": "/tmp",
1198 "runtime_constraints": {},
1200 }`, nil, func() int {
1201 fmt.Fprintln(s.executor.created.Stdout, "hello")
1202 fmt.Fprintln(s.executor.created.Stderr, "world")
1206 final := s.api.CalledWith("container.state", "Complete")
1207 c.Assert(final, NotNil)
1208 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1209 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1211 c.Check(s.api.Logs["stdout"].String(), Matches, ".*hello\n")
1212 c.Check(s.api.Logs["stderr"].String(), Matches, ".*world\n")
1215 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
1216 s.fullRunHelper(c, `{
1218 "container_image": "`+arvadostest.DockerImage112PDH+`",
1221 "mounts": {"/tmp": {"kind": "tmp"} },
1222 "output_path": "/tmp",
1224 "runtime_constraints": {},
1226 }`, nil, func() int {
1227 fmt.Fprintf(s.executor.created.Stdout, "workdir=%q", s.executor.created.WorkingDir)
1231 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1232 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1233 c.Log(s.api.Logs["stdout"])
1234 c.Check(s.api.Logs["stdout"].String(), Matches, `.*workdir=""\n`)
1237 func (s *TestSuite) TestFullRunSetCwd(c *C) {
1238 s.fullRunHelper(c, `{
1240 "container_image": "`+arvadostest.DockerImage112PDH+`",
1243 "mounts": {"/tmp": {"kind": "tmp"} },
1244 "output_path": "/tmp",
1246 "runtime_constraints": {},
1248 }`, nil, func() int {
1249 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.WorkingDir)
1253 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1254 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1255 c.Check(s.api.Logs["stdout"].String(), Matches, ".*/bin\n")
1258 func (s *TestSuite) TestFullRunSetOutputStorageClasses(c *C) {
1259 s.fullRunHelper(c, `{
1261 "container_image": "`+arvadostest.DockerImage112PDH+`",
1264 "mounts": {"/tmp": {"kind": "tmp"} },
1265 "output_path": "/tmp",
1267 "runtime_constraints": {},
1269 "output_storage_classes": ["foo", "bar"]
1270 }`, nil, func() int {
1271 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.WorkingDir)
1275 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1276 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1277 c.Check(s.api.Logs["stdout"].String(), Matches, ".*/bin\n")
1278 c.Check(s.testDispatcherKeepClient.StorageClasses, DeepEquals, []string{"foo", "bar"})
1279 c.Check(s.testContainerKeepClient.StorageClasses, DeepEquals, []string{"foo", "bar"})
1282 func (s *TestSuite) TestEnableCUDADeviceCount(c *C) {
1283 s.fullRunHelper(c, `{
1285 "container_image": "`+arvadostest.DockerImage112PDH+`",
1288 "mounts": {"/tmp": {"kind": "tmp"} },
1289 "output_path": "/tmp",
1291 "runtime_constraints": {"cuda": {"device_count": 2}},
1293 "output_storage_classes": ["foo", "bar"]
1294 }`, nil, func() int {
1295 fmt.Fprintln(s.executor.created.Stdout, "ok")
1298 c.Check(s.executor.created.CUDADeviceCount, Equals, 2)
1301 func (s *TestSuite) TestEnableCUDAHardwareCapability(c *C) {
1302 s.fullRunHelper(c, `{
1304 "container_image": "`+arvadostest.DockerImage112PDH+`",
1307 "mounts": {"/tmp": {"kind": "tmp"} },
1308 "output_path": "/tmp",
1310 "runtime_constraints": {"cuda": {"hardware_capability": "foo"}},
1312 "output_storage_classes": ["foo", "bar"]
1313 }`, nil, func() int {
1314 fmt.Fprintln(s.executor.created.Stdout, "ok")
1317 c.Check(s.executor.created.CUDADeviceCount, Equals, 0)
1320 func (s *TestSuite) TestStopOnSignal(c *C) {
1321 s.executor.runFunc = func() int {
1322 s.executor.created.Stdout.Write([]byte("foo\n"))
1323 s.runner.SigChan <- syscall.SIGINT
1324 time.Sleep(10 * time.Second)
1327 s.testStopContainer(c)
1330 func (s *TestSuite) TestStopOnArvMountDeath(c *C) {
1331 s.executor.runFunc = func() int {
1332 s.executor.created.Stdout.Write([]byte("foo\n"))
1333 s.runner.ArvMountExit <- nil
1334 close(s.runner.ArvMountExit)
1335 time.Sleep(10 * time.Second)
1338 s.runner.ArvMountExit = make(chan error)
1339 s.testStopContainer(c)
1342 func (s *TestSuite) testStopContainer(c *C) {
1344 "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
1345 "container_image": "` + arvadostest.DockerImage112PDH + `",
1348 "mounts": {"/tmp": {"kind": "tmp"} },
1349 "output_path": "/tmp",
1351 "runtime_constraints": {},
1355 err := json.Unmarshal([]byte(record), &s.api.Container)
1356 c.Assert(err, IsNil)
1358 s.runner.RunArvMount = func([]string, string) (*exec.Cmd, error) { return nil, nil }
1359 s.runner.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1360 return &ArvTestClient{}, &KeepTestClient{}, nil, nil
1363 done := make(chan error)
1365 done <- s.runner.Run()
1368 case <-time.After(20 * time.Second):
1369 pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
1370 c.Fatal("timed out")
1374 for k, v := range s.api.Logs {
1376 c.Log(v.String(), "\n")
1379 c.Check(s.api.CalledWith("container.log", nil), NotNil)
1380 c.Check(s.api.CalledWith("container.state", "Cancelled"), NotNil)
1381 c.Check(s.api.Logs["stdout"].String(), Matches, "(?ms).*foo\n$")
1384 func (s *TestSuite) TestFullRunSetEnv(c *C) {
1385 s.fullRunHelper(c, `{
1386 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1387 "container_image": "`+arvadostest.DockerImage112PDH+`",
1389 "environment": {"FROBIZ": "bilbo"},
1390 "mounts": {"/tmp": {"kind": "tmp"} },
1391 "output_path": "/tmp",
1393 "runtime_constraints": {},
1395 }`, nil, func() int {
1396 fmt.Fprintf(s.executor.created.Stdout, "%v", s.executor.created.Env)
1400 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1401 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1402 c.Check(s.api.Logs["stdout"].String(), Matches, `.*map\[FROBIZ:bilbo\]\n`)
1405 type ArvMountCmdLine struct {
1410 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
1416 func stubCert(c *C, temp string) string {
1417 path := temp + "/ca-certificates.crt"
1418 err := os.WriteFile(path, []byte{}, 0666)
1419 c.Assert(err, IsNil)
1420 os.Setenv("SSL_CERT_FILE", path)
1424 func (s *TestSuite) TestSetupMounts(c *C) {
1426 am := &ArvMountCmdLine{}
1427 cr.RunArvMount = am.ArvMountTest
1428 cr.containerClient, _ = apiStub()
1429 cr.ContainerArvClient = &ArvTestClient{}
1430 cr.ContainerKeepClient = &KeepTestClient{}
1431 cr.Container.OutputStorageClasses = []string{"default"}
1433 realTemp := c.MkDir()
1434 certTemp := c.MkDir()
1435 stubCertPath := stubCert(c, certTemp)
1436 cr.parentTemp = realTemp
1439 cr.MkTempDir = func(_ string, prefix string) (string, error) {
1441 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
1442 err := os.Mkdir(d, os.ModePerm)
1443 if err != nil && strings.Contains(err.Error(), ": file exists") {
1444 // Test case must have pre-populated the tempdir
1450 checkEmpty := func() {
1451 // Should be deleted.
1452 _, err := os.Stat(realTemp)
1453 c.Assert(os.IsNotExist(err), Equals, true)
1455 // Now recreate it for the next test.
1456 c.Assert(os.Mkdir(realTemp, 0777), IsNil)
1461 cr.ArvMountPoint = ""
1462 cr.Container.Mounts = make(map[string]arvados.Mount)
1463 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1464 cr.Container.OutputPath = "/tmp"
1465 cr.statInterval = 5 * time.Second
1466 bindmounts, err := cr.SetupMounts()
1468 c.Check(am.Cmd, DeepEquals, []string{"arv-mount", "--foreground",
1469 "--read-write", "--storage-classes", "default", "--crunchstat-interval=5",
1470 "--mount-by-pdh", "by_id", "--disable-event-listening", "--mount-by-id", "by_uuid", realTemp + "/keep1"})
1471 c.Check(bindmounts, DeepEquals, map[string]bindmount{"/tmp": {realTemp + "/tmp2", false}})
1472 os.RemoveAll(cr.ArvMountPoint)
1479 cr.ArvMountPoint = ""
1480 cr.Container.Mounts = make(map[string]arvados.Mount)
1481 cr.Container.Mounts["/out"] = arvados.Mount{Kind: "tmp"}
1482 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1483 cr.Container.OutputPath = "/out"
1484 cr.Container.OutputStorageClasses = []string{"foo", "bar"}
1486 bindmounts, err := cr.SetupMounts()
1488 c.Check(am.Cmd, DeepEquals, []string{"arv-mount", "--foreground",
1489 "--read-write", "--storage-classes", "foo,bar", "--crunchstat-interval=5",
1490 "--mount-by-pdh", "by_id", "--disable-event-listening", "--mount-by-id", "by_uuid", realTemp + "/keep1"})
1491 c.Check(bindmounts, DeepEquals, map[string]bindmount{"/out": {realTemp + "/tmp2", false}, "/tmp": {realTemp + "/tmp3", false}})
1492 os.RemoveAll(cr.ArvMountPoint)
1499 cr.ArvMountPoint = ""
1500 cr.Container.Mounts = make(map[string]arvados.Mount)
1501 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1502 cr.Container.OutputPath = "/tmp"
1503 cr.Container.RuntimeConstraints.API = true
1504 cr.Container.OutputStorageClasses = []string{"default"}
1506 bindmounts, err := cr.SetupMounts()
1508 c.Check(am.Cmd, DeepEquals, []string{"arv-mount", "--foreground",
1509 "--read-write", "--storage-classes", "default", "--crunchstat-interval=5",
1510 "--mount-by-pdh", "by_id", "--disable-event-listening", "--mount-by-id", "by_uuid", realTemp + "/keep1"})
1511 c.Check(bindmounts, DeepEquals, map[string]bindmount{"/tmp": {realTemp + "/tmp2", false}, "/etc/arvados/ca-certificates.crt": {stubCertPath, true}})
1512 os.RemoveAll(cr.ArvMountPoint)
1516 cr.Container.RuntimeConstraints.API = false
1521 cr.ArvMountPoint = ""
1522 cr.Container.Mounts = map[string]arvados.Mount{
1523 "/keeptmp": {Kind: "collection", Writable: true},
1525 cr.Container.OutputPath = "/keeptmp"
1527 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1529 bindmounts, err := cr.SetupMounts()
1531 c.Check(am.Cmd, DeepEquals, []string{"arv-mount", "--foreground",
1532 "--read-write", "--storage-classes", "default", "--crunchstat-interval=5",
1533 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", "--disable-event-listening", "--mount-by-id", "by_uuid", realTemp + "/keep1"})
1534 c.Check(bindmounts, DeepEquals, map[string]bindmount{"/keeptmp": {realTemp + "/keep1/tmp0", false}})
1535 os.RemoveAll(cr.ArvMountPoint)
1542 cr.ArvMountPoint = ""
1543 cr.Container.Mounts = map[string]arvados.Mount{
1544 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1545 "/keepout": {Kind: "collection", Writable: true},
1547 cr.Container.OutputPath = "/keepout"
1549 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1550 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1552 bindmounts, err := cr.SetupMounts()
1554 c.Check(am.Cmd, DeepEquals, []string{"arv-mount", "--foreground",
1555 "--read-write", "--storage-classes", "default", "--crunchstat-interval=5",
1556 "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", "--disable-event-listening", "--mount-by-id", "by_uuid", realTemp + "/keep1"})
1557 c.Check(bindmounts, DeepEquals, map[string]bindmount{
1558 "/keepinp": {realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", true},
1559 "/keepout": {realTemp + "/keep1/tmp0", false},
1561 os.RemoveAll(cr.ArvMountPoint)
1568 cr.ArvMountPoint = ""
1569 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
1570 cr.Container.Mounts = map[string]arvados.Mount{
1571 "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1572 "/keepout": {Kind: "collection", Writable: true},
1574 cr.Container.OutputPath = "/keepout"
1576 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1577 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1579 bindmounts, err := cr.SetupMounts()
1581 c.Check(am.Cmd, DeepEquals, []string{"arv-mount", "--foreground",
1582 "--read-write", "--storage-classes", "default", "--crunchstat-interval=5", "--ram-cache",
1583 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", "--disable-event-listening", "--mount-by-id", "by_uuid", realTemp + "/keep1"})
1584 c.Check(bindmounts, DeepEquals, map[string]bindmount{
1585 "/keepinp": {realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", true},
1586 "/keepout": {realTemp + "/keep1/tmp0", false},
1588 os.RemoveAll(cr.ArvMountPoint)
1593 for _, test := range []struct {
1597 {in: "foo", out: `"foo"`},
1598 {in: nil, out: `null`},
1599 {in: map[string]int64{"foo": 123456789123456789}, out: `{"foo":123456789123456789}`},
1602 cr.ArvMountPoint = ""
1603 cr.Container.Mounts = map[string]arvados.Mount{
1604 "/mnt/test.json": {Kind: "json", Content: test.in},
1606 bindmounts, err := cr.SetupMounts()
1608 c.Check(bindmounts, DeepEquals, map[string]bindmount{
1609 "/mnt/test.json": {realTemp + "/json2/mountdata.json", true},
1611 content, err := ioutil.ReadFile(realTemp + "/json2/mountdata.json")
1613 c.Check(content, DeepEquals, []byte(test.out))
1614 os.RemoveAll(cr.ArvMountPoint)
1619 for _, test := range []struct {
1623 {in: "foo", out: `foo`},
1624 {in: nil, out: "error"},
1625 {in: map[string]int64{"foo": 123456789123456789}, out: "error"},
1628 cr.ArvMountPoint = ""
1629 cr.Container.Mounts = map[string]arvados.Mount{
1630 "/mnt/test.txt": {Kind: "text", Content: test.in},
1632 bindmounts, err := cr.SetupMounts()
1633 if test.out == "error" {
1634 c.Check(err.Error(), Equals, "content for mount \"/mnt/test.txt\" must be a string")
1637 c.Check(bindmounts, DeepEquals, map[string]bindmount{
1638 "/mnt/test.txt": {realTemp + "/text2/mountdata.text", true},
1640 content, err := ioutil.ReadFile(realTemp + "/text2/mountdata.text")
1642 c.Check(content, DeepEquals, []byte(test.out))
1644 os.RemoveAll(cr.ArvMountPoint)
1649 // Read-only mount points are allowed underneath output_dir mount point
1652 cr.ArvMountPoint = ""
1653 cr.Container.Mounts = make(map[string]arvados.Mount)
1654 cr.Container.Mounts = map[string]arvados.Mount{
1655 "/tmp": {Kind: "tmp"},
1656 "/tmp/foo": {Kind: "collection"},
1658 cr.Container.OutputPath = "/tmp"
1660 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1662 bindmounts, err := cr.SetupMounts()
1664 c.Check(am.Cmd, DeepEquals, []string{"arv-mount", "--foreground",
1665 "--read-write", "--storage-classes", "default", "--crunchstat-interval=5", "--ram-cache",
1666 "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", "--disable-event-listening", "--mount-by-id", "by_uuid", realTemp + "/keep1"})
1667 c.Check(bindmounts, DeepEquals, map[string]bindmount{
1668 "/tmp": {realTemp + "/tmp2", false},
1669 "/tmp/foo": {realTemp + "/keep1/tmp0", true},
1671 os.RemoveAll(cr.ArvMountPoint)
1676 // Writable mount points copied to output_dir mount point
1679 cr.ArvMountPoint = ""
1680 cr.Container.Mounts = make(map[string]arvados.Mount)
1681 cr.Container.Mounts = map[string]arvados.Mount{
1682 "/tmp": {Kind: "tmp"},
1683 "/tmp/foo": {Kind: "collection",
1684 PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53",
1686 "/tmp/bar": {Kind: "collection",
1687 PortableDataHash: "59389a8f9ee9d399be35462a0f92541d+53",
1691 cr.Container.OutputPath = "/tmp"
1693 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1694 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz", os.ModePerm)
1696 rf, _ := os.Create(realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz/quux")
1697 rf.Write([]byte("bar"))
1700 _, err := cr.SetupMounts()
1702 _, err = os.Stat(cr.HostOutputDir + "/foo")
1704 _, err = os.Stat(cr.HostOutputDir + "/bar/quux")
1706 os.RemoveAll(cr.ArvMountPoint)
1711 // Only mount points of kind 'collection' are allowed underneath output_dir mount point
1714 cr.ArvMountPoint = ""
1715 cr.Container.Mounts = make(map[string]arvados.Mount)
1716 cr.Container.Mounts = map[string]arvados.Mount{
1717 "/tmp": {Kind: "tmp"},
1718 "/tmp/foo": {Kind: "tmp"},
1720 cr.Container.OutputPath = "/tmp"
1722 _, err := cr.SetupMounts()
1723 c.Check(err, NotNil)
1724 c.Check(err, ErrorMatches, `only mount points of kind 'collection', 'text' or 'json' are supported underneath the output_path.*`)
1725 os.RemoveAll(cr.ArvMountPoint)
1730 // Only mount point of kind 'collection' is allowed for stdin
1733 cr.ArvMountPoint = ""
1734 cr.Container.Mounts = make(map[string]arvados.Mount)
1735 cr.Container.Mounts = map[string]arvados.Mount{
1736 "stdin": {Kind: "tmp"},
1739 _, err := cr.SetupMounts()
1740 c.Check(err, NotNil)
1741 c.Check(err, ErrorMatches, `unsupported mount kind 'tmp' for stdin.*`)
1742 os.RemoveAll(cr.ArvMountPoint)
1750 cr.ArvMountPoint = ""
1751 git_client.InstallProtocol("https", git_http.NewClient(arvados.InsecureHTTPClient))
1752 cr.token = arvadostest.ActiveToken
1753 cr.Container.Mounts = make(map[string]arvados.Mount)
1754 cr.Container.Mounts = map[string]arvados.Mount{
1757 UUID: arvadostest.Repository2UUID,
1758 Commit: "fd3531f42995344f36c30b79f55f27b502f3d344",
1763 UUID: arvadostest.Repository2UUID,
1764 Commit: "5ebfab0522851df01fec11ec55a6d0f4877b542e",
1768 cr.Container.OutputPath = "/tmp"
1770 bindmounts, err := cr.SetupMounts()
1773 for path, mount := range bindmounts {
1774 c.Check(mount.ReadOnly, Equals, !cr.Container.Mounts[path].Writable, Commentf("%s %#v", path, mount))
1777 data, err := ioutil.ReadFile(bindmounts["/tip"].HostPath + "/dir1/dir2/file with mode 0644")
1779 c.Check(string(data), Equals, "\000\001\002\003")
1780 _, err = ioutil.ReadFile(bindmounts["/tip"].HostPath + "/file only on testbranch")
1781 c.Check(err, FitsTypeOf, &os.PathError{})
1782 c.Check(os.IsNotExist(err), Equals, true)
1784 data, err = ioutil.ReadFile(bindmounts["/non-tip"].HostPath + "/dir1/dir2/file with mode 0644")
1786 c.Check(string(data), Equals, "\000\001\002\003")
1787 data, err = ioutil.ReadFile(bindmounts["/non-tip"].HostPath + "/file only on testbranch")
1789 c.Check(string(data), Equals, "testfile\n")
1796 func (s *TestSuite) TestStdout(c *C) {
1798 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1799 "container_image": "` + arvadostest.DockerImage112PDH + `",
1801 "environment": {"FROBIZ": "bilbo"},
1802 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1803 "output_path": "/tmp",
1805 "runtime_constraints": {},
1809 s.fullRunHelper(c, helperRecord, nil, func() int {
1810 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.Env["FROBIZ"])
1814 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1815 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1816 c.Check(s.runner.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1819 // Used by the TestStdoutWithWrongPath*()
1820 func (s *TestSuite) stdoutErrorRunHelper(c *C, record string, fn func() int) (*ArvTestClient, *ContainerRunner, error) {
1821 err := json.Unmarshal([]byte(record), &s.api.Container)
1822 c.Assert(err, IsNil)
1823 s.executor.runFunc = fn
1824 s.runner.RunArvMount = (&ArvMountCmdLine{}).ArvMountTest
1825 s.runner.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1826 return s.api, &KeepTestClient{}, nil, nil
1828 return s.api, s.runner, s.runner.Run()
1831 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1832 _, _, err := s.stdoutErrorRunHelper(c, `{
1833 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1834 "output_path": "/tmp",
1836 }`, func() int { return 0 })
1837 c.Check(err, ErrorMatches, ".*Stdout path does not start with OutputPath.*")
1840 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1841 _, _, err := s.stdoutErrorRunHelper(c, `{
1842 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1843 "output_path": "/tmp",
1845 }`, func() int { return 0 })
1846 c.Check(err, ErrorMatches, ".*unsupported mount kind 'tmp' for stdout.*")
1849 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1850 _, _, err := s.stdoutErrorRunHelper(c, `{
1851 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1852 "output_path": "/tmp",
1854 }`, func() int { return 0 })
1855 c.Check(err, ErrorMatches, ".*unsupported mount kind 'collection' for stdout.*")
1858 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1859 s.fullRunHelper(c, `{
1860 "command": ["/bin/sh", "-c", "true $ARVADOS_API_HOST"],
1861 "container_image": "`+arvadostest.DockerImage112PDH+`",
1864 "mounts": {"/tmp": {"kind": "tmp"} },
1865 "output_path": "/tmp",
1867 "runtime_constraints": {"API": true},
1869 }`, nil, func() int {
1870 c.Check(s.executor.created.Env["ARVADOS_API_HOST"], Equals, os.Getenv("ARVADOS_API_HOST"))
1873 c.Check(s.api.CalledWith("container.exit_code", 3), NotNil)
1874 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1875 c.Check(s.api.Logs["crunch-run"].String(), Matches, `(?ms).*status code 3\n.*`)
1878 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1879 defer os.Setenv("ARVADOS_API_HOST", os.Getenv("ARVADOS_API_HOST"))
1880 os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1881 s.fullRunHelper(c, `{
1882 "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1883 "container_image": "`+arvadostest.DockerImage112PDH+`",
1886 "mounts": {"/tmp": {"kind": "tmp"} },
1887 "output_path": "/tmp",
1889 "runtime_constraints": {"API": true},
1891 }`, nil, func() int {
1892 s.api.Container.Output = arvadostest.DockerImage112PDH
1896 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1897 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1898 c.Check(s.api.CalledWith("container.output", arvadostest.DockerImage112PDH), NotNil)
1901 func (s *TestSuite) TestArvMountRuntimeStatusWarning(c *C) {
1902 s.runner.RunArvMount = func([]string, string) (*exec.Cmd, error) {
1903 os.Mkdir(s.runner.ArvMountPoint+"/by_id", 0666)
1904 ioutil.WriteFile(s.runner.ArvMountPoint+"/by_id/README", nil, 0666)
1905 return s.runner.ArvMountCmd([]string{"bash", "-c", "echo >&2 Test: Keep write error: I am a teapot; sleep 3"}, "")
1907 s.executor.runFunc = func() int {
1908 time.Sleep(time.Second)
1912 "command": ["sleep", "1"],
1913 "container_image": "` + arvadostest.DockerImage112PDH + `",
1916 "mounts": {"/tmp": {"kind": "tmp"} },
1917 "output_path": "/tmp",
1919 "runtime_constraints": {"API": true},
1922 err := json.Unmarshal([]byte(record), &s.api.Container)
1923 c.Assert(err, IsNil)
1924 err = s.runner.Run()
1925 c.Assert(err, IsNil)
1926 c.Check(s.api.CalledWith("container.exit_code", 137), NotNil)
1927 c.Check(s.api.CalledWith("container.runtime_status.warning", "arv-mount: Keep write error"), NotNil)
1928 c.Check(s.api.CalledWith("container.runtime_status.warningDetail", "Test: Keep write error: I am a teapot"), NotNil)
1929 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1930 c.Check(s.api.Logs["crunch-run"].String(), Matches, `(?ms).*Container exited with status code 137 \(signal 9, SIGKILL\).*`)
1933 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1935 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1936 "container_image": "` + arvadostest.DockerImage112PDH + `",
1938 "environment": {"FROBIZ": "bilbo"},
1940 "/tmp": {"kind": "tmp"},
1941 "/tmp/foo": {"kind": "collection",
1942 "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1943 "exclude_from_output": true
1945 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1947 "output_path": "/tmp",
1949 "runtime_constraints": {},
1953 extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1955 s.fullRunHelper(c, helperRecord, extraMounts, func() int {
1956 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.Env["FROBIZ"])
1960 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
1961 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
1962 c.Check(s.runner.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1965 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1967 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1968 "container_image": "` + arvadostest.DockerImage112PDH + `",
1970 "environment": {"FROBIZ": "bilbo"},
1972 "/tmp": {"kind": "tmp"},
1973 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1974 "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1975 "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1976 "/tmp/foo/baz/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1977 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1979 "output_path": "/tmp",
1981 "runtime_constraints": {},
1983 "uuid": "zzzzz-dz642-202301130848001"
1986 extraMounts := []string{
1987 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1988 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1989 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1992 api, _, realtemp := s.fullRunHelper(c, helperRecord, extraMounts, func() int {
1993 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.Env["FROBIZ"])
1997 c.Check(s.executor.created.BindMounts, DeepEquals, map[string]bindmount{
1998 "/tmp": {realtemp + "/tmp1", false},
1999 "/tmp/foo/bar": {s.keepmount + "/by_id/a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt", true},
2000 "/tmp/foo/baz/sub2file2": {s.keepmount + "/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt", true},
2001 "/tmp/foo/sub1": {s.keepmount + "/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1", true},
2002 "/tmp/foo/sub1file2": {s.keepmount + "/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt", true},
2005 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2006 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2007 output_count := uint(0)
2008 for _, v := range s.runner.ContainerArvClient.(*ArvTestClient).Content {
2009 if v["collection"] == nil {
2012 collection := v["collection"].(arvadosclient.Dict)
2013 if collection["name"].(string) != "output for zzzzz-dz642-202301130848001" {
2016 c.Check(v["ensure_unique_name"], Equals, true)
2017 c.Check(collection["manifest_text"].(string), Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
2018 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:bar 36:18:sub1file2
2019 ./foo/baz 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2
2020 ./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
2021 ./foo/sub1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
2025 c.Check(output_count, Not(Equals), uint(0))
2028 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
2030 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
2031 "container_image": "` + arvadostest.DockerImage112PDH + `",
2033 "environment": {"FROBIZ": "bilbo"},
2035 "/tmp": {"kind": "tmp"},
2036 "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/subdir1/file2_in_subdir1.txt"},
2037 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
2039 "output_path": "/tmp",
2041 "runtime_constraints": {},
2043 "uuid": "zzzzz-dz642-202301130848002"
2046 extraMounts := []string{
2047 "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
2050 s.fullRunHelper(c, helperRecord, extraMounts, func() int {
2051 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.Env["FROBIZ"])
2055 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
2056 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
2057 output_count := uint(0)
2058 for _, v := range s.runner.ContainerArvClient.(*ArvTestClient).Content {
2059 if v["collection"] == nil {
2062 collection := v["collection"].(arvadosclient.Dict)
2063 if collection["name"].(string) != "output for zzzzz-dz642-202301130848002" {
2066 c.Check(collection["manifest_text"].(string), Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
2067 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 10:17:bar
2071 c.Check(output_count, Not(Equals), uint(0))
2074 func (s *TestSuite) TestOutputError(c *C) {
2076 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
2077 "container_image": "` + arvadostest.DockerImage112PDH + `",
2079 "environment": {"FROBIZ": "bilbo"},
2081 "/tmp": {"kind": "tmp"}
2083 "output_path": "/tmp",
2085 "runtime_constraints": {},
2088 s.fullRunHelper(c, helperRecord, nil, func() int {
2089 os.Symlink("/etc/hosts", s.runner.HostOutputDir+"/baz")
2093 c.Check(s.api.CalledWith("container.state", "Cancelled"), NotNil)
2096 func (s *TestSuite) TestStdinCollectionMountPoint(c *C) {
2098 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
2099 "container_image": "` + arvadostest.DockerImage112PDH + `",
2101 "environment": {"FROBIZ": "bilbo"},
2103 "/tmp": {"kind": "tmp"},
2104 "stdin": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/file1_in_main.txt"},
2105 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
2107 "output_path": "/tmp",
2109 "runtime_constraints": {},
2113 extraMounts := []string{
2114 "b0def87f80dd594d4675809e83bd4f15+367/file1_in_main.txt",
2117 api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, func() int {
2118 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.Env["FROBIZ"])
2122 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2123 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2124 for _, v := range api.Content {
2125 if v["collection"] != nil {
2126 collection := v["collection"].(arvadosclient.Dict)
2127 if strings.Index(collection["name"].(string), "output") == 0 {
2128 manifest := collection["manifest_text"].(string)
2129 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
2136 func (s *TestSuite) TestStdinJsonMountPoint(c *C) {
2138 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
2139 "container_image": "` + arvadostest.DockerImage112PDH + `",
2141 "environment": {"FROBIZ": "bilbo"},
2143 "/tmp": {"kind": "tmp"},
2144 "stdin": {"kind": "json", "content": "foo"},
2145 "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
2147 "output_path": "/tmp",
2149 "runtime_constraints": {},
2153 api, _, _ := s.fullRunHelper(c, helperRecord, nil, func() int {
2154 fmt.Fprintln(s.executor.created.Stdout, s.executor.created.Env["FROBIZ"])
2158 c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2159 c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2160 for _, v := range api.Content {
2161 if v["collection"] != nil {
2162 collection := v["collection"].(arvadosclient.Dict)
2163 if strings.Index(collection["name"].(string), "output") == 0 {
2164 manifest := collection["manifest_text"].(string)
2165 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
2172 func (s *TestSuite) TestStderrMount(c *C) {
2173 api, cr, _ := s.fullRunHelper(c, `{
2174 "command": ["/bin/sh", "-c", "echo hello;exit 1"],
2175 "container_image": "`+arvadostest.DockerImage112PDH+`",
2178 "mounts": {"/tmp": {"kind": "tmp"},
2179 "stdout": {"kind": "file", "path": "/tmp/a/out.txt"},
2180 "stderr": {"kind": "file", "path": "/tmp/b/err.txt"}},
2181 "output_path": "/tmp",
2183 "runtime_constraints": {},
2185 }`, nil, func() int {
2186 fmt.Fprintln(s.executor.created.Stdout, "hello")
2187 fmt.Fprintln(s.executor.created.Stderr, "oops")
2191 final := api.CalledWith("container.state", "Complete")
2192 c.Assert(final, NotNil)
2193 c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
2194 c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
2196 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)
2199 func (s *TestSuite) TestNumberRoundTrip(c *C) {
2200 s.api.callraw = true
2201 err := s.runner.fetchContainerRecord()
2202 c.Assert(err, IsNil)
2203 jsondata, err := json.Marshal(s.runner.Container.Mounts["/json"].Content)
2204 c.Logf("%#v", s.runner.Container)
2206 c.Check(string(jsondata), Equals, `{"number":123456789123456789}`)
2209 func (s *TestSuite) TestFullBrokenDocker(c *C) {
2211 for _, setup := range []func(){
2213 c.Log("// waitErr = ocl runtime error")
2214 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\\\"\""`)
2215 nextState = "Cancelled"
2218 c.Log("// loadErr = cannot connect")
2219 s.executor.loadErr = errors.New("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?")
2220 s.runner.brokenNodeHook = c.MkDir() + "/broken-node-hook"
2221 err := ioutil.WriteFile(s.runner.brokenNodeHook, []byte("#!/bin/sh\nexec echo killme\n"), 0700)
2222 c.Assert(err, IsNil)
2223 nextState = "Queued"
2228 s.fullRunHelper(c, `{
2229 "command": ["echo", "hello world"],
2230 "container_image": "`+arvadostest.DockerImage112PDH+`",
2233 "mounts": {"/tmp": {"kind": "tmp"} },
2234 "output_path": "/tmp",
2236 "runtime_constraints": {},
2238 }`, nil, func() int { return 0 })
2239 c.Check(s.api.CalledWith("container.state", nextState), NotNil)
2240 c.Check(s.api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
2241 if s.runner.brokenNodeHook != "" {
2242 c.Check(s.api.Logs["crunch-run"].String(), Matches, "(?ms).*Running broken node hook.*")
2243 c.Check(s.api.Logs["crunch-run"].String(), Matches, "(?ms).*killme.*")
2244 c.Check(s.api.Logs["crunch-run"].String(), Not(Matches), "(?ms).*Writing /var/lock/crunch-run-broken to mark node as broken.*")
2246 c.Check(s.api.Logs["crunch-run"].String(), Matches, "(?ms).*Writing /var/lock/crunch-run-broken to mark node as broken.*")
2251 func (s *TestSuite) TestBadCommand(c *C) {
2252 for _, startError := range []string{
2253 `panic: standard_init_linux.go:175: exec user process caused "no such file or directory"`,
2254 `Error response from daemon: Cannot start container 41f26cbc43bcc1280f4323efb1830a394ba8660c9d1c2b564ba42bf7f7694845: [8] System error: no such file or directory`,
2255 `Error response from daemon: Cannot start container 58099cd76c834f3dc2a4fb76c8028f049ae6d4fdf0ec373e1f2cfea030670c2d: [8] System error: exec: "foobar": executable file not found in $PATH`,
2258 s.executor.startErr = errors.New(startError)
2259 s.fullRunHelper(c, `{
2260 "command": ["echo", "hello world"],
2261 "container_image": "`+arvadostest.DockerImage112PDH+`",
2264 "mounts": {"/tmp": {"kind": "tmp"} },
2265 "output_path": "/tmp",
2267 "runtime_constraints": {},
2269 }`, nil, func() int { return 0 })
2270 c.Check(s.api.CalledWith("container.state", "Cancelled"), NotNil)
2271 c.Check(s.api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2275 func (s *TestSuite) TestSecretTextMountPoint(c *C) {
2277 "command": ["true"],
2278 "container_image": "` + arvadostest.DockerImage112PDH + `",
2281 "/tmp": {"kind": "tmp"},
2282 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2286 "output_path": "/tmp",
2288 "runtime_constraints": {},
2292 s.fullRunHelper(c, helperRecord, nil, func() int {
2293 content, err := ioutil.ReadFile(s.runner.HostOutputDir + "/secret.conf")
2295 c.Check(string(content), Equals, "mypassword")
2299 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
2300 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
2301 c.Check(s.runner.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), NotNil)
2302 c.Check(s.runner.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ""), IsNil)
2304 // under secret mounts, not captured in output
2306 "command": ["true"],
2307 "container_image": "` + arvadostest.DockerImage112PDH + `",
2310 "/tmp": {"kind": "tmp"}
2313 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2315 "output_path": "/tmp",
2317 "runtime_constraints": {},
2322 s.fullRunHelper(c, helperRecord, nil, func() int {
2323 content, err := ioutil.ReadFile(s.runner.HostOutputDir + "/secret.conf")
2325 c.Check(string(content), Equals, "mypassword")
2329 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
2330 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
2331 c.Check(s.runner.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), IsNil)
2332 c.Check(s.runner.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ""), NotNil)
2334 // under secret mounts, output dir is a collection, not captured in output
2336 "command": ["true"],
2337 "container_image": "` + arvadostest.DockerImage112PDH + `",
2340 "/tmp": {"kind": "collection", "writable": true}
2343 "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2345 "output_path": "/tmp",
2347 "runtime_constraints": {},
2352 _, _, realtemp := s.fullRunHelper(c, helperRecord, nil, func() int {
2353 // secret.conf should be provisioned as a separate
2354 // bind mount, i.e., it should not appear in the
2355 // (fake) fuse filesystem as viewed from the host.
2356 content, err := ioutil.ReadFile(s.runner.HostOutputDir + "/secret.conf")
2357 if !c.Check(errors.Is(err, os.ErrNotExist), Equals, true) {
2358 c.Logf("secret.conf: content %q, err %#v", content, err)
2360 err = ioutil.WriteFile(s.runner.HostOutputDir+"/.arvados#collection", []byte(`{"manifest_text":". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo.txt\n"}`), 0700)
2365 content, err := ioutil.ReadFile(realtemp + "/text1/mountdata.text")
2367 c.Check(string(content), Equals, "mypassword")
2368 c.Check(s.executor.created.BindMounts["/tmp/secret.conf"], DeepEquals, bindmount{realtemp + "/text1/mountdata.text", true})
2369 c.Check(s.api.CalledWith("container.exit_code", 0), NotNil)
2370 c.Check(s.api.CalledWith("container.state", "Complete"), NotNil)
2371 c.Check(s.runner.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo.txt\n"), NotNil)
2374 func (s *TestSuite) TestCalculateCost(c *C) {
2375 defer func(s string) { lockdir = s }(lockdir)
2379 cr.costStartTime = now.Add(-time.Hour)
2380 var logbuf bytes.Buffer
2381 cr.CrunchLog.Immediate = log.New(&logbuf, "", 0)
2383 // if there's no InstanceType env var, cost is calculated as 0
2384 os.Unsetenv("InstanceType")
2385 cost := cr.calculateCost(now)
2386 c.Check(cost, Equals, 0.0)
2388 // with InstanceType env var and loadPrices() hasn't run (or
2389 // hasn't found any data), cost is calculated based on
2390 // InstanceType env var
2391 os.Setenv("InstanceType", `{"Price":1.2}`)
2392 defer os.Unsetenv("InstanceType")
2393 cost = cr.calculateCost(now)
2394 c.Check(cost, Equals, 1.2)
2396 // first update tells us the spot price was $1/h until 30
2397 // minutes ago when it increased to $2/h
2398 j, err := json.Marshal([]cloud.InstancePrice{
2399 {StartTime: now.Add(-4 * time.Hour), Price: 1.0},
2400 {StartTime: now.Add(-time.Hour / 2), Price: 2.0},
2402 c.Assert(err, IsNil)
2403 os.WriteFile(lockdir+"/"+pricesfile, j, 0777)
2405 cost = cr.calculateCost(now)
2406 c.Check(cost, Equals, 1.5)
2408 // next update (via --list + SIGUSR2) tells us the spot price
2409 // increased to $3/h 15 minutes ago
2410 j, err = json.Marshal([]cloud.InstancePrice{
2411 {StartTime: now.Add(-time.Hour / 3), Price: 2.0}, // dup of -time.Hour/2 price
2412 {StartTime: now.Add(-time.Hour / 4), Price: 3.0},
2414 c.Assert(err, IsNil)
2415 os.WriteFile(lockdir+"/"+pricesfile, j, 0777)
2417 cost = cr.calculateCost(now)
2418 c.Check(cost, Equals, 1.0/2+2.0/4+3.0/4)
2420 cost = cr.calculateCost(now.Add(-time.Hour / 2))
2421 c.Check(cost, Equals, 0.5)
2423 c.Logf("%s", logbuf.String())
2424 c.Check(logbuf.String(), Matches, `(?ms).*Instance price changed to 1\.00 at 20.* changed to 2\.00 .* changed to 3\.00 .*`)
2425 c.Check(logbuf.String(), Not(Matches), `(?ms).*changed to 2\.00 .* changed to 2\.00 .*`)
2428 func (s *TestSuite) TestSIGUSR2CostUpdate(c *C) {
2431 pricesJSON, err := json.Marshal([]cloud.InstancePrice{
2432 {StartTime: now.Add(-4 * time.Hour), Price: 2.4},
2433 {StartTime: now.Add(-2 * time.Hour), Price: 2.6},
2435 c.Assert(err, IsNil)
2437 os.Setenv("InstanceType", `{"Price":2.2}`)
2438 defer os.Unsetenv("InstanceType")
2439 defer func(s string) { lockdir = s }(lockdir)
2442 // We can't use s.api.CalledWith because timing differences will yield
2443 // different cost values across runs. getCostUpdate iterates over API
2444 // calls until it finds one that sets the cost, then writes that value
2445 // to the next index of costUpdates.
2446 deadline := now.Add(time.Second)
2447 costUpdates := make([]float64, 2)
2450 getCostUpdate := func() {
2451 for ; time.Now().Before(deadline); time.Sleep(time.Second / 10) {
2452 for apiIndex < len(s.api.Content) {
2453 update := s.api.Content[apiIndex]
2457 if update, ok = update["container"].(arvadosclient.Dict); !ok {
2460 if cost, ok = update["cost"].(float64); !ok {
2463 c.Logf("API call #%d updates cost to %v", apiIndex-1, cost)
2464 costUpdates[costIndex] = cost
2471 s.fullRunHelper(c, `{
2472 "command": ["true"],
2473 "container_image": "`+arvadostest.DockerImage112PDH+`",
2476 "mounts": {"/tmp": {"kind": "tmp"} },
2477 "output_path": "/tmp",
2479 "runtime_constraints": {},
2481 "uuid": "zzzzz-dz642-20230320101530a"
2482 }`, nil, func() int {
2483 s.runner.costStartTime = now.Add(-3 * time.Hour)
2484 err := syscall.Kill(pid, syscall.SIGUSR2)
2485 c.Check(err, IsNil, Commentf("error sending first SIGUSR2 to runner"))
2488 err = os.WriteFile(path.Join(lockdir, pricesfile), pricesJSON, 0o700)
2489 c.Check(err, IsNil, Commentf("error writing JSON prices file"))
2490 err = syscall.Kill(pid, syscall.SIGUSR2)
2491 c.Check(err, IsNil, Commentf("error sending second SIGUSR2 to runner"))
2496 // Comparing with format strings makes it easy to ignore minor variations
2497 // in cost across runs while keeping diagnostics pretty.
2498 c.Check(fmt.Sprintf("%.3f", costUpdates[0]), Equals, "6.600")
2499 c.Check(fmt.Sprintf("%.3f", costUpdates[1]), Equals, "7.600")
2502 type FakeProcess struct {
2506 func (fp FakeProcess) CmdlineSlice() ([]string, error) {
2507 return fp.cmdLine, nil