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