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