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