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