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