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