13134: Support for secret mounts in crunch-run.
[arvados.git] / services / crunch-run / crunchrun_test.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package main
6
7 import (
8         "bufio"
9         "bytes"
10         "crypto/md5"
11         "encoding/json"
12         "errors"
13         "fmt"
14         "io"
15         "io/ioutil"
16         "net"
17         "os"
18         "os/exec"
19         "runtime/pprof"
20         "sort"
21         "strings"
22         "sync"
23         "syscall"
24         "testing"
25         "time"
26
27         "git.curoverse.com/arvados.git/sdk/go/arvados"
28         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
29         "git.curoverse.com/arvados.git/sdk/go/arvadostest"
30         "git.curoverse.com/arvados.git/sdk/go/manifest"
31         "golang.org/x/net/context"
32
33         dockertypes "github.com/docker/docker/api/types"
34         dockercontainer "github.com/docker/docker/api/types/container"
35         dockernetwork "github.com/docker/docker/api/types/network"
36         . "gopkg.in/check.v1"
37 )
38
39 // Gocheck boilerplate
40 func TestCrunchExec(t *testing.T) {
41         TestingT(t)
42 }
43
44 // Gocheck boilerplate
45 var _ = Suite(&TestSuite{})
46
47 type TestSuite struct {
48         docker *TestDockerClient
49 }
50
51 func (s *TestSuite) SetUpTest(c *C) {
52         s.docker = NewTestDockerClient()
53 }
54
55 type ArvTestClient struct {
56         Total   int64
57         Calls   int
58         Content []arvadosclient.Dict
59         arvados.Container
60         Logs map[string]*bytes.Buffer
61         sync.Mutex
62         WasSetRunning bool
63         callraw       bool
64 }
65
66 type KeepTestClient struct {
67         Called  bool
68         Content []byte
69 }
70
71 var hwManifest = ". 82ab40c24fc8df01798e57ba66795bb1+841216+Aa124ac75e5168396c73c0a18eda641a4f41791c0@569fa8c3 0:841216:9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7.tar\n"
72 var hwPDH = "a45557269dcb65a6b78f9ac061c0850b+120"
73 var hwImageId = "9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7"
74
75 var otherManifest = ". 68a84f561b1d1708c6baff5e019a9ab3+46+Ae5d0af96944a3690becb1decdf60cc1c937f556d@5693216f 0:46:md5sum.txt\n"
76 var otherPDH = "a3e8f74c6f101eae01fa08bfb4e49b3a+54"
77
78 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
79 ./subdir1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
80 ./subdir1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
81 `
82
83 var normalizedWithSubdirsPDH = "a0def87f80dd594d4675809e83bd4f15+367"
84
85 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"
86 var denormalizedWithSubdirsPDH = "b0def87f80dd594d4675809e83bd4f15+367"
87
88 var fakeAuthUUID = "zzzzz-gj3su-55pqoyepgi2glem"
89 var fakeAuthToken = "a3ltuwzqcu2u4sc0q7yhpc2w7s00fdcqecg5d6e0u3pfohmbjt"
90
91 type TestDockerClient struct {
92         imageLoaded string
93         logReader   io.ReadCloser
94         logWriter   io.WriteCloser
95         fn          func(t *TestDockerClient)
96         exitCode    int
97         stop        chan bool
98         cwd         string
99         env         []string
100         api         *ArvTestClient
101         realTemp    string
102         calledWait  bool
103 }
104
105 func NewTestDockerClient() *TestDockerClient {
106         t := &TestDockerClient{}
107         t.logReader, t.logWriter = io.Pipe()
108         t.stop = make(chan bool, 1)
109         t.cwd = "/"
110         return t
111 }
112
113 type MockConn struct {
114         net.Conn
115 }
116
117 func (m *MockConn) Write(b []byte) (int, error) {
118         return len(b), nil
119 }
120
121 func NewMockConn() *MockConn {
122         c := &MockConn{}
123         return c
124 }
125
126 func (t *TestDockerClient) ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error) {
127         return dockertypes.HijackedResponse{Conn: NewMockConn(), Reader: bufio.NewReader(t.logReader)}, nil
128 }
129
130 func (t *TestDockerClient) ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig, networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error) {
131         if config.WorkingDir != "" {
132                 t.cwd = config.WorkingDir
133         }
134         t.env = config.Env
135         return dockercontainer.ContainerCreateCreatedBody{ID: "abcde"}, nil
136 }
137
138 func (t *TestDockerClient) ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error {
139         if t.exitCode == 3 {
140                 return errors.New(`Error response from daemon: oci runtime error: container_linux.go:247: starting container process caused "process_linux.go:359: container init caused \"rootfs_linux.go:54: mounting \\\"/tmp/keep453790790/by_id/99999999999999999999999999999999+99999/myGenome\\\" to rootfs \\\"/tmp/docker/overlay2/9999999999999999999999999999999999999999999999999999999999999999/merged\\\" at \\\"/tmp/docker/overlay2/9999999999999999999999999999999999999999999999999999999999999999/merged/keep/99999999999999999999999999999999+99999/myGenome\\\" caused \\\"no such file or directory\\\"\""`)
141         }
142         if t.exitCode == 4 {
143                 return errors.New(`panic: standard_init_linux.go:175: exec user process caused "no such file or directory"`)
144         }
145         if t.exitCode == 5 {
146                 return errors.New(`Error response from daemon: Cannot start container 41f26cbc43bcc1280f4323efb1830a394ba8660c9d1c2b564ba42bf7f7694845: [8] System error: no such file or directory`)
147         }
148         if t.exitCode == 6 {
149                 return errors.New(`Error response from daemon: Cannot start container 58099cd76c834f3dc2a4fb76c8028f049ae6d4fdf0ec373e1f2cfea030670c2d: [8] System error: exec: "foobar": executable file not found in $PATH`)
150         }
151
152         if container == "abcde" {
153                 // t.fn gets executed in ContainerWait
154                 return nil
155         } else {
156                 return errors.New("Invalid container id")
157         }
158 }
159
160 func (t *TestDockerClient) ContainerRemove(ctx context.Context, container string, options dockertypes.ContainerRemoveOptions) error {
161         t.stop <- true
162         return nil
163 }
164
165 func (t *TestDockerClient) ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error) {
166         t.calledWait = true
167         body := make(chan dockercontainer.ContainerWaitOKBody, 1)
168         err := make(chan error)
169         go func() {
170                 t.fn(t)
171                 body <- dockercontainer.ContainerWaitOKBody{StatusCode: int64(t.exitCode)}
172         }()
173         return body, err
174 }
175
176 func (t *TestDockerClient) ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error) {
177         if t.exitCode == 2 {
178                 return dockertypes.ImageInspect{}, nil, fmt.Errorf("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?")
179         }
180
181         if t.imageLoaded == image {
182                 return dockertypes.ImageInspect{}, nil, nil
183         } else {
184                 return dockertypes.ImageInspect{}, nil, errors.New("")
185         }
186 }
187
188 func (t *TestDockerClient) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error) {
189         if t.exitCode == 2 {
190                 return dockertypes.ImageLoadResponse{}, fmt.Errorf("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?")
191         }
192         _, err := io.Copy(ioutil.Discard, input)
193         if err != nil {
194                 return dockertypes.ImageLoadResponse{}, err
195         } else {
196                 t.imageLoaded = hwImageId
197                 return dockertypes.ImageLoadResponse{Body: ioutil.NopCloser(input)}, nil
198         }
199 }
200
201 func (*TestDockerClient) ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {
202         return nil, nil
203 }
204
205 func (client *ArvTestClient) Create(resourceType string,
206         parameters arvadosclient.Dict,
207         output interface{}) error {
208
209         client.Mutex.Lock()
210         defer client.Mutex.Unlock()
211
212         client.Calls++
213         client.Content = append(client.Content, parameters)
214
215         if resourceType == "logs" {
216                 et := parameters["log"].(arvadosclient.Dict)["event_type"].(string)
217                 if client.Logs == nil {
218                         client.Logs = make(map[string]*bytes.Buffer)
219                 }
220                 if client.Logs[et] == nil {
221                         client.Logs[et] = &bytes.Buffer{}
222                 }
223                 client.Logs[et].Write([]byte(parameters["log"].(arvadosclient.Dict)["properties"].(map[string]string)["text"]))
224         }
225
226         if resourceType == "collections" && output != nil {
227                 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
228                 outmap := output.(*arvados.Collection)
229                 outmap.PortableDataHash = fmt.Sprintf("%x+%d", md5.Sum([]byte(mt)), len(mt))
230         }
231
232         return nil
233 }
234
235 func (client *ArvTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
236         switch {
237         case method == "GET" && resourceType == "containers" && action == "auth":
238                 return json.Unmarshal([]byte(`{
239                         "kind": "arvados#api_client_authorization",
240                         "uuid": "`+fakeAuthUUID+`",
241                         "api_token": "`+fakeAuthToken+`"
242                         }`), output)
243         default:
244                 return fmt.Errorf("Not found")
245         }
246 }
247
248 func (client *ArvTestClient) CallRaw(method, resourceType, uuid, action string,
249         parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
250         var j []byte
251         if method == "GET" && resourceType == "nodes" && uuid == "" && action == "" {
252                 j = []byte(`{
253                         "kind": "arvados#nodeList",
254                         "items": [{
255                                 "uuid": "zzzzz-7ekkf-2z3mc76g2q73aio",
256                                 "hostname": "compute2",
257                                 "properties": {"total_cpu_cores": 16}
258                         }]}`)
259         } else if method == "GET" && resourceType == "containers" && action == "" && !client.callraw {
260                 if uuid == "" {
261                         j, err = json.Marshal(map[string]interface{}{
262                                 "items": []interface{}{client.Container},
263                                 "kind":  "arvados#nodeList",
264                         })
265                 } else {
266                         j, err = json.Marshal(client.Container)
267                 }
268         } else {
269                 j = []byte(`{
270                         "command": ["sleep", "1"],
271                         "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
272                         "cwd": ".",
273                         "environment": {},
274                         "mounts": {"/tmp": {"kind": "tmp"}, "/json": {"kind": "json", "content": {"number": 123456789123456789}}},
275                         "output_path": "/tmp",
276                         "priority": 1,
277                         "runtime_constraints": {}
278                 }`)
279         }
280         return ioutil.NopCloser(bytes.NewReader(j)), err
281 }
282
283 func (client *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
284         if resourceType == "collections" {
285                 if uuid == hwPDH {
286                         output.(*arvados.Collection).ManifestText = hwManifest
287                 } else if uuid == otherPDH {
288                         output.(*arvados.Collection).ManifestText = otherManifest
289                 } else if uuid == normalizedWithSubdirsPDH {
290                         output.(*arvados.Collection).ManifestText = normalizedManifestWithSubdirs
291                 } else if uuid == denormalizedWithSubdirsPDH {
292                         output.(*arvados.Collection).ManifestText = denormalizedManifestWithSubdirs
293                 }
294         }
295         if resourceType == "containers" {
296                 (*output.(*arvados.Container)) = client.Container
297         }
298         return nil
299 }
300
301 func (client *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
302         client.Mutex.Lock()
303         defer client.Mutex.Unlock()
304         client.Calls++
305         client.Content = append(client.Content, parameters)
306         if resourceType == "containers" {
307                 if parameters["container"].(arvadosclient.Dict)["state"] == "Running" {
308                         client.WasSetRunning = true
309                 }
310         }
311         return nil
312 }
313
314 var discoveryMap = map[string]interface{}{
315         "defaultTrashLifetime":               float64(1209600),
316         "crunchLimitLogBytesPerJob":          float64(67108864),
317         "crunchLogThrottleBytes":             float64(65536),
318         "crunchLogThrottlePeriod":            float64(60),
319         "crunchLogThrottleLines":             float64(1024),
320         "crunchLogPartialLineThrottlePeriod": float64(5),
321         "crunchLogBytesPerEvent":             float64(4096),
322         "crunchLogSecondsBetweenEvents":      float64(1),
323 }
324
325 func (client *ArvTestClient) Discovery(key string) (interface{}, error) {
326         return discoveryMap[key], nil
327 }
328
329 // CalledWith returns the parameters from the first API call whose
330 // parameters match jpath/string. E.g., CalledWith(c, "foo.bar",
331 // "baz") returns parameters with parameters["foo"]["bar"]=="baz". If
332 // no call matches, it returns nil.
333 func (client *ArvTestClient) CalledWith(jpath string, expect interface{}) arvadosclient.Dict {
334 call:
335         for _, content := range client.Content {
336                 var v interface{} = content
337                 for _, k := range strings.Split(jpath, ".") {
338                         if dict, ok := v.(arvadosclient.Dict); !ok {
339                                 continue call
340                         } else {
341                                 v = dict[k]
342                         }
343                 }
344                 if v == expect {
345                         return content
346                 }
347         }
348         return nil
349 }
350
351 func (client *KeepTestClient) PutHB(hash string, buf []byte) (string, int, error) {
352         client.Content = buf
353         return fmt.Sprintf("%s+%d", hash, len(buf)), len(buf), nil
354 }
355
356 func (*KeepTestClient) ClearBlockCache() {
357 }
358
359 type FileWrapper struct {
360         io.ReadCloser
361         len int64
362 }
363
364 func (fw FileWrapper) Readdir(n int) ([]os.FileInfo, error) {
365         return nil, errors.New("not implemented")
366 }
367
368 func (fw FileWrapper) Seek(int64, int) (int64, error) {
369         return 0, errors.New("not implemented")
370 }
371
372 func (fw FileWrapper) Size() int64 {
373         return fw.len
374 }
375
376 func (fw FileWrapper) Stat() (os.FileInfo, error) {
377         return nil, errors.New("not implemented")
378 }
379
380 func (fw FileWrapper) Truncate(int64) error {
381         return errors.New("not implemented")
382 }
383
384 func (fw FileWrapper) Write([]byte) (int, error) {
385         return 0, errors.New("not implemented")
386 }
387
388 func (client *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
389         if filename == hwImageId+".tar" {
390                 rdr := ioutil.NopCloser(&bytes.Buffer{})
391                 client.Called = true
392                 return FileWrapper{rdr, 1321984}, nil
393         } else if filename == "/file1_in_main.txt" {
394                 rdr := ioutil.NopCloser(strings.NewReader("foo"))
395                 client.Called = true
396                 return FileWrapper{rdr, 3}, nil
397         }
398         return nil, nil
399 }
400
401 func (s *TestSuite) TestLoadImage(c *C) {
402         kc := &KeepTestClient{}
403         cr := NewContainerRunner(&ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
404
405         _, err := cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
406
407         _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
408         c.Check(err, NotNil)
409
410         cr.Container.ContainerImage = hwPDH
411
412         // (1) Test loading image from keep
413         c.Check(kc.Called, Equals, false)
414         c.Check(cr.ContainerConfig.Image, Equals, "")
415
416         err = cr.LoadImage()
417
418         c.Check(err, IsNil)
419         defer func() {
420                 cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
421         }()
422
423         c.Check(kc.Called, Equals, true)
424         c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
425
426         _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
427         c.Check(err, IsNil)
428
429         // (2) Test using image that's already loaded
430         kc.Called = false
431         cr.ContainerConfig.Image = ""
432
433         err = cr.LoadImage()
434         c.Check(err, IsNil)
435         c.Check(kc.Called, Equals, false)
436         c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
437
438 }
439
440 type ArvErrorTestClient struct{}
441
442 func (ArvErrorTestClient) Create(resourceType string,
443         parameters arvadosclient.Dict,
444         output interface{}) error {
445         return nil
446 }
447
448 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
449         return errors.New("ArvError")
450 }
451
452 func (ArvErrorTestClient) CallRaw(method, resourceType, uuid, action string,
453         parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
454         return nil, errors.New("ArvError")
455 }
456
457 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
458         return errors.New("ArvError")
459 }
460
461 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
462         return nil
463 }
464
465 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
466         return discoveryMap[key], nil
467 }
468
469 type KeepErrorTestClient struct{}
470
471 func (KeepErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
472         return "", 0, errors.New("KeepError")
473 }
474
475 func (KeepErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
476         return nil, errors.New("KeepError")
477 }
478
479 func (KeepErrorTestClient) ClearBlockCache() {
480 }
481
482 type KeepReadErrorTestClient struct{}
483
484 func (KeepReadErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
485         return "", 0, nil
486 }
487
488 func (KeepReadErrorTestClient) ClearBlockCache() {
489 }
490
491 type ErrorReader struct {
492         FileWrapper
493 }
494
495 func (ErrorReader) Read(p []byte) (n int, err error) {
496         return 0, errors.New("ErrorReader")
497 }
498
499 func (ErrorReader) Seek(int64, int) (int64, error) {
500         return 0, errors.New("ErrorReader")
501 }
502
503 func (KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
504         return ErrorReader{}, nil
505 }
506
507 func (s *TestSuite) TestLoadImageArvError(c *C) {
508         // (1) Arvados error
509         cr := NewContainerRunner(ArvErrorTestClient{}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
510         cr.Container.ContainerImage = hwPDH
511
512         err := cr.LoadImage()
513         c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
514 }
515
516 func (s *TestSuite) TestLoadImageKeepError(c *C) {
517         // (2) Keep error
518         cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
519         cr.Container.ContainerImage = hwPDH
520
521         err := cr.LoadImage()
522         c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
523 }
524
525 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
526         // (3) Collection doesn't contain image
527         cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
528         cr.Container.ContainerImage = otherPDH
529
530         err := cr.LoadImage()
531         c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
532 }
533
534 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
535         // (4) Collection doesn't contain image
536         cr := NewContainerRunner(&ArvTestClient{}, KeepReadErrorTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
537         cr.Container.ContainerImage = hwPDH
538
539         err := cr.LoadImage()
540         c.Check(err, NotNil)
541 }
542
543 type ClosableBuffer struct {
544         bytes.Buffer
545 }
546
547 func (*ClosableBuffer) Close() error {
548         return nil
549 }
550
551 type TestLogs struct {
552         Stdout ClosableBuffer
553         Stderr ClosableBuffer
554 }
555
556 func (tl *TestLogs) NewTestLoggingWriter(logstr string) io.WriteCloser {
557         if logstr == "stdout" {
558                 return &tl.Stdout
559         }
560         if logstr == "stderr" {
561                 return &tl.Stderr
562         }
563         return nil
564 }
565
566 func dockerLog(fd byte, msg string) []byte {
567         by := []byte(msg)
568         header := make([]byte, 8+len(by))
569         header[0] = fd
570         header[7] = byte(len(by))
571         copy(header[8:], by)
572         return header
573 }
574
575 func (s *TestSuite) TestRunContainer(c *C) {
576         s.docker.fn = func(t *TestDockerClient) {
577                 t.logWriter.Write(dockerLog(1, "Hello world\n"))
578                 t.logWriter.Close()
579         }
580         cr := NewContainerRunner(&ArvTestClient{}, &KeepTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
581
582         var logs TestLogs
583         cr.NewLogWriter = logs.NewTestLoggingWriter
584         cr.Container.ContainerImage = hwPDH
585         cr.Container.Command = []string{"./hw"}
586         err := cr.LoadImage()
587         c.Check(err, IsNil)
588
589         err = cr.CreateContainer()
590         c.Check(err, IsNil)
591
592         err = cr.StartContainer()
593         c.Check(err, IsNil)
594
595         err = cr.WaitFinish()
596         c.Check(err, IsNil)
597
598         c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
599         c.Check(logs.Stderr.String(), Equals, "")
600 }
601
602 func (s *TestSuite) TestCommitLogs(c *C) {
603         api := &ArvTestClient{}
604         kc := &KeepTestClient{}
605         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
606         cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
607
608         cr.CrunchLog.Print("Hello world!")
609         cr.CrunchLog.Print("Goodbye")
610         cr.finalState = "Complete"
611
612         err := cr.CommitLogs()
613         c.Check(err, IsNil)
614
615         c.Check(api.Calls, Equals, 2)
616         c.Check(api.Content[1]["ensure_unique_name"], Equals, true)
617         c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
618         c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
619         c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
620 }
621
622 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
623         api := &ArvTestClient{}
624         kc := &KeepTestClient{}
625         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
626
627         err := cr.UpdateContainerRunning()
628         c.Check(err, IsNil)
629
630         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
631 }
632
633 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
634         api := &ArvTestClient{}
635         kc := &KeepTestClient{}
636         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
637
638         cr.LogsPDH = new(string)
639         *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
640
641         cr.ExitCode = new(int)
642         *cr.ExitCode = 42
643         cr.finalState = "Complete"
644
645         err := cr.UpdateContainerFinal()
646         c.Check(err, IsNil)
647
648         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
649         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
650         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
651 }
652
653 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
654         api := &ArvTestClient{}
655         kc := &KeepTestClient{}
656         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
657         cr.cCancelled = true
658         cr.finalState = "Cancelled"
659
660         err := cr.UpdateContainerFinal()
661         c.Check(err, IsNil)
662
663         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
664         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
665         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
666 }
667
668 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
669 // dress rehearsal of the Run() function, starting from a JSON container record.
670 func (s *TestSuite) fullRunHelper(c *C, record string, extraMounts []string, exitCode int, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, realTemp string) {
671         rec := arvados.Container{}
672         err := json.Unmarshal([]byte(record), &rec)
673         c.Check(err, IsNil)
674
675         s.docker.exitCode = exitCode
676         s.docker.fn = fn
677         s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
678
679         api = &ArvTestClient{Container: rec}
680         s.docker.api = api
681         cr = NewContainerRunner(api, &KeepTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
682         cr.statInterval = 100 * time.Millisecond
683         am := &ArvMountCmdLine{}
684         cr.RunArvMount = am.ArvMountTest
685
686         realTemp, err = ioutil.TempDir("", "crunchrun_test1-")
687         c.Assert(err, IsNil)
688         defer os.RemoveAll(realTemp)
689
690         s.docker.realTemp = realTemp
691
692         tempcount := 0
693         cr.MkTempDir = func(_ string, prefix string) (string, error) {
694                 tempcount++
695                 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, tempcount)
696                 err := os.Mkdir(d, os.ModePerm)
697                 if err != nil && strings.Contains(err.Error(), ": file exists") {
698                         // Test case must have pre-populated the tempdir
699                         err = nil
700                 }
701                 return d, err
702         }
703
704         if extraMounts != nil && len(extraMounts) > 0 {
705                 err := cr.SetupArvMountPoint("keep")
706                 c.Check(err, IsNil)
707
708                 for _, m := range extraMounts {
709                         os.MkdirAll(cr.ArvMountPoint+"/by_id/"+m, os.ModePerm)
710                 }
711         }
712
713         err = cr.Run()
714         if api.CalledWith("container.state", "Complete") != nil {
715                 c.Check(err, IsNil)
716         }
717         if exitCode != 2 {
718                 c.Check(api.WasSetRunning, Equals, true)
719                 c.Check(api.Content[api.Calls-2]["container"].(arvadosclient.Dict)["log"], NotNil)
720         }
721
722         if err != nil {
723                 for k, v := range api.Logs {
724                         c.Log(k)
725                         c.Log(v.String())
726                 }
727         }
728
729         return
730 }
731
732 func (s *TestSuite) TestFullRunHello(c *C) {
733         api, _, _ := s.fullRunHelper(c, `{
734     "command": ["echo", "hello world"],
735     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
736     "cwd": ".",
737     "environment": {},
738     "mounts": {"/tmp": {"kind": "tmp"} },
739     "output_path": "/tmp",
740     "priority": 1,
741     "runtime_constraints": {}
742 }`, nil, 0, func(t *TestDockerClient) {
743                 t.logWriter.Write(dockerLog(1, "hello world\n"))
744                 t.logWriter.Close()
745         })
746
747         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
748         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
749         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
750
751 }
752
753 func (s *TestSuite) TestCrunchstat(c *C) {
754         api, _, _ := s.fullRunHelper(c, `{
755                 "command": ["sleep", "1"],
756                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
757                 "cwd": ".",
758                 "environment": {},
759                 "mounts": {"/tmp": {"kind": "tmp"} },
760                 "output_path": "/tmp",
761                 "priority": 1,
762                 "runtime_constraints": {}
763         }`, nil, 0, func(t *TestDockerClient) {
764                 time.Sleep(time.Second)
765                 t.logWriter.Close()
766         })
767
768         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
769         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
770
771         // We didn't actually start a container, so crunchstat didn't
772         // find accounting files and therefore didn't log any stats.
773         // It should have logged a "can't find accounting files"
774         // message after one poll interval, though, so we can confirm
775         // it's alive:
776         c.Assert(api.Logs["crunchstat"], NotNil)
777         c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
778
779         // The "files never appeared" log assures us that we called
780         // (*crunchstat.Reporter)Stop(), and that we set it up with
781         // the correct container ID "abcde":
782         c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files never appeared for abcde\n`)
783 }
784
785 func (s *TestSuite) TestNodeInfoLog(c *C) {
786         os.Setenv("SLURMD_NODENAME", "compute2")
787         api, _, _ := s.fullRunHelper(c, `{
788                 "command": ["sleep", "1"],
789                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
790                 "cwd": ".",
791                 "environment": {},
792                 "mounts": {"/tmp": {"kind": "tmp"} },
793                 "output_path": "/tmp",
794                 "priority": 1,
795                 "runtime_constraints": {}
796         }`, nil, 0,
797                 func(t *TestDockerClient) {
798                         time.Sleep(time.Second)
799                         t.logWriter.Close()
800                 })
801
802         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
803         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
804
805         c.Assert(api.Logs["node"], NotNil)
806         json := api.Logs["node"].String()
807         c.Check(json, Matches, `(?ms).*"uuid": *"zzzzz-7ekkf-2z3mc76g2q73aio".*`)
808         c.Check(json, Matches, `(?ms).*"total_cpu_cores": *16.*`)
809         c.Check(json, Not(Matches), `(?ms).*"info":.*`)
810
811         c.Assert(api.Logs["node-info"], NotNil)
812         json = api.Logs["node-info"].String()
813         c.Check(json, Matches, `(?ms).*Host Information.*`)
814         c.Check(json, Matches, `(?ms).*CPU Information.*`)
815         c.Check(json, Matches, `(?ms).*Memory Information.*`)
816         c.Check(json, Matches, `(?ms).*Disk Space.*`)
817         c.Check(json, Matches, `(?ms).*Disk INodes.*`)
818 }
819
820 func (s *TestSuite) TestContainerRecordLog(c *C) {
821         api, _, _ := s.fullRunHelper(c, `{
822                 "command": ["sleep", "1"],
823                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
824                 "cwd": ".",
825                 "environment": {},
826                 "mounts": {"/tmp": {"kind": "tmp"} },
827                 "output_path": "/tmp",
828                 "priority": 1,
829                 "runtime_constraints": {}
830         }`, nil, 0,
831                 func(t *TestDockerClient) {
832                         time.Sleep(time.Second)
833                         t.logWriter.Close()
834                 })
835
836         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
837         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
838
839         c.Assert(api.Logs["container"], NotNil)
840         c.Check(api.Logs["container"].String(), Matches, `(?ms).*container_image.*`)
841 }
842
843 func (s *TestSuite) TestFullRunStderr(c *C) {
844         api, _, _ := s.fullRunHelper(c, `{
845     "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
846     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
847     "cwd": ".",
848     "environment": {},
849     "mounts": {"/tmp": {"kind": "tmp"} },
850     "output_path": "/tmp",
851     "priority": 1,
852     "runtime_constraints": {}
853 }`, nil, 1, func(t *TestDockerClient) {
854                 t.logWriter.Write(dockerLog(1, "hello\n"))
855                 t.logWriter.Write(dockerLog(2, "world\n"))
856                 t.logWriter.Close()
857         })
858
859         final := api.CalledWith("container.state", "Complete")
860         c.Assert(final, NotNil)
861         c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
862         c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
863
864         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
865         c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
866 }
867
868 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
869         api, _, _ := s.fullRunHelper(c, `{
870     "command": ["pwd"],
871     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
872     "cwd": ".",
873     "environment": {},
874     "mounts": {"/tmp": {"kind": "tmp"} },
875     "output_path": "/tmp",
876     "priority": 1,
877     "runtime_constraints": {}
878 }`, nil, 0, func(t *TestDockerClient) {
879                 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
880                 t.logWriter.Close()
881         })
882
883         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
884         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
885         c.Log(api.Logs["stdout"])
886         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
887 }
888
889 func (s *TestSuite) TestFullRunSetCwd(c *C) {
890         api, _, _ := s.fullRunHelper(c, `{
891     "command": ["pwd"],
892     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
893     "cwd": "/bin",
894     "environment": {},
895     "mounts": {"/tmp": {"kind": "tmp"} },
896     "output_path": "/tmp",
897     "priority": 1,
898     "runtime_constraints": {}
899 }`, nil, 0, func(t *TestDockerClient) {
900                 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
901                 t.logWriter.Close()
902         })
903
904         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
905         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
906         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
907 }
908
909 func (s *TestSuite) TestStopOnSignal(c *C) {
910         s.testStopContainer(c, func(cr *ContainerRunner) {
911                 go func() {
912                         for !s.docker.calledWait {
913                                 time.Sleep(time.Millisecond)
914                         }
915                         cr.SigChan <- syscall.SIGINT
916                 }()
917         })
918 }
919
920 func (s *TestSuite) TestStopOnArvMountDeath(c *C) {
921         s.testStopContainer(c, func(cr *ContainerRunner) {
922                 cr.ArvMountExit = make(chan error)
923                 go func() {
924                         cr.ArvMountExit <- exec.Command("true").Run()
925                         close(cr.ArvMountExit)
926                 }()
927         })
928 }
929
930 func (s *TestSuite) testStopContainer(c *C, setup func(cr *ContainerRunner)) {
931         record := `{
932     "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
933     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
934     "cwd": ".",
935     "environment": {},
936     "mounts": {"/tmp": {"kind": "tmp"} },
937     "output_path": "/tmp",
938     "priority": 1,
939     "runtime_constraints": {}
940 }`
941
942         rec := arvados.Container{}
943         err := json.Unmarshal([]byte(record), &rec)
944         c.Check(err, IsNil)
945
946         s.docker.fn = func(t *TestDockerClient) {
947                 <-t.stop
948                 t.logWriter.Write(dockerLog(1, "foo\n"))
949                 t.logWriter.Close()
950         }
951         s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
952
953         api := &ArvTestClient{Container: rec}
954         cr := NewContainerRunner(api, &KeepTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
955         cr.RunArvMount = func([]string, string) (*exec.Cmd, error) { return nil, nil }
956         setup(cr)
957
958         done := make(chan error)
959         go func() {
960                 done <- cr.Run()
961         }()
962         select {
963         case <-time.After(20 * time.Second):
964                 pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
965                 c.Fatal("timed out")
966         case err = <-done:
967                 c.Check(err, IsNil)
968         }
969         for k, v := range api.Logs {
970                 c.Log(k)
971                 c.Log(v.String())
972         }
973
974         c.Check(api.CalledWith("container.log", nil), NotNil)
975         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
976         c.Check(api.Logs["stdout"].String(), Matches, "(?ms).*foo\n$")
977 }
978
979 func (s *TestSuite) TestFullRunSetEnv(c *C) {
980         api, _, _ := s.fullRunHelper(c, `{
981     "command": ["/bin/sh", "-c", "echo $FROBIZ"],
982     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
983     "cwd": "/bin",
984     "environment": {"FROBIZ": "bilbo"},
985     "mounts": {"/tmp": {"kind": "tmp"} },
986     "output_path": "/tmp",
987     "priority": 1,
988     "runtime_constraints": {}
989 }`, nil, 0, func(t *TestDockerClient) {
990                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
991                 t.logWriter.Close()
992         })
993
994         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
995         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
996         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)
997 }
998
999 type ArvMountCmdLine struct {
1000         Cmd   []string
1001         token string
1002 }
1003
1004 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
1005         am.Cmd = c
1006         am.token = token
1007         return nil, nil
1008 }
1009
1010 func stubCert(temp string) string {
1011         path := temp + "/ca-certificates.crt"
1012         crt, _ := os.Create(path)
1013         crt.Close()
1014         arvadosclient.CertFiles = []string{path}
1015         return path
1016 }
1017
1018 func (s *TestSuite) TestSetupMounts(c *C) {
1019         api := &ArvTestClient{}
1020         kc := &KeepTestClient{}
1021         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1022         am := &ArvMountCmdLine{}
1023         cr.RunArvMount = am.ArvMountTest
1024
1025         realTemp, err := ioutil.TempDir("", "crunchrun_test1-")
1026         c.Assert(err, IsNil)
1027         certTemp, err := ioutil.TempDir("", "crunchrun_test2-")
1028         c.Assert(err, IsNil)
1029         stubCertPath := stubCert(certTemp)
1030
1031         cr.parentTemp = realTemp
1032
1033         defer os.RemoveAll(realTemp)
1034         defer os.RemoveAll(certTemp)
1035
1036         i := 0
1037         cr.MkTempDir = func(_ string, prefix string) (string, error) {
1038                 i++
1039                 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
1040                 err := os.Mkdir(d, os.ModePerm)
1041                 if err != nil && strings.Contains(err.Error(), ": file exists") {
1042                         // Test case must have pre-populated the tempdir
1043                         err = nil
1044                 }
1045                 return d, err
1046         }
1047
1048         checkEmpty := func() {
1049                 // Should be deleted.
1050                 _, err := os.Stat(realTemp)
1051                 c.Assert(os.IsNotExist(err), Equals, true)
1052
1053                 // Now recreate it for the next test.
1054                 c.Assert(os.Mkdir(realTemp, 0777), IsNil)
1055         }
1056
1057         {
1058                 i = 0
1059                 cr.ArvMountPoint = ""
1060                 cr.Container.Mounts = make(map[string]arvados.Mount)
1061                 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1062                 cr.OutputPath = "/tmp"
1063                 cr.statInterval = 5 * time.Second
1064                 err := cr.SetupMounts()
1065                 c.Check(err, IsNil)
1066                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1067                         "--read-write", "--crunchstat-interval=5",
1068                         "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1069                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp"})
1070                 os.RemoveAll(cr.ArvMountPoint)
1071                 cr.CleanupDirs()
1072                 checkEmpty()
1073         }
1074
1075         {
1076                 i = 0
1077                 cr.ArvMountPoint = ""
1078                 cr.Container.Mounts = make(map[string]arvados.Mount)
1079                 cr.Container.Mounts["/out"] = arvados.Mount{Kind: "tmp"}
1080                 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1081                 cr.OutputPath = "/out"
1082
1083                 err := cr.SetupMounts()
1084                 c.Check(err, IsNil)
1085                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1086                         "--read-write", "--crunchstat-interval=5",
1087                         "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1088                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/out", realTemp + "/tmp3:/tmp"})
1089                 os.RemoveAll(cr.ArvMountPoint)
1090                 cr.CleanupDirs()
1091                 checkEmpty()
1092         }
1093
1094         {
1095                 i = 0
1096                 cr.ArvMountPoint = ""
1097                 cr.Container.Mounts = make(map[string]arvados.Mount)
1098                 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1099                 cr.OutputPath = "/tmp"
1100
1101                 apiflag := true
1102                 cr.Container.RuntimeConstraints.API = &apiflag
1103
1104                 err := cr.SetupMounts()
1105                 c.Check(err, IsNil)
1106                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1107                         "--read-write", "--crunchstat-interval=5",
1108                         "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1109                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", stubCertPath + ":/etc/arvados/ca-certificates.crt:ro"})
1110                 os.RemoveAll(cr.ArvMountPoint)
1111                 cr.CleanupDirs()
1112                 checkEmpty()
1113
1114                 apiflag = false
1115         }
1116
1117         {
1118                 i = 0
1119                 cr.ArvMountPoint = ""
1120                 cr.Container.Mounts = map[string]arvados.Mount{
1121                         "/keeptmp": {Kind: "collection", Writable: true},
1122                 }
1123                 cr.OutputPath = "/keeptmp"
1124
1125                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1126
1127                 err := cr.SetupMounts()
1128                 c.Check(err, IsNil)
1129                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1130                         "--read-write", "--crunchstat-interval=5",
1131                         "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1132                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/tmp0:/keeptmp"})
1133                 os.RemoveAll(cr.ArvMountPoint)
1134                 cr.CleanupDirs()
1135                 checkEmpty()
1136         }
1137
1138         {
1139                 i = 0
1140                 cr.ArvMountPoint = ""
1141                 cr.Container.Mounts = map[string]arvados.Mount{
1142                         "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1143                         "/keepout": {Kind: "collection", Writable: true},
1144                 }
1145                 cr.OutputPath = "/keepout"
1146
1147                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1148                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1149
1150                 err := cr.SetupMounts()
1151                 c.Check(err, IsNil)
1152                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1153                         "--read-write", "--crunchstat-interval=5",
1154                         "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1155                 sort.StringSlice(cr.Binds).Sort()
1156                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1157                         realTemp + "/keep1/tmp0:/keepout"})
1158                 os.RemoveAll(cr.ArvMountPoint)
1159                 cr.CleanupDirs()
1160                 checkEmpty()
1161         }
1162
1163         {
1164                 i = 0
1165                 cr.ArvMountPoint = ""
1166                 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
1167                 cr.Container.Mounts = map[string]arvados.Mount{
1168                         "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1169                         "/keepout": {Kind: "collection", Writable: true},
1170                 }
1171                 cr.OutputPath = "/keepout"
1172
1173                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1174                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1175
1176                 err := cr.SetupMounts()
1177                 c.Check(err, IsNil)
1178                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1179                         "--read-write", "--crunchstat-interval=5",
1180                         "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1181                 sort.StringSlice(cr.Binds).Sort()
1182                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1183                         realTemp + "/keep1/tmp0:/keepout"})
1184                 os.RemoveAll(cr.ArvMountPoint)
1185                 cr.CleanupDirs()
1186                 checkEmpty()
1187         }
1188
1189         for _, test := range []struct {
1190                 in  interface{}
1191                 out string
1192         }{
1193                 {in: "foo", out: `"foo"`},
1194                 {in: nil, out: `null`},
1195                 {in: map[string]int64{"foo": 123456789123456789}, out: `{"foo":123456789123456789}`},
1196         } {
1197                 i = 0
1198                 cr.ArvMountPoint = ""
1199                 cr.Container.Mounts = map[string]arvados.Mount{
1200                         "/mnt/test.json": {Kind: "json", Content: test.in},
1201                 }
1202                 err := cr.SetupMounts()
1203                 c.Check(err, IsNil)
1204                 sort.StringSlice(cr.Binds).Sort()
1205                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/json2/mountdata.json:/mnt/test.json:ro"})
1206                 content, err := ioutil.ReadFile(realTemp + "/json2/mountdata.json")
1207                 c.Check(err, IsNil)
1208                 c.Check(content, DeepEquals, []byte(test.out))
1209                 os.RemoveAll(cr.ArvMountPoint)
1210                 cr.CleanupDirs()
1211                 checkEmpty()
1212         }
1213
1214         for _, test := range []struct {
1215                 in  interface{}
1216                 out string
1217         }{
1218                 {in: "foo", out: `foo`},
1219                 {in: nil, out: "error"},
1220                 {in: map[string]int64{"foo": 123456789123456789}, out: "error"},
1221         } {
1222                 i = 0
1223                 cr.ArvMountPoint = ""
1224                 cr.Container.Mounts = map[string]arvados.Mount{
1225                         "/mnt/test.txt": {Kind: "text", Content: test.in},
1226                 }
1227                 err := cr.SetupMounts()
1228                 if test.out == "error" {
1229                         c.Check(err.Error(), Equals, "content for mount \"/mnt/test.txt\" must be a string")
1230                 } else {
1231                         c.Check(err, IsNil)
1232                         sort.StringSlice(cr.Binds).Sort()
1233                         c.Check(cr.Binds, DeepEquals, []string{realTemp + "/text2/mountdata.text:/mnt/test.txt:ro"})
1234                         content, err := ioutil.ReadFile(realTemp + "/text2/mountdata.text")
1235                         c.Check(err, IsNil)
1236                         c.Check(content, DeepEquals, []byte(test.out))
1237                 }
1238                 os.RemoveAll(cr.ArvMountPoint)
1239                 cr.CleanupDirs()
1240                 checkEmpty()
1241         }
1242
1243         // Read-only mount points are allowed underneath output_dir mount point
1244         {
1245                 i = 0
1246                 cr.ArvMountPoint = ""
1247                 cr.Container.Mounts = make(map[string]arvados.Mount)
1248                 cr.Container.Mounts = map[string]arvados.Mount{
1249                         "/tmp":     {Kind: "tmp"},
1250                         "/tmp/foo": {Kind: "collection"},
1251                 }
1252                 cr.OutputPath = "/tmp"
1253
1254                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1255
1256                 err := cr.SetupMounts()
1257                 c.Check(err, IsNil)
1258                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1259                         "--read-write", "--crunchstat-interval=5",
1260                         "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1261                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", realTemp + "/keep1/tmp0:/tmp/foo:ro"})
1262                 os.RemoveAll(cr.ArvMountPoint)
1263                 cr.CleanupDirs()
1264                 checkEmpty()
1265         }
1266
1267         // Writable mount points copied to output_dir mount point
1268         {
1269                 i = 0
1270                 cr.ArvMountPoint = ""
1271                 cr.Container.Mounts = make(map[string]arvados.Mount)
1272                 cr.Container.Mounts = map[string]arvados.Mount{
1273                         "/tmp": {Kind: "tmp"},
1274                         "/tmp/foo": {Kind: "collection",
1275                                 PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53",
1276                                 Writable:         true},
1277                         "/tmp/bar": {Kind: "collection",
1278                                 PortableDataHash: "59389a8f9ee9d399be35462a0f92541d+53",
1279                                 Path:             "baz",
1280                                 Writable:         true},
1281                 }
1282                 cr.OutputPath = "/tmp"
1283
1284                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1285                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz", os.ModePerm)
1286
1287                 rf, _ := os.Create(realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz/quux")
1288                 rf.Write([]byte("bar"))
1289                 rf.Close()
1290
1291                 err := cr.SetupMounts()
1292                 c.Check(err, IsNil)
1293                 _, err = os.Stat(cr.HostOutputDir + "/foo")
1294                 c.Check(err, IsNil)
1295                 _, err = os.Stat(cr.HostOutputDir + "/bar/quux")
1296                 c.Check(err, IsNil)
1297                 os.RemoveAll(cr.ArvMountPoint)
1298                 cr.CleanupDirs()
1299                 checkEmpty()
1300         }
1301
1302         // Only mount points of kind 'collection' are allowed underneath output_dir mount point
1303         {
1304                 i = 0
1305                 cr.ArvMountPoint = ""
1306                 cr.Container.Mounts = make(map[string]arvados.Mount)
1307                 cr.Container.Mounts = map[string]arvados.Mount{
1308                         "/tmp":     {Kind: "tmp"},
1309                         "/tmp/foo": {Kind: "tmp"},
1310                 }
1311                 cr.OutputPath = "/tmp"
1312
1313                 err := cr.SetupMounts()
1314                 c.Check(err, NotNil)
1315                 c.Check(err, ErrorMatches, `Only mount points of kind 'collection', 'text' or 'json' are supported underneath the output_path.*`)
1316                 os.RemoveAll(cr.ArvMountPoint)
1317                 cr.CleanupDirs()
1318                 checkEmpty()
1319         }
1320
1321         // Only mount point of kind 'collection' is allowed for stdin
1322         {
1323                 i = 0
1324                 cr.ArvMountPoint = ""
1325                 cr.Container.Mounts = make(map[string]arvados.Mount)
1326                 cr.Container.Mounts = map[string]arvados.Mount{
1327                         "stdin": {Kind: "tmp"},
1328                 }
1329
1330                 err := cr.SetupMounts()
1331                 c.Check(err, NotNil)
1332                 c.Check(err, ErrorMatches, `Unsupported mount kind 'tmp' for stdin.*`)
1333                 os.RemoveAll(cr.ArvMountPoint)
1334                 cr.CleanupDirs()
1335                 checkEmpty()
1336         }
1337
1338         // git_tree mounts
1339         {
1340                 i = 0
1341                 cr.ArvMountPoint = ""
1342                 (*GitMountSuite)(nil).useTestGitServer(c)
1343                 cr.token = arvadostest.ActiveToken
1344                 cr.Container.Mounts = make(map[string]arvados.Mount)
1345                 cr.Container.Mounts = map[string]arvados.Mount{
1346                         "/tip": {
1347                                 Kind:   "git_tree",
1348                                 UUID:   arvadostest.Repository2UUID,
1349                                 Commit: "fd3531f42995344f36c30b79f55f27b502f3d344",
1350                                 Path:   "/",
1351                         },
1352                         "/non-tip": {
1353                                 Kind:   "git_tree",
1354                                 UUID:   arvadostest.Repository2UUID,
1355                                 Commit: "5ebfab0522851df01fec11ec55a6d0f4877b542e",
1356                                 Path:   "/",
1357                         },
1358                 }
1359                 cr.OutputPath = "/tmp"
1360
1361                 err := cr.SetupMounts()
1362                 c.Check(err, IsNil)
1363
1364                 // dirMap[mountpoint] == tmpdir
1365                 dirMap := make(map[string]string)
1366                 for _, bind := range cr.Binds {
1367                         tokens := strings.Split(bind, ":")
1368                         dirMap[tokens[1]] = tokens[0]
1369
1370                         if cr.Container.Mounts[tokens[1]].Writable {
1371                                 c.Check(len(tokens), Equals, 2)
1372                         } else {
1373                                 c.Check(len(tokens), Equals, 3)
1374                                 c.Check(tokens[2], Equals, "ro")
1375                         }
1376                 }
1377
1378                 data, err := ioutil.ReadFile(dirMap["/tip"] + "/dir1/dir2/file with mode 0644")
1379                 c.Check(err, IsNil)
1380                 c.Check(string(data), Equals, "\000\001\002\003")
1381                 _, err = ioutil.ReadFile(dirMap["/tip"] + "/file only on testbranch")
1382                 c.Check(err, FitsTypeOf, &os.PathError{})
1383                 c.Check(os.IsNotExist(err), Equals, true)
1384
1385                 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/dir1/dir2/file with mode 0644")
1386                 c.Check(err, IsNil)
1387                 c.Check(string(data), Equals, "\000\001\002\003")
1388                 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/file only on testbranch")
1389                 c.Check(err, IsNil)
1390                 c.Check(string(data), Equals, "testfile\n")
1391
1392                 cr.CleanupDirs()
1393                 checkEmpty()
1394         }
1395 }
1396
1397 func (s *TestSuite) TestStdout(c *C) {
1398         helperRecord := `{
1399                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1400                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1401                 "cwd": "/bin",
1402                 "environment": {"FROBIZ": "bilbo"},
1403                 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1404                 "output_path": "/tmp",
1405                 "priority": 1,
1406                 "runtime_constraints": {}
1407         }`
1408
1409         api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1410                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1411                 t.logWriter.Close()
1412         })
1413
1414         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1415         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1416         c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1417 }
1418
1419 // Used by the TestStdoutWithWrongPath*()
1420 func (s *TestSuite) stdoutErrorRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, err error) {
1421         rec := arvados.Container{}
1422         err = json.Unmarshal([]byte(record), &rec)
1423         c.Check(err, IsNil)
1424
1425         s.docker.fn = fn
1426         s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
1427
1428         api = &ArvTestClient{Container: rec}
1429         cr = NewContainerRunner(api, &KeepTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1430         am := &ArvMountCmdLine{}
1431         cr.RunArvMount = am.ArvMountTest
1432
1433         err = cr.Run()
1434         return
1435 }
1436
1437 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1438         _, _, err := s.stdoutErrorRunHelper(c, `{
1439     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1440     "output_path": "/tmp"
1441 }`, func(t *TestDockerClient) {})
1442
1443         c.Check(err, NotNil)
1444         c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
1445 }
1446
1447 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1448         _, _, err := s.stdoutErrorRunHelper(c, `{
1449     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1450     "output_path": "/tmp"
1451 }`, func(t *TestDockerClient) {})
1452
1453         c.Check(err, NotNil)
1454         c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'tmp' for stdout"), Equals, true)
1455 }
1456
1457 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1458         _, _, err := s.stdoutErrorRunHelper(c, `{
1459     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1460     "output_path": "/tmp"
1461 }`, func(t *TestDockerClient) {})
1462
1463         c.Check(err, NotNil)
1464         c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'collection' for stdout"), Equals, true)
1465 }
1466
1467 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1468         os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1469         defer os.Unsetenv("ARVADOS_API_HOST")
1470         api, _, _ := s.fullRunHelper(c, `{
1471     "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1472     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1473     "cwd": "/bin",
1474     "environment": {},
1475     "mounts": {"/tmp": {"kind": "tmp"} },
1476     "output_path": "/tmp",
1477     "priority": 1,
1478     "runtime_constraints": {"API": true}
1479 }`, nil, 0, func(t *TestDockerClient) {
1480                 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
1481                 t.logWriter.Close()
1482         })
1483
1484         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1485         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1486         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "test.arvados.org\n"), Equals, true)
1487         c.Check(api.CalledWith("container.output", "d41d8cd98f00b204e9800998ecf8427e+0"), NotNil)
1488 }
1489
1490 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1491         os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1492         defer os.Unsetenv("ARVADOS_API_HOST")
1493         api, _, _ := s.fullRunHelper(c, `{
1494     "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1495     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1496     "cwd": "/bin",
1497     "environment": {},
1498     "mounts": {"/tmp": {"kind": "tmp"} },
1499     "output_path": "/tmp",
1500     "priority": 1,
1501     "runtime_constraints": {"API": true}
1502 }`, nil, 0, func(t *TestDockerClient) {
1503                 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
1504                 t.logWriter.Close()
1505         })
1506
1507         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1508         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1509         c.Check(api.CalledWith("container.output", "d4ab34d3d4f8a72f5c4973051ae69fab+122"), NotNil)
1510 }
1511
1512 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1513         helperRecord := `{
1514                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1515                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1516                 "cwd": "/bin",
1517                 "environment": {"FROBIZ": "bilbo"},
1518                 "mounts": {
1519         "/tmp": {"kind": "tmp"},
1520         "/tmp/foo": {"kind": "collection",
1521                      "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1522                      "exclude_from_output": true
1523         },
1524         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1525     },
1526                 "output_path": "/tmp",
1527                 "priority": 1,
1528                 "runtime_constraints": {}
1529         }`
1530
1531         extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1532
1533         api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1534                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1535                 t.logWriter.Close()
1536         })
1537
1538         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1539         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1540         c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1541 }
1542
1543 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1544         helperRecord := `{
1545                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1546                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1547                 "cwd": "/bin",
1548                 "environment": {"FROBIZ": "bilbo"},
1549                 "mounts": {
1550         "/tmp": {"kind": "tmp"},
1551         "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1552         "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1553         "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1554         "/tmp/foo/baz/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1555         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1556     },
1557                 "output_path": "/tmp",
1558                 "priority": 1,
1559                 "runtime_constraints": {}
1560         }`
1561
1562         extraMounts := []string{
1563                 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1564                 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1565                 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1566         }
1567
1568         api, runner, realtemp := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1569                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1570                 t.logWriter.Close()
1571         })
1572
1573         c.Check(runner.Binds, DeepEquals, []string{realtemp + "/tmp2:/tmp",
1574                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt:/tmp/foo/bar:ro",
1575                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt:/tmp/foo/baz/sub2file2:ro",
1576                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1:/tmp/foo/sub1:ro",
1577                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt:/tmp/foo/sub1file2:ro",
1578         })
1579
1580         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1581         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1582         for _, v := range api.Content {
1583                 if v["collection"] != nil {
1584                         c.Check(v["ensure_unique_name"], Equals, true)
1585                         collection := v["collection"].(arvadosclient.Dict)
1586                         if strings.Index(collection["name"].(string), "output") == 0 {
1587                                 manifest := collection["manifest_text"].(string)
1588
1589                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1590 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 9:18:bar 9:18:sub1file2
1591 ./foo/baz 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2
1592 ./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1593 ./foo/sub1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1594 `)
1595                         }
1596                 }
1597         }
1598 }
1599
1600 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
1601         helperRecord := `{
1602                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1603                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1604                 "cwd": "/bin",
1605                 "environment": {"FROBIZ": "bilbo"},
1606                 "mounts": {
1607         "/tmp": {"kind": "tmp"},
1608         "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt"},
1609         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1610     },
1611                 "output_path": "/tmp",
1612                 "priority": 1,
1613                 "runtime_constraints": {}
1614         }`
1615
1616         extraMounts := []string{
1617                 "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1618         }
1619
1620         api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1621                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1622                 t.logWriter.Close()
1623         })
1624
1625         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1626         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1627         for _, v := range api.Content {
1628                 if v["collection"] != nil {
1629                         collection := v["collection"].(arvadosclient.Dict)
1630                         if strings.Index(collection["name"].(string), "output") == 0 {
1631                                 manifest := collection["manifest_text"].(string)
1632
1633                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1634 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 10:17:bar
1635 `)
1636                         }
1637                 }
1638         }
1639 }
1640
1641 func (s *TestSuite) TestOutputSymlinkToInput(c *C) {
1642         helperRecord := `{
1643                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1644                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1645                 "cwd": "/bin",
1646                 "environment": {"FROBIZ": "bilbo"},
1647                 "mounts": {
1648         "/tmp": {"kind": "tmp"},
1649         "/keep/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path": "/subdir1/file2_in_subdir1.txt"},
1650         "/keep/foo2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367"}
1651     },
1652                 "output_path": "/tmp",
1653                 "priority": 1,
1654                 "runtime_constraints": {}
1655         }`
1656
1657         extraMounts := []string{
1658                 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1659         }
1660
1661         api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1662                 os.Symlink("/keep/foo/sub1file2", t.realTemp+"/tmp2/baz")
1663                 os.Symlink("/keep/foo2/subdir1/file2_in_subdir1.txt", t.realTemp+"/tmp2/baz2")
1664                 os.Symlink("/keep/foo2/subdir1", t.realTemp+"/tmp2/baz3")
1665                 os.Mkdir(t.realTemp+"/tmp2/baz4", 0700)
1666                 os.Symlink("/keep/foo2/subdir1/file2_in_subdir1.txt", t.realTemp+"/tmp2/baz4/baz5")
1667                 t.logWriter.Close()
1668         })
1669
1670         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1671         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1672         for _, v := range api.Content {
1673                 if v["collection"] != nil {
1674                         collection := v["collection"].(arvadosclient.Dict)
1675                         if strings.Index(collection["name"].(string), "output") == 0 {
1676                                 manifest := collection["manifest_text"].(string)
1677                                 c.Check(manifest, Equals, `. 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:baz 9:18:baz2
1678 ./baz3 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1679 ./baz3/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1680 ./baz4 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:baz5
1681 `)
1682                         }
1683                 }
1684         }
1685 }
1686
1687 func (s *TestSuite) TestOutputError(c *C) {
1688         helperRecord := `{
1689                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1690                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1691                 "cwd": "/bin",
1692                 "environment": {"FROBIZ": "bilbo"},
1693                 "mounts": {
1694         "/tmp": {"kind": "tmp"}
1695     },
1696                 "output_path": "/tmp",
1697                 "priority": 1,
1698                 "runtime_constraints": {}
1699         }`
1700
1701         extraMounts := []string{}
1702
1703         api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1704                 os.Symlink("/etc/hosts", t.realTemp+"/tmp2/baz")
1705                 t.logWriter.Close()
1706         })
1707
1708         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1709 }
1710
1711 func (s *TestSuite) TestOutputSymlinkToOutput(c *C) {
1712         helperRecord := `{
1713                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1714                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1715                 "cwd": "/bin",
1716                 "environment": {"FROBIZ": "bilbo"},
1717                 "mounts": {
1718         "/tmp": {"kind": "tmp"}
1719     },
1720                 "output_path": "/tmp",
1721                 "priority": 1,
1722                 "runtime_constraints": {}
1723         }`
1724
1725         extraMounts := []string{}
1726
1727         api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1728                 rf, _ := os.Create(t.realTemp + "/tmp2/realfile")
1729                 rf.Write([]byte("foo"))
1730                 rf.Close()
1731
1732                 os.Mkdir(t.realTemp+"/tmp2/realdir", 0700)
1733                 rf, _ = os.Create(t.realTemp + "/tmp2/realdir/subfile")
1734                 rf.Write([]byte("bar"))
1735                 rf.Close()
1736
1737                 os.Symlink("/tmp/realfile", t.realTemp+"/tmp2/file1")
1738                 os.Symlink("realfile", t.realTemp+"/tmp2/file2")
1739                 os.Symlink("/tmp/file1", t.realTemp+"/tmp2/file3")
1740                 os.Symlink("file2", t.realTemp+"/tmp2/file4")
1741                 os.Symlink("realdir", t.realTemp+"/tmp2/dir1")
1742                 os.Symlink("/tmp/realdir", t.realTemp+"/tmp2/dir2")
1743                 t.logWriter.Close()
1744         })
1745
1746         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1747         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1748         for _, v := range api.Content {
1749                 if v["collection"] != nil {
1750                         collection := v["collection"].(arvadosclient.Dict)
1751                         if strings.Index(collection["name"].(string), "output") == 0 {
1752                                 manifest := collection["manifest_text"].(string)
1753                                 c.Check(manifest, Equals,
1754                                         `. 7a2c86e102dcc231bd232aad99686dfa+15 0:3:file1 3:3:file2 6:3:file3 9:3:file4 12:3:realfile
1755 ./dir1 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1756 ./dir2 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1757 ./realdir 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1758 `)
1759                         }
1760                 }
1761         }
1762 }
1763
1764 func (s *TestSuite) TestStdinCollectionMountPoint(c *C) {
1765         helperRecord := `{
1766                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1767                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1768                 "cwd": "/bin",
1769                 "environment": {"FROBIZ": "bilbo"},
1770                 "mounts": {
1771         "/tmp": {"kind": "tmp"},
1772         "stdin": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/file1_in_main.txt"},
1773         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1774     },
1775                 "output_path": "/tmp",
1776                 "priority": 1,
1777                 "runtime_constraints": {}
1778         }`
1779
1780         extraMounts := []string{
1781                 "b0def87f80dd594d4675809e83bd4f15+367/file1_in_main.txt",
1782         }
1783
1784         api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1785                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1786                 t.logWriter.Close()
1787         })
1788
1789         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1790         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1791         for _, v := range api.Content {
1792                 if v["collection"] != nil {
1793                         collection := v["collection"].(arvadosclient.Dict)
1794                         if strings.Index(collection["name"].(string), "output") == 0 {
1795                                 manifest := collection["manifest_text"].(string)
1796                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1797 `)
1798                         }
1799                 }
1800         }
1801 }
1802
1803 func (s *TestSuite) TestStdinJsonMountPoint(c *C) {
1804         helperRecord := `{
1805                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1806                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1807                 "cwd": "/bin",
1808                 "environment": {"FROBIZ": "bilbo"},
1809                 "mounts": {
1810         "/tmp": {"kind": "tmp"},
1811         "stdin": {"kind": "json", "content": "foo"},
1812         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1813     },
1814                 "output_path": "/tmp",
1815                 "priority": 1,
1816                 "runtime_constraints": {}
1817         }`
1818
1819         api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1820                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1821                 t.logWriter.Close()
1822         })
1823
1824         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1825         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1826         for _, v := range api.Content {
1827                 if v["collection"] != nil {
1828                         collection := v["collection"].(arvadosclient.Dict)
1829                         if strings.Index(collection["name"].(string), "output") == 0 {
1830                                 manifest := collection["manifest_text"].(string)
1831                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1832 `)
1833                         }
1834                 }
1835         }
1836 }
1837
1838 func (s *TestSuite) TestStderrMount(c *C) {
1839         api, _, _ := s.fullRunHelper(c, `{
1840     "command": ["/bin/sh", "-c", "echo hello;exit 1"],
1841     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1842     "cwd": ".",
1843     "environment": {},
1844     "mounts": {"/tmp": {"kind": "tmp"},
1845                "stdout": {"kind": "file", "path": "/tmp/a/out.txt"},
1846                "stderr": {"kind": "file", "path": "/tmp/b/err.txt"}},
1847     "output_path": "/tmp",
1848     "priority": 1,
1849     "runtime_constraints": {}
1850 }`, nil, 1, func(t *TestDockerClient) {
1851                 t.logWriter.Write(dockerLog(1, "hello\n"))
1852                 t.logWriter.Write(dockerLog(2, "oops\n"))
1853                 t.logWriter.Close()
1854         })
1855
1856         final := api.CalledWith("container.state", "Complete")
1857         c.Assert(final, NotNil)
1858         c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1859         c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1860
1861         c.Check(api.CalledWith("collection.manifest_text", "./a b1946ac92492d2347c6235b4d2611184+6 0:6:out.txt\n./b 38af5c54926b620264ab1501150cf189+5 0:5:err.txt\n"), NotNil)
1862 }
1863
1864 func (s *TestSuite) TestNumberRoundTrip(c *C) {
1865         cr := NewContainerRunner(&ArvTestClient{callraw: true}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1866         cr.fetchContainerRecord()
1867
1868         jsondata, err := json.Marshal(cr.Container.Mounts["/json"].Content)
1869
1870         c.Check(err, IsNil)
1871         c.Check(string(jsondata), Equals, `{"number":123456789123456789}`)
1872 }
1873
1874 func (s *TestSuite) TestEvalSymlinks(c *C) {
1875         cr := NewContainerRunner(&ArvTestClient{callraw: true}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1876
1877         realTemp, err := ioutil.TempDir("", "crunchrun_test-")
1878         c.Assert(err, IsNil)
1879         defer os.RemoveAll(realTemp)
1880
1881         cr.HostOutputDir = realTemp
1882
1883         // Absolute path outside output dir
1884         os.Symlink("/etc/passwd", realTemp+"/p1")
1885
1886         // Relative outside output dir
1887         os.Symlink("../zip", realTemp+"/p2")
1888
1889         // Circular references
1890         os.Symlink("p4", realTemp+"/p3")
1891         os.Symlink("p5", realTemp+"/p4")
1892         os.Symlink("p3", realTemp+"/p5")
1893
1894         // Target doesn't exist
1895         os.Symlink("p99", realTemp+"/p6")
1896
1897         for _, v := range []string{"p1", "p2", "p3", "p4", "p5"} {
1898                 info, err := os.Lstat(realTemp + "/" + v)
1899                 _, _, _, err = cr.derefOutputSymlink(realTemp+"/"+v, info)
1900                 c.Assert(err, NotNil)
1901         }
1902 }
1903
1904 func (s *TestSuite) TestEvalSymlinkDir(c *C) {
1905         cr := NewContainerRunner(&ArvTestClient{callraw: true}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1906
1907         realTemp, err := ioutil.TempDir("", "crunchrun_test-")
1908         c.Assert(err, IsNil)
1909         defer os.RemoveAll(realTemp)
1910
1911         cr.HostOutputDir = realTemp
1912
1913         // Absolute path outside output dir
1914         os.Symlink(".", realTemp+"/loop")
1915
1916         v := "loop"
1917         info, err := os.Lstat(realTemp + "/" + v)
1918         _, err = cr.UploadOutputFile(realTemp+"/"+v, info, err, []string{}, nil, "", "", 0)
1919         c.Assert(err, NotNil)
1920 }
1921
1922 func (s *TestSuite) TestFullBrokenDocker1(c *C) {
1923         tf, err := ioutil.TempFile("", "brokenNodeHook-")
1924         c.Assert(err, IsNil)
1925         defer os.Remove(tf.Name())
1926
1927         tf.Write([]byte(`#!/bin/sh
1928 exec echo killme
1929 `))
1930         tf.Close()
1931         os.Chmod(tf.Name(), 0700)
1932
1933         ech := tf.Name()
1934         brokenNodeHook = &ech
1935
1936         api, _, _ := s.fullRunHelper(c, `{
1937     "command": ["echo", "hello world"],
1938     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1939     "cwd": ".",
1940     "environment": {},
1941     "mounts": {"/tmp": {"kind": "tmp"} },
1942     "output_path": "/tmp",
1943     "priority": 1,
1944     "runtime_constraints": {}
1945 }`, nil, 2, func(t *TestDockerClient) {
1946                 t.logWriter.Write(dockerLog(1, "hello world\n"))
1947                 t.logWriter.Close()
1948         })
1949
1950         c.Check(api.CalledWith("container.state", "Queued"), NotNil)
1951         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1952         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Running broken node hook.*")
1953         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*killme.*")
1954
1955 }
1956
1957 func (s *TestSuite) TestFullBrokenDocker2(c *C) {
1958         ech := ""
1959         brokenNodeHook = &ech
1960
1961         api, _, _ := s.fullRunHelper(c, `{
1962     "command": ["echo", "hello world"],
1963     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1964     "cwd": ".",
1965     "environment": {},
1966     "mounts": {"/tmp": {"kind": "tmp"} },
1967     "output_path": "/tmp",
1968     "priority": 1,
1969     "runtime_constraints": {}
1970 }`, nil, 2, func(t *TestDockerClient) {
1971                 t.logWriter.Write(dockerLog(1, "hello world\n"))
1972                 t.logWriter.Close()
1973         })
1974
1975         c.Check(api.CalledWith("container.state", "Queued"), NotNil)
1976         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1977         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*No broken node hook.*")
1978 }
1979
1980 func (s *TestSuite) TestFullBrokenDocker3(c *C) {
1981         ech := ""
1982         brokenNodeHook = &ech
1983
1984         api, _, _ := s.fullRunHelper(c, `{
1985     "command": ["echo", "hello world"],
1986     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1987     "cwd": ".",
1988     "environment": {},
1989     "mounts": {"/tmp": {"kind": "tmp"} },
1990     "output_path": "/tmp",
1991     "priority": 1,
1992     "runtime_constraints": {}
1993 }`, nil, 3, func(t *TestDockerClient) {
1994                 t.logWriter.Write(dockerLog(1, "hello world\n"))
1995                 t.logWriter.Close()
1996         })
1997
1998         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1999         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
2000 }
2001
2002 func (s *TestSuite) TestBadCommand1(c *C) {
2003         ech := ""
2004         brokenNodeHook = &ech
2005
2006         api, _, _ := s.fullRunHelper(c, `{
2007     "command": ["echo", "hello world"],
2008     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2009     "cwd": ".",
2010     "environment": {},
2011     "mounts": {"/tmp": {"kind": "tmp"} },
2012     "output_path": "/tmp",
2013     "priority": 1,
2014     "runtime_constraints": {}
2015 }`, nil, 4, func(t *TestDockerClient) {
2016                 t.logWriter.Write(dockerLog(1, "hello world\n"))
2017                 t.logWriter.Close()
2018         })
2019
2020         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2021         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2022 }
2023
2024 func (s *TestSuite) TestBadCommand2(c *C) {
2025         ech := ""
2026         brokenNodeHook = &ech
2027
2028         api, _, _ := s.fullRunHelper(c, `{
2029     "command": ["echo", "hello world"],
2030     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2031     "cwd": ".",
2032     "environment": {},
2033     "mounts": {"/tmp": {"kind": "tmp"} },
2034     "output_path": "/tmp",
2035     "priority": 1,
2036     "runtime_constraints": {}
2037 }`, nil, 5, func(t *TestDockerClient) {
2038                 t.logWriter.Write(dockerLog(1, "hello world\n"))
2039                 t.logWriter.Close()
2040         })
2041
2042         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2043         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2044 }
2045
2046 func (s *TestSuite) TestBadCommand3(c *C) {
2047         ech := ""
2048         brokenNodeHook = &ech
2049
2050         api, _, _ := s.fullRunHelper(c, `{
2051     "command": ["echo", "hello world"],
2052     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2053     "cwd": ".",
2054     "environment": {},
2055     "mounts": {"/tmp": {"kind": "tmp"} },
2056     "output_path": "/tmp",
2057     "priority": 1,
2058     "runtime_constraints": {}
2059 }`, nil, 6, func(t *TestDockerClient) {
2060                 t.logWriter.Write(dockerLog(1, "hello world\n"))
2061                 t.logWriter.Close()
2062         })
2063
2064         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2065         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2066 }
2067
2068 func (s *TestSuite) TestSecretTextMountPoint(c *C) {
2069         // under normal mounts, gets captured in output, oops
2070         helperRecord := `{
2071                 "command": ["true"],
2072                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2073                 "cwd": "/bin",
2074                 "mounts": {
2075                     "/tmp": {"kind": "tmp"},
2076                     "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2077                 },
2078                 "secret_mounts": {
2079                 },
2080                 "output_path": "/tmp",
2081                 "priority": 1,
2082                 "runtime_constraints": {}
2083         }`
2084
2085         api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2086                 t.logWriter.Close()
2087         })
2088
2089         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2090         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2091         c.Check(api.CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), NotNil)
2092         c.Check(api.CalledWith("collection.manifest_text", ""), IsNil)
2093
2094         // under secret mounts, not captured in output
2095         helperRecord = `{
2096                 "command": ["true"],
2097                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2098                 "cwd": "/bin",
2099                 "mounts": {
2100                     "/tmp": {"kind": "tmp"}
2101                 },
2102                 "secret_mounts": {
2103                     "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2104                 },
2105                 "output_path": "/tmp",
2106                 "priority": 1,
2107                 "runtime_constraints": {}
2108         }`
2109
2110         api, _, _ = s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2111                 t.logWriter.Close()
2112         })
2113
2114         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2115         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2116         c.Check(api.CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), IsNil)
2117         c.Check(api.CalledWith("collection.manifest_text", ""), NotNil)
2118 }