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