Merge branch 'master' of git.curoverse.com:arvados into 11876-r-sdk
[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         "context"
11         "crypto/md5"
12         "encoding/json"
13         "errors"
14         "fmt"
15         "io"
16         "io/ioutil"
17         "net"
18         "os"
19         "os/exec"
20         "path/filepath"
21         "runtime/pprof"
22         "sort"
23         "strings"
24         "sync"
25         "syscall"
26         "testing"
27         "time"
28
29         "git.curoverse.com/arvados.git/sdk/go/arvados"
30         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
31         "git.curoverse.com/arvados.git/sdk/go/arvadostest"
32         "git.curoverse.com/arvados.git/sdk/go/manifest"
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 type TestSuite struct{}
46
47 // Gocheck boilerplate
48 var _ = Suite(&TestSuite{})
49
50 type ArvTestClient struct {
51         Total   int64
52         Calls   int
53         Content []arvadosclient.Dict
54         arvados.Container
55         Logs map[string]*bytes.Buffer
56         sync.Mutex
57         WasSetRunning bool
58         callraw       bool
59 }
60
61 type KeepTestClient struct {
62         Called  bool
63         Content []byte
64 }
65
66 var hwManifest = ". 82ab40c24fc8df01798e57ba66795bb1+841216+Aa124ac75e5168396c73c0a18eda641a4f41791c0@569fa8c3 0:841216:9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7.tar\n"
67 var hwPDH = "a45557269dcb65a6b78f9ac061c0850b+120"
68 var hwImageId = "9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7"
69
70 var otherManifest = ". 68a84f561b1d1708c6baff5e019a9ab3+46+Ae5d0af96944a3690becb1decdf60cc1c937f556d@5693216f 0:46:md5sum.txt\n"
71 var otherPDH = "a3e8f74c6f101eae01fa08bfb4e49b3a+54"
72
73 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
74 ./subdir1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
75 ./subdir1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
76 `
77
78 var normalizedWithSubdirsPDH = "a0def87f80dd594d4675809e83bd4f15+367"
79
80 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"
81 var denormalizedWithSubdirsPDH = "b0def87f80dd594d4675809e83bd4f15+367"
82
83 var fakeAuthUUID = "zzzzz-gj3su-55pqoyepgi2glem"
84 var fakeAuthToken = "a3ltuwzqcu2u4sc0q7yhpc2w7s00fdcqecg5d6e0u3pfohmbjt"
85
86 type TestDockerClient struct {
87         imageLoaded string
88         logReader   io.ReadCloser
89         logWriter   io.WriteCloser
90         fn          func(t *TestDockerClient)
91         finish      int
92         stop        chan bool
93         cwd         string
94         env         []string
95         api         *ArvTestClient
96         realTemp    string
97 }
98
99 func NewTestDockerClient(exitCode int) *TestDockerClient {
100         t := &TestDockerClient{}
101         t.logReader, t.logWriter = io.Pipe()
102         t.finish = exitCode
103         t.stop = make(chan bool, 1)
104         t.cwd = "/"
105         return t
106 }
107
108 type MockConn struct {
109         net.Conn
110 }
111
112 func (m *MockConn) Write(b []byte) (int, error) {
113         return len(b), nil
114 }
115
116 func NewMockConn() *MockConn {
117         c := &MockConn{}
118         return c
119 }
120
121 func (t *TestDockerClient) ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error) {
122         return dockertypes.HijackedResponse{Conn: NewMockConn(), Reader: bufio.NewReader(t.logReader)}, nil
123 }
124
125 func (t *TestDockerClient) ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig, networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error) {
126         if config.WorkingDir != "" {
127                 t.cwd = config.WorkingDir
128         }
129         t.env = config.Env
130         return dockercontainer.ContainerCreateCreatedBody{ID: "abcde"}, nil
131 }
132
133 func (t *TestDockerClient) ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error {
134         if t.finish == 3 {
135                 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\\\"\""`)
136         }
137         if t.finish == 4 {
138                 return errors.New(`panic: standard_init_linux.go:175: exec user process caused "no such file or directory"`)
139         }
140         if t.finish == 5 {
141                 return errors.New(`Error response from daemon: Cannot start container 41f26cbc43bcc1280f4323efb1830a394ba8660c9d1c2b564ba42bf7f7694845: [8] System error: no such file or directory`)
142         }
143         if t.finish == 6 {
144                 return errors.New(`Error response from daemon: Cannot start container 58099cd76c834f3dc2a4fb76c8028f049ae6d4fdf0ec373e1f2cfea030670c2d: [8] System error: exec: "foobar": executable file not found in $PATH`)
145         }
146
147         if container == "abcde" {
148                 // t.fn gets executed in ContainerWait
149                 return nil
150         } else {
151                 return errors.New("Invalid container id")
152         }
153 }
154
155 func (t *TestDockerClient) ContainerStop(ctx context.Context, container string, timeout *time.Duration) error {
156         t.stop <- true
157         return nil
158 }
159
160 func (t *TestDockerClient) ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error) {
161         body := make(chan dockercontainer.ContainerWaitOKBody)
162         err := make(chan error)
163         go func() {
164                 t.fn(t)
165                 body <- dockercontainer.ContainerWaitOKBody{StatusCode: int64(t.finish)}
166                 close(body)
167                 close(err)
168         }()
169         return body, err
170 }
171
172 func (t *TestDockerClient) ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error) {
173         if t.finish == 2 {
174                 return dockertypes.ImageInspect{}, nil, fmt.Errorf("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?")
175         }
176
177         if t.imageLoaded == image {
178                 return dockertypes.ImageInspect{}, nil, nil
179         } else {
180                 return dockertypes.ImageInspect{}, nil, errors.New("")
181         }
182 }
183
184 func (t *TestDockerClient) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error) {
185         if t.finish == 2 {
186                 return dockertypes.ImageLoadResponse{}, fmt.Errorf("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?")
187         }
188         _, err := io.Copy(ioutil.Discard, input)
189         if err != nil {
190                 return dockertypes.ImageLoadResponse{}, err
191         } else {
192                 t.imageLoaded = hwImageId
193                 return dockertypes.ImageLoadResponse{Body: ioutil.NopCloser(input)}, nil
194         }
195 }
196
197 func (*TestDockerClient) ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {
198         return nil, nil
199 }
200
201 func (client *ArvTestClient) Create(resourceType string,
202         parameters arvadosclient.Dict,
203         output interface{}) error {
204
205         client.Mutex.Lock()
206         defer client.Mutex.Unlock()
207
208         client.Calls++
209         client.Content = append(client.Content, parameters)
210
211         if resourceType == "logs" {
212                 et := parameters["log"].(arvadosclient.Dict)["event_type"].(string)
213                 if client.Logs == nil {
214                         client.Logs = make(map[string]*bytes.Buffer)
215                 }
216                 if client.Logs[et] == nil {
217                         client.Logs[et] = &bytes.Buffer{}
218                 }
219                 client.Logs[et].Write([]byte(parameters["log"].(arvadosclient.Dict)["properties"].(map[string]string)["text"]))
220         }
221
222         if resourceType == "collections" && output != nil {
223                 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
224                 outmap := output.(*arvados.Collection)
225                 outmap.PortableDataHash = fmt.Sprintf("%x+%d", md5.Sum([]byte(mt)), len(mt))
226         }
227
228         return nil
229 }
230
231 func (client *ArvTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
232         switch {
233         case method == "GET" && resourceType == "containers" && action == "auth":
234                 return json.Unmarshal([]byte(`{
235                         "kind": "arvados#api_client_authorization",
236                         "uuid": "`+fakeAuthUUID+`",
237                         "api_token": "`+fakeAuthToken+`"
238                         }`), output)
239         default:
240                 return fmt.Errorf("Not found")
241         }
242 }
243
244 func (client *ArvTestClient) CallRaw(method, resourceType, uuid, action string,
245         parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
246         var j []byte
247         if method == "GET" && resourceType == "nodes" && uuid == "" && action == "" {
248                 j = []byte(`{
249                         "kind": "arvados#nodeList",
250                         "items": [{
251                                 "uuid": "zzzzz-7ekkf-2z3mc76g2q73aio",
252                                 "hostname": "compute2",
253                                 "properties": {"total_cpu_cores": 16}
254                         }]}`)
255         } else if method == "GET" && resourceType == "containers" && action == "" && !client.callraw {
256                 if uuid == "" {
257                         j, err = json.Marshal(map[string]interface{}{
258                                 "items": []interface{}{client.Container},
259                                 "kind":  "arvados#nodeList",
260                         })
261                 } else {
262                         j, err = json.Marshal(client.Container)
263                 }
264         } else {
265                 j = []byte(`{
266                         "command": ["sleep", "1"],
267                         "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
268                         "cwd": ".",
269                         "environment": {},
270                         "mounts": {"/tmp": {"kind": "tmp"}, "/json": {"kind": "json", "content": {"number": 123456789123456789}}},
271                         "output_path": "/tmp",
272                         "priority": 1,
273                         "runtime_constraints": {}
274                 }`)
275         }
276         return ioutil.NopCloser(bytes.NewReader(j)), err
277 }
278
279 func (client *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
280         if resourceType == "collections" {
281                 if uuid == hwPDH {
282                         output.(*arvados.Collection).ManifestText = hwManifest
283                 } else if uuid == otherPDH {
284                         output.(*arvados.Collection).ManifestText = otherManifest
285                 } else if uuid == normalizedWithSubdirsPDH {
286                         output.(*arvados.Collection).ManifestText = normalizedManifestWithSubdirs
287                 } else if uuid == denormalizedWithSubdirsPDH {
288                         output.(*arvados.Collection).ManifestText = denormalizedManifestWithSubdirs
289                 }
290         }
291         if resourceType == "containers" {
292                 (*output.(*arvados.Container)) = client.Container
293         }
294         return nil
295 }
296
297 func (client *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
298         client.Mutex.Lock()
299         defer client.Mutex.Unlock()
300         client.Calls++
301         client.Content = append(client.Content, parameters)
302         if resourceType == "containers" {
303                 if parameters["container"].(arvadosclient.Dict)["state"] == "Running" {
304                         client.WasSetRunning = true
305                 }
306         }
307         return nil
308 }
309
310 var discoveryMap = map[string]interface{}{
311         "defaultTrashLifetime":               float64(1209600),
312         "crunchLimitLogBytesPerJob":          float64(67108864),
313         "crunchLogThrottleBytes":             float64(65536),
314         "crunchLogThrottlePeriod":            float64(60),
315         "crunchLogThrottleLines":             float64(1024),
316         "crunchLogPartialLineThrottlePeriod": float64(5),
317         "crunchLogBytesPerEvent":             float64(4096),
318         "crunchLogSecondsBetweenEvents":      float64(1),
319 }
320
321 func (client *ArvTestClient) Discovery(key string) (interface{}, error) {
322         return discoveryMap[key], nil
323 }
324
325 // CalledWith returns the parameters from the first API call whose
326 // parameters match jpath/string. E.g., CalledWith(c, "foo.bar",
327 // "baz") returns parameters with parameters["foo"]["bar"]=="baz". If
328 // no call matches, it returns nil.
329 func (client *ArvTestClient) CalledWith(jpath string, expect interface{}) arvadosclient.Dict {
330 call:
331         for _, content := range client.Content {
332                 var v interface{} = content
333                 for _, k := range strings.Split(jpath, ".") {
334                         if dict, ok := v.(arvadosclient.Dict); !ok {
335                                 continue call
336                         } else {
337                                 v = dict[k]
338                         }
339                 }
340                 if v == expect {
341                         return content
342                 }
343         }
344         return nil
345 }
346
347 func (client *KeepTestClient) PutHB(hash string, buf []byte) (string, int, error) {
348         client.Content = buf
349         return fmt.Sprintf("%s+%d", hash, len(buf)), len(buf), nil
350 }
351
352 func (*KeepTestClient) ClearBlockCache() {
353 }
354
355 type FileWrapper struct {
356         io.ReadCloser
357         len int64
358 }
359
360 func (fw FileWrapper) Readdir(n int) ([]os.FileInfo, error) {
361         return nil, errors.New("not implemented")
362 }
363
364 func (fw FileWrapper) Seek(int64, int) (int64, error) {
365         return 0, errors.New("not implemented")
366 }
367
368 func (fw FileWrapper) Size() int64 {
369         return fw.len
370 }
371
372 func (fw FileWrapper) Stat() (os.FileInfo, error) {
373         return nil, errors.New("not implemented")
374 }
375
376 func (fw FileWrapper) Truncate(int64) error {
377         return errors.New("not implemented")
378 }
379
380 func (fw FileWrapper) Write([]byte) (int, error) {
381         return 0, errors.New("not implemented")
382 }
383
384 func (client *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
385         if filename == hwImageId+".tar" {
386                 rdr := ioutil.NopCloser(&bytes.Buffer{})
387                 client.Called = true
388                 return FileWrapper{rdr, 1321984}, nil
389         } else if filename == "/file1_in_main.txt" {
390                 rdr := ioutil.NopCloser(strings.NewReader("foo"))
391                 client.Called = true
392                 return FileWrapper{rdr, 3}, nil
393         }
394         return nil, nil
395 }
396
397 func (s *TestSuite) TestLoadImage(c *C) {
398         kc := &KeepTestClient{}
399         docker := NewTestDockerClient(0)
400         cr := NewContainerRunner(&ArvTestClient{}, kc, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
401
402         _, err := cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
403
404         _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
405         c.Check(err, NotNil)
406
407         cr.Container.ContainerImage = hwPDH
408
409         // (1) Test loading image from keep
410         c.Check(kc.Called, Equals, false)
411         c.Check(cr.ContainerConfig.Image, Equals, "")
412
413         err = cr.LoadImage()
414
415         c.Check(err, IsNil)
416         defer func() {
417                 cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
418         }()
419
420         c.Check(kc.Called, Equals, true)
421         c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
422
423         _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
424         c.Check(err, IsNil)
425
426         // (2) Test using image that's already loaded
427         kc.Called = false
428         cr.ContainerConfig.Image = ""
429
430         err = cr.LoadImage()
431         c.Check(err, IsNil)
432         c.Check(kc.Called, Equals, false)
433         c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
434
435 }
436
437 type ArvErrorTestClient struct{}
438
439 func (ArvErrorTestClient) Create(resourceType string,
440         parameters arvadosclient.Dict,
441         output interface{}) error {
442         return nil
443 }
444
445 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
446         return errors.New("ArvError")
447 }
448
449 func (ArvErrorTestClient) CallRaw(method, resourceType, uuid, action string,
450         parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
451         return nil, errors.New("ArvError")
452 }
453
454 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
455         return errors.New("ArvError")
456 }
457
458 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
459         return nil
460 }
461
462 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
463         return discoveryMap[key], nil
464 }
465
466 type KeepErrorTestClient struct{}
467
468 func (KeepErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
469         return "", 0, errors.New("KeepError")
470 }
471
472 func (KeepErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
473         return nil, errors.New("KeepError")
474 }
475
476 func (KeepErrorTestClient) ClearBlockCache() {
477 }
478
479 type KeepReadErrorTestClient struct{}
480
481 func (KeepReadErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
482         return "", 0, nil
483 }
484
485 func (KeepReadErrorTestClient) ClearBlockCache() {
486 }
487
488 type ErrorReader struct {
489         FileWrapper
490 }
491
492 func (ErrorReader) Read(p []byte) (n int, err error) {
493         return 0, errors.New("ErrorReader")
494 }
495
496 func (ErrorReader) Seek(int64, int) (int64, error) {
497         return 0, errors.New("ErrorReader")
498 }
499
500 func (KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
501         return ErrorReader{}, nil
502 }
503
504 func (s *TestSuite) TestLoadImageArvError(c *C) {
505         // (1) Arvados error
506         cr := NewContainerRunner(ArvErrorTestClient{}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
507         cr.Container.ContainerImage = hwPDH
508
509         err := cr.LoadImage()
510         c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
511 }
512
513 func (s *TestSuite) TestLoadImageKeepError(c *C) {
514         // (2) Keep error
515         docker := NewTestDockerClient(0)
516         cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
517         cr.Container.ContainerImage = hwPDH
518
519         err := cr.LoadImage()
520         c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
521 }
522
523 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
524         // (3) Collection doesn't contain image
525         cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
526         cr.Container.ContainerImage = otherPDH
527
528         err := cr.LoadImage()
529         c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
530 }
531
532 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
533         // (4) Collection doesn't contain image
534         docker := NewTestDockerClient(0)
535         cr := NewContainerRunner(&ArvTestClient{}, KeepReadErrorTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
536         cr.Container.ContainerImage = hwPDH
537
538         err := cr.LoadImage()
539         c.Check(err, NotNil)
540 }
541
542 type ClosableBuffer struct {
543         bytes.Buffer
544 }
545
546 func (*ClosableBuffer) Close() error {
547         return nil
548 }
549
550 type TestLogs struct {
551         Stdout ClosableBuffer
552         Stderr ClosableBuffer
553 }
554
555 func (tl *TestLogs) NewTestLoggingWriter(logstr string) io.WriteCloser {
556         if logstr == "stdout" {
557                 return &tl.Stdout
558         }
559         if logstr == "stderr" {
560                 return &tl.Stderr
561         }
562         return nil
563 }
564
565 func dockerLog(fd byte, msg string) []byte {
566         by := []byte(msg)
567         header := make([]byte, 8+len(by))
568         header[0] = fd
569         header[7] = byte(len(by))
570         copy(header[8:], by)
571         return header
572 }
573
574 func (s *TestSuite) TestRunContainer(c *C) {
575         docker := NewTestDockerClient(0)
576         docker.fn = func(t *TestDockerClient) {
577                 t.logWriter.Write(dockerLog(1, "Hello world\n"))
578                 t.logWriter.Close()
579         }
580         cr := NewContainerRunner(&ArvTestClient{}, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
581
582         var logs TestLogs
583         cr.NewLogWriter = logs.NewTestLoggingWriter
584         cr.Container.ContainerImage = hwPDH
585         cr.Container.Command = []string{"./hw"}
586         err := cr.LoadImage()
587         c.Check(err, IsNil)
588
589         err = cr.CreateContainer()
590         c.Check(err, IsNil)
591
592         err = cr.StartContainer()
593         c.Check(err, IsNil)
594
595         err = cr.WaitFinish()
596         c.Check(err, IsNil)
597
598         c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
599         c.Check(logs.Stderr.String(), Equals, "")
600 }
601
602 func (s *TestSuite) TestCommitLogs(c *C) {
603         api := &ArvTestClient{}
604         kc := &KeepTestClient{}
605         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
606         cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
607
608         cr.CrunchLog.Print("Hello world!")
609         cr.CrunchLog.Print("Goodbye")
610         cr.finalState = "Complete"
611
612         err := cr.CommitLogs()
613         c.Check(err, IsNil)
614
615         c.Check(api.Calls, Equals, 2)
616         c.Check(api.Content[1]["ensure_unique_name"], Equals, true)
617         c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
618         c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
619         c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
620 }
621
622 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
623         api := &ArvTestClient{}
624         kc := &KeepTestClient{}
625         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
626
627         err := cr.UpdateContainerRunning()
628         c.Check(err, IsNil)
629
630         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
631 }
632
633 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
634         api := &ArvTestClient{}
635         kc := &KeepTestClient{}
636         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
637
638         cr.LogsPDH = new(string)
639         *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
640
641         cr.ExitCode = new(int)
642         *cr.ExitCode = 42
643         cr.finalState = "Complete"
644
645         err := cr.UpdateContainerFinal()
646         c.Check(err, IsNil)
647
648         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
649         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
650         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
651 }
652
653 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
654         api := &ArvTestClient{}
655         kc := &KeepTestClient{}
656         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
657         cr.cCancelled = true
658         cr.finalState = "Cancelled"
659
660         err := cr.UpdateContainerFinal()
661         c.Check(err, IsNil)
662
663         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
664         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
665         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
666 }
667
668 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
669 // dress rehearsal of the Run() function, starting from a JSON container record.
670 func FullRunHelper(c *C, record string, extraMounts []string, exitCode int, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, realTemp string) {
671         rec := arvados.Container{}
672         err := json.Unmarshal([]byte(record), &rec)
673         c.Check(err, IsNil)
674
675         docker := NewTestDockerClient(exitCode)
676         docker.fn = fn
677         docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
678
679         api = &ArvTestClient{Container: rec}
680         docker.api = api
681         cr = NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
682         cr.statInterval = 100 * time.Millisecond
683         am := &ArvMountCmdLine{}
684         cr.RunArvMount = am.ArvMountTest
685
686         realTemp, err = ioutil.TempDir("", "crunchrun_test1-")
687         c.Assert(err, IsNil)
688         defer os.RemoveAll(realTemp)
689
690         docker.realTemp = realTemp
691
692         tempcount := 0
693         cr.MkTempDir = func(_ string, prefix string) (string, error) {
694                 tempcount++
695                 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, tempcount)
696                 err := os.Mkdir(d, os.ModePerm)
697                 if err != nil && strings.Contains(err.Error(), ": file exists") {
698                         // Test case must have pre-populated the tempdir
699                         err = nil
700                 }
701                 return d, err
702         }
703
704         if extraMounts != nil && len(extraMounts) > 0 {
705                 err := cr.SetupArvMountPoint("keep")
706                 c.Check(err, IsNil)
707
708                 for _, m := range extraMounts {
709                         os.MkdirAll(cr.ArvMountPoint+"/by_id/"+m, os.ModePerm)
710                 }
711         }
712
713         err = cr.Run()
714         if api.CalledWith("container.state", "Complete") != nil {
715                 c.Check(err, IsNil)
716         }
717         if exitCode != 2 {
718                 c.Check(api.WasSetRunning, Equals, true)
719                 c.Check(api.Content[api.Calls-2]["container"].(arvadosclient.Dict)["log"], NotNil)
720         }
721
722         if err != nil {
723                 for k, v := range api.Logs {
724                         c.Log(k)
725                         c.Log(v.String())
726                 }
727         }
728
729         return
730 }
731
732 func (s *TestSuite) TestFullRunHello(c *C) {
733         api, _, _ := FullRunHelper(c, `{
734     "command": ["echo", "hello world"],
735     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
736     "cwd": ".",
737     "environment": {},
738     "mounts": {"/tmp": {"kind": "tmp"} },
739     "output_path": "/tmp",
740     "priority": 1,
741     "runtime_constraints": {}
742 }`, nil, 0, func(t *TestDockerClient) {
743                 t.logWriter.Write(dockerLog(1, "hello world\n"))
744                 t.logWriter.Close()
745         })
746
747         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
748         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
749         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
750
751 }
752
753 func (s *TestSuite) TestCrunchstat(c *C) {
754         api, _, _ := FullRunHelper(c, `{
755                 "command": ["sleep", "1"],
756                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
757                 "cwd": ".",
758                 "environment": {},
759                 "mounts": {"/tmp": {"kind": "tmp"} },
760                 "output_path": "/tmp",
761                 "priority": 1,
762                 "runtime_constraints": {}
763         }`, nil, 0, func(t *TestDockerClient) {
764                 time.Sleep(time.Second)
765                 t.logWriter.Close()
766         })
767
768         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
769         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
770
771         // We didn't actually start a container, so crunchstat didn't
772         // find accounting files and therefore didn't log any stats.
773         // It should have logged a "can't find accounting files"
774         // message after one poll interval, though, so we can confirm
775         // it's alive:
776         c.Assert(api.Logs["crunchstat"], NotNil)
777         c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
778
779         // The "files never appeared" log assures us that we called
780         // (*crunchstat.Reporter)Stop(), and that we set it up with
781         // the correct container ID "abcde":
782         c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files never appeared for abcde\n`)
783 }
784
785 func (s *TestSuite) TestNodeInfoLog(c *C) {
786         os.Setenv("SLURMD_NODENAME", "compute2")
787         api, _, _ := FullRunHelper(c, `{
788                 "command": ["sleep", "1"],
789                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
790                 "cwd": ".",
791                 "environment": {},
792                 "mounts": {"/tmp": {"kind": "tmp"} },
793                 "output_path": "/tmp",
794                 "priority": 1,
795                 "runtime_constraints": {}
796         }`, nil, 0,
797                 func(t *TestDockerClient) {
798                         time.Sleep(time.Second)
799                         t.logWriter.Close()
800                 })
801
802         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
803         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
804
805         c.Assert(api.Logs["node"], NotNil)
806         json := api.Logs["node"].String()
807         c.Check(json, Matches, `(?ms).*"uuid": *"zzzzz-7ekkf-2z3mc76g2q73aio".*`)
808         c.Check(json, Matches, `(?ms).*"total_cpu_cores": *16.*`)
809         c.Check(json, Not(Matches), `(?ms).*"info":.*`)
810
811         c.Assert(api.Logs["node-info"], NotNil)
812         json = api.Logs["node-info"].String()
813         c.Check(json, Matches, `(?ms).*Host Information.*`)
814         c.Check(json, Matches, `(?ms).*CPU Information.*`)
815         c.Check(json, Matches, `(?ms).*Memory Information.*`)
816         c.Check(json, Matches, `(?ms).*Disk Space.*`)
817         c.Check(json, Matches, `(?ms).*Disk INodes.*`)
818 }
819
820 func (s *TestSuite) TestContainerRecordLog(c *C) {
821         api, _, _ := FullRunHelper(c, `{
822                 "command": ["sleep", "1"],
823                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
824                 "cwd": ".",
825                 "environment": {},
826                 "mounts": {"/tmp": {"kind": "tmp"} },
827                 "output_path": "/tmp",
828                 "priority": 1,
829                 "runtime_constraints": {}
830         }`, nil, 0,
831                 func(t *TestDockerClient) {
832                         time.Sleep(time.Second)
833                         t.logWriter.Close()
834                 })
835
836         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
837         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
838
839         c.Assert(api.Logs["container"], NotNil)
840         c.Check(api.Logs["container"].String(), Matches, `(?ms).*container_image.*`)
841 }
842
843 func (s *TestSuite) TestFullRunStderr(c *C) {
844         api, _, _ := FullRunHelper(c, `{
845     "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
846     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
847     "cwd": ".",
848     "environment": {},
849     "mounts": {"/tmp": {"kind": "tmp"} },
850     "output_path": "/tmp",
851     "priority": 1,
852     "runtime_constraints": {}
853 }`, nil, 1, func(t *TestDockerClient) {
854                 t.logWriter.Write(dockerLog(1, "hello\n"))
855                 t.logWriter.Write(dockerLog(2, "world\n"))
856                 t.logWriter.Close()
857         })
858
859         final := api.CalledWith("container.state", "Complete")
860         c.Assert(final, NotNil)
861         c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
862         c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
863
864         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
865         c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
866 }
867
868 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
869         api, _, _ := FullRunHelper(c, `{
870     "command": ["pwd"],
871     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
872     "cwd": ".",
873     "environment": {},
874     "mounts": {"/tmp": {"kind": "tmp"} },
875     "output_path": "/tmp",
876     "priority": 1,
877     "runtime_constraints": {}
878 }`, nil, 0, func(t *TestDockerClient) {
879                 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
880                 t.logWriter.Close()
881         })
882
883         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
884         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
885         c.Log(api.Logs["stdout"])
886         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
887 }
888
889 func (s *TestSuite) TestFullRunSetCwd(c *C) {
890         api, _, _ := FullRunHelper(c, `{
891     "command": ["pwd"],
892     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
893     "cwd": "/bin",
894     "environment": {},
895     "mounts": {"/tmp": {"kind": "tmp"} },
896     "output_path": "/tmp",
897     "priority": 1,
898     "runtime_constraints": {}
899 }`, nil, 0, func(t *TestDockerClient) {
900                 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
901                 t.logWriter.Close()
902         })
903
904         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
905         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
906         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
907 }
908
909 func (s *TestSuite) TestStopOnSignal(c *C) {
910         s.testStopContainer(c, func(cr *ContainerRunner) {
911                 go func() {
912                         for !cr.cStarted {
913                                 time.Sleep(time.Millisecond)
914                         }
915                         cr.SigChan <- syscall.SIGINT
916                 }()
917         })
918 }
919
920 func (s *TestSuite) TestStopOnArvMountDeath(c *C) {
921         s.testStopContainer(c, func(cr *ContainerRunner) {
922                 cr.ArvMountExit = make(chan error)
923                 go func() {
924                         cr.ArvMountExit <- exec.Command("true").Run()
925                         close(cr.ArvMountExit)
926                 }()
927         })
928 }
929
930 func (s *TestSuite) testStopContainer(c *C, setup func(cr *ContainerRunner)) {
931         record := `{
932     "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
933     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
934     "cwd": ".",
935     "environment": {},
936     "mounts": {"/tmp": {"kind": "tmp"} },
937     "output_path": "/tmp",
938     "priority": 1,
939     "runtime_constraints": {}
940 }`
941
942         rec := arvados.Container{}
943         err := json.Unmarshal([]byte(record), &rec)
944         c.Check(err, IsNil)
945
946         docker := NewTestDockerClient(0)
947         docker.fn = func(t *TestDockerClient) {
948                 <-t.stop
949                 t.logWriter.Write(dockerLog(1, "foo\n"))
950                 t.logWriter.Close()
951         }
952         docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
953
954         api := &ArvTestClient{Container: rec}
955         cr := NewContainerRunner(api, &KeepTestClient{}, 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, _, _ := 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, _, _ := 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 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         docker := NewTestDockerClient(0)
1379         docker.fn = fn
1380         docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
1381
1382         api = &ArvTestClient{Container: rec}
1383         cr = NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1384         am := &ArvMountCmdLine{}
1385         cr.RunArvMount = am.ArvMountTest
1386
1387         err = cr.Run()
1388         return
1389 }
1390
1391 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1392         _, _, err := StdoutErrorRunHelper(c, `{
1393     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1394     "output_path": "/tmp"
1395 }`, func(t *TestDockerClient) {})
1396
1397         c.Check(err, NotNil)
1398         c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
1399 }
1400
1401 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1402         _, _, err := StdoutErrorRunHelper(c, `{
1403     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1404     "output_path": "/tmp"
1405 }`, func(t *TestDockerClient) {})
1406
1407         c.Check(err, NotNil)
1408         c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'tmp' for stdout"), Equals, true)
1409 }
1410
1411 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1412         _, _, err := StdoutErrorRunHelper(c, `{
1413     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1414     "output_path": "/tmp"
1415 }`, func(t *TestDockerClient) {})
1416
1417         c.Check(err, NotNil)
1418         c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'collection' for stdout"), Equals, true)
1419 }
1420
1421 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1422         os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1423         defer os.Unsetenv("ARVADOS_API_HOST")
1424         api, _, _ := FullRunHelper(c, `{
1425     "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1426     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1427     "cwd": "/bin",
1428     "environment": {},
1429     "mounts": {"/tmp": {"kind": "tmp"} },
1430     "output_path": "/tmp",
1431     "priority": 1,
1432     "runtime_constraints": {"API": true}
1433 }`, nil, 0, func(t *TestDockerClient) {
1434                 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
1435                 t.logWriter.Close()
1436         })
1437
1438         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1439         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1440         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "test.arvados.org\n"), Equals, true)
1441         c.Check(api.CalledWith("container.output", "d41d8cd98f00b204e9800998ecf8427e+0"), NotNil)
1442 }
1443
1444 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1445         os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1446         defer os.Unsetenv("ARVADOS_API_HOST")
1447         api, _, _ := FullRunHelper(c, `{
1448     "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1449     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1450     "cwd": "/bin",
1451     "environment": {},
1452     "mounts": {"/tmp": {"kind": "tmp"} },
1453     "output_path": "/tmp",
1454     "priority": 1,
1455     "runtime_constraints": {"API": true}
1456 }`, nil, 0, func(t *TestDockerClient) {
1457                 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
1458                 t.logWriter.Close()
1459         })
1460
1461         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1462         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1463         c.Check(api.CalledWith("container.output", "d4ab34d3d4f8a72f5c4973051ae69fab+122"), NotNil)
1464 }
1465
1466 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1467         helperRecord := `{
1468                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1469                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1470                 "cwd": "/bin",
1471                 "environment": {"FROBIZ": "bilbo"},
1472                 "mounts": {
1473         "/tmp": {"kind": "tmp"},
1474         "/tmp/foo": {"kind": "collection",
1475                      "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1476                      "exclude_from_output": true
1477         },
1478         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1479     },
1480                 "output_path": "/tmp",
1481                 "priority": 1,
1482                 "runtime_constraints": {}
1483         }`
1484
1485         extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1486
1487         api, _, _ := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1488                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1489                 t.logWriter.Close()
1490         })
1491
1492         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1493         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1494         c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1495 }
1496
1497 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1498         helperRecord := `{
1499                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1500                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1501                 "cwd": "/bin",
1502                 "environment": {"FROBIZ": "bilbo"},
1503                 "mounts": {
1504         "/tmp": {"kind": "tmp"},
1505         "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1506         "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1507         "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1508         "/tmp/foo/baz/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1509         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1510     },
1511                 "output_path": "/tmp",
1512                 "priority": 1,
1513                 "runtime_constraints": {}
1514         }`
1515
1516         extraMounts := []string{
1517                 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1518                 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1519                 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1520         }
1521
1522         api, runner, realtemp := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1523                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1524                 t.logWriter.Close()
1525         })
1526
1527         c.Check(runner.Binds, DeepEquals, []string{realtemp + "/2:/tmp",
1528                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt:/tmp/foo/bar:ro",
1529                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt:/tmp/foo/baz/sub2file2:ro",
1530                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1:/tmp/foo/sub1:ro",
1531                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt:/tmp/foo/sub1file2:ro",
1532         })
1533
1534         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1535         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1536         for _, v := range api.Content {
1537                 if v["collection"] != nil {
1538                         c.Check(v["ensure_unique_name"], Equals, true)
1539                         collection := v["collection"].(arvadosclient.Dict)
1540                         if strings.Index(collection["name"].(string), "output") == 0 {
1541                                 manifest := collection["manifest_text"].(string)
1542
1543                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1544 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 9:18:bar 9:18:sub1file2
1545 ./foo/baz 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2
1546 ./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1547 ./foo/sub1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1548 `)
1549                         }
1550                 }
1551         }
1552 }
1553
1554 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
1555         helperRecord := `{
1556                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1557                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1558                 "cwd": "/bin",
1559                 "environment": {"FROBIZ": "bilbo"},
1560                 "mounts": {
1561         "/tmp": {"kind": "tmp"},
1562         "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt"},
1563         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1564     },
1565                 "output_path": "/tmp",
1566                 "priority": 1,
1567                 "runtime_constraints": {}
1568         }`
1569
1570         extraMounts := []string{
1571                 "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1572         }
1573
1574         api, _, _ := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1575                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1576                 t.logWriter.Close()
1577         })
1578
1579         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1580         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1581         for _, v := range api.Content {
1582                 if v["collection"] != nil {
1583                         collection := v["collection"].(arvadosclient.Dict)
1584                         if strings.Index(collection["name"].(string), "output") == 0 {
1585                                 manifest := collection["manifest_text"].(string)
1586
1587                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1588 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 10:17:bar
1589 `)
1590                         }
1591                 }
1592         }
1593 }
1594
1595 func (s *TestSuite) TestOutputSymlinkToInput(c *C) {
1596         helperRecord := `{
1597                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1598                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1599                 "cwd": "/bin",
1600                 "environment": {"FROBIZ": "bilbo"},
1601                 "mounts": {
1602         "/tmp": {"kind": "tmp"},
1603         "/keep/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path": "/subdir1/file2_in_subdir1.txt"},
1604         "/keep/foo2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367"}
1605     },
1606                 "output_path": "/tmp",
1607                 "priority": 1,
1608                 "runtime_constraints": {}
1609         }`
1610
1611         extraMounts := []string{
1612                 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1613         }
1614
1615         api, _, _ := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1616                 os.Symlink("/keep/foo/sub1file2", t.realTemp+"/2/baz")
1617                 os.Symlink("/keep/foo2/subdir1/file2_in_subdir1.txt", t.realTemp+"/2/baz2")
1618                 os.Symlink("/keep/foo2/subdir1", t.realTemp+"/2/baz3")
1619                 os.Mkdir(t.realTemp+"/2/baz4", 0700)
1620                 os.Symlink("/keep/foo2/subdir1/file2_in_subdir1.txt", t.realTemp+"/2/baz4/baz5")
1621                 t.logWriter.Close()
1622         })
1623
1624         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1625         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1626         for _, v := range api.Content {
1627                 if v["collection"] != nil {
1628                         collection := v["collection"].(arvadosclient.Dict)
1629                         if strings.Index(collection["name"].(string), "output") == 0 {
1630                                 manifest := collection["manifest_text"].(string)
1631                                 c.Check(manifest, Equals, `. 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:baz 9:18:baz2
1632 ./baz3 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1633 ./baz3/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1634 ./baz4 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:baz5
1635 `)
1636                         }
1637                 }
1638         }
1639 }
1640
1641 func (s *TestSuite) TestOutputError(c *C) {
1642         helperRecord := `{
1643                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1644                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1645                 "cwd": "/bin",
1646                 "environment": {"FROBIZ": "bilbo"},
1647                 "mounts": {
1648         "/tmp": {"kind": "tmp"}
1649     },
1650                 "output_path": "/tmp",
1651                 "priority": 1,
1652                 "runtime_constraints": {}
1653         }`
1654
1655         extraMounts := []string{}
1656
1657         api, _, _ := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1658                 os.Symlink("/etc/hosts", t.realTemp+"/2/baz")
1659                 t.logWriter.Close()
1660         })
1661
1662         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1663 }
1664
1665 func (s *TestSuite) TestOutputSymlinkToOutput(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     },
1674                 "output_path": "/tmp",
1675                 "priority": 1,
1676                 "runtime_constraints": {}
1677         }`
1678
1679         extraMounts := []string{}
1680
1681         api, _, _ := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1682                 rf, _ := os.Create(t.realTemp + "/2/realfile")
1683                 rf.Write([]byte("foo"))
1684                 rf.Close()
1685
1686                 os.Mkdir(t.realTemp+"/2/realdir", 0700)
1687                 rf, _ = os.Create(t.realTemp + "/2/realdir/subfile")
1688                 rf.Write([]byte("bar"))
1689                 rf.Close()
1690
1691                 os.Symlink("/tmp/realfile", t.realTemp+"/2/file1")
1692                 os.Symlink("realfile", t.realTemp+"/2/file2")
1693                 os.Symlink("/tmp/file1", t.realTemp+"/2/file3")
1694                 os.Symlink("file2", t.realTemp+"/2/file4")
1695                 os.Symlink("realdir", t.realTemp+"/2/dir1")
1696                 os.Symlink("/tmp/realdir", t.realTemp+"/2/dir2")
1697                 t.logWriter.Close()
1698         })
1699
1700         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1701         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1702         for _, v := range api.Content {
1703                 if v["collection"] != nil {
1704                         collection := v["collection"].(arvadosclient.Dict)
1705                         if strings.Index(collection["name"].(string), "output") == 0 {
1706                                 manifest := collection["manifest_text"].(string)
1707                                 c.Check(manifest, Equals,
1708                                         `. 7a2c86e102dcc231bd232aad99686dfa+15 0:3:file1 3:3:file2 6:3:file3 9:3:file4 12:3:realfile
1709 ./dir1 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1710 ./dir2 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1711 ./realdir 37b51d194a7513e45b56f6524f2d51f2+3 0:3:subfile
1712 `)
1713                         }
1714                 }
1715         }
1716 }
1717
1718 func (s *TestSuite) TestStdinCollectionMountPoint(c *C) {
1719         helperRecord := `{
1720                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1721                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1722                 "cwd": "/bin",
1723                 "environment": {"FROBIZ": "bilbo"},
1724                 "mounts": {
1725         "/tmp": {"kind": "tmp"},
1726         "stdin": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/file1_in_main.txt"},
1727         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1728     },
1729                 "output_path": "/tmp",
1730                 "priority": 1,
1731                 "runtime_constraints": {}
1732         }`
1733
1734         extraMounts := []string{
1735                 "b0def87f80dd594d4675809e83bd4f15+367/file1_in_main.txt",
1736         }
1737
1738         api, _, _ := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1739                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1740                 t.logWriter.Close()
1741         })
1742
1743         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1744         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1745         for _, v := range api.Content {
1746                 if v["collection"] != nil {
1747                         collection := v["collection"].(arvadosclient.Dict)
1748                         if strings.Index(collection["name"].(string), "output") == 0 {
1749                                 manifest := collection["manifest_text"].(string)
1750                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1751 `)
1752                         }
1753                 }
1754         }
1755 }
1756
1757 func (s *TestSuite) TestStdinJsonMountPoint(c *C) {
1758         helperRecord := `{
1759                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1760                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1761                 "cwd": "/bin",
1762                 "environment": {"FROBIZ": "bilbo"},
1763                 "mounts": {
1764         "/tmp": {"kind": "tmp"},
1765         "stdin": {"kind": "json", "content": "foo"},
1766         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1767     },
1768                 "output_path": "/tmp",
1769                 "priority": 1,
1770                 "runtime_constraints": {}
1771         }`
1772
1773         api, _, _ := FullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1774                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1775                 t.logWriter.Close()
1776         })
1777
1778         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1779         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1780         for _, v := range api.Content {
1781                 if v["collection"] != nil {
1782                         collection := v["collection"].(arvadosclient.Dict)
1783                         if strings.Index(collection["name"].(string), "output") == 0 {
1784                                 manifest := collection["manifest_text"].(string)
1785                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1786 `)
1787                         }
1788                 }
1789         }
1790 }
1791
1792 func (s *TestSuite) TestStderrMount(c *C) {
1793         api, _, _ := FullRunHelper(c, `{
1794     "command": ["/bin/sh", "-c", "echo hello;exit 1"],
1795     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1796     "cwd": ".",
1797     "environment": {},
1798     "mounts": {"/tmp": {"kind": "tmp"},
1799                "stdout": {"kind": "file", "path": "/tmp/a/out.txt"},
1800                "stderr": {"kind": "file", "path": "/tmp/b/err.txt"}},
1801     "output_path": "/tmp",
1802     "priority": 1,
1803     "runtime_constraints": {}
1804 }`, nil, 1, func(t *TestDockerClient) {
1805                 t.logWriter.Write(dockerLog(1, "hello\n"))
1806                 t.logWriter.Write(dockerLog(2, "oops\n"))
1807                 t.logWriter.Close()
1808         })
1809
1810         final := api.CalledWith("container.state", "Complete")
1811         c.Assert(final, NotNil)
1812         c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1813         c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1814
1815         c.Check(api.CalledWith("collection.manifest_text", "./a b1946ac92492d2347c6235b4d2611184+6 0:6:out.txt\n./b 38af5c54926b620264ab1501150cf189+5 0:5:err.txt\n"), NotNil)
1816 }
1817
1818 func (s *TestSuite) TestNumberRoundTrip(c *C) {
1819         cr := NewContainerRunner(&ArvTestClient{callraw: true}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1820         cr.fetchContainerRecord()
1821
1822         jsondata, err := json.Marshal(cr.Container.Mounts["/json"].Content)
1823
1824         c.Check(err, IsNil)
1825         c.Check(string(jsondata), Equals, `{"number":123456789123456789}`)
1826 }
1827
1828 func (s *TestSuite) TestEvalSymlinks(c *C) {
1829         cr := NewContainerRunner(&ArvTestClient{callraw: true}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1830
1831         realTemp, err := ioutil.TempDir("", "crunchrun_test-")
1832         c.Assert(err, IsNil)
1833         defer os.RemoveAll(realTemp)
1834
1835         cr.HostOutputDir = realTemp
1836
1837         // Absolute path outside output dir
1838         os.Symlink("/etc/passwd", realTemp+"/p1")
1839
1840         // Relative outside output dir
1841         os.Symlink("../zip", realTemp+"/p2")
1842
1843         // Circular references
1844         os.Symlink("p4", realTemp+"/p3")
1845         os.Symlink("p5", realTemp+"/p4")
1846         os.Symlink("p3", realTemp+"/p5")
1847
1848         // Target doesn't exist
1849         os.Symlink("p99", realTemp+"/p6")
1850
1851         for _, v := range []string{"p1", "p2", "p3", "p4", "p5"} {
1852                 info, err := os.Lstat(realTemp + "/" + v)
1853                 _, _, _, err = cr.derefOutputSymlink(realTemp+"/"+v, info)
1854                 c.Assert(err, NotNil)
1855         }
1856 }
1857
1858 func (s *TestSuite) TestEvalSymlinkDir(c *C) {
1859         cr := NewContainerRunner(&ArvTestClient{callraw: true}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1860
1861         realTemp, err := ioutil.TempDir("", "crunchrun_test-")
1862         c.Assert(err, IsNil)
1863         defer os.RemoveAll(realTemp)
1864
1865         cr.HostOutputDir = realTemp
1866
1867         // Absolute path outside output dir
1868         os.Symlink(".", realTemp+"/loop")
1869
1870         v := "loop"
1871         info, err := os.Lstat(realTemp + "/" + v)
1872         _, err = cr.UploadOutputFile(realTemp+"/"+v, info, err, []string{}, nil, "", "", 0)
1873         c.Assert(err, NotNil)
1874 }
1875
1876 func (s *TestSuite) TestFullBrokenDocker1(c *C) {
1877         tf, err := ioutil.TempFile("", "brokenNodeHook-")
1878         c.Assert(err, IsNil)
1879         defer os.Remove(tf.Name())
1880
1881         tf.Write([]byte(`#!/bin/sh
1882 exec echo killme
1883 `))
1884         tf.Close()
1885         os.Chmod(tf.Name(), 0700)
1886
1887         ech := tf.Name()
1888         brokenNodeHook = &ech
1889
1890         api, _, _ := FullRunHelper(c, `{
1891     "command": ["echo", "hello world"],
1892     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1893     "cwd": ".",
1894     "environment": {},
1895     "mounts": {"/tmp": {"kind": "tmp"} },
1896     "output_path": "/tmp",
1897     "priority": 1,
1898     "runtime_constraints": {}
1899 }`, nil, 2, func(t *TestDockerClient) {
1900                 t.logWriter.Write(dockerLog(1, "hello world\n"))
1901                 t.logWriter.Close()
1902         })
1903
1904         c.Check(api.CalledWith("container.state", "Queued"), NotNil)
1905         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1906         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Running broken node hook.*")
1907         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*killme.*")
1908
1909 }
1910
1911 func (s *TestSuite) TestFullBrokenDocker2(c *C) {
1912         ech := ""
1913         brokenNodeHook = &ech
1914
1915         api, _, _ := FullRunHelper(c, `{
1916     "command": ["echo", "hello world"],
1917     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1918     "cwd": ".",
1919     "environment": {},
1920     "mounts": {"/tmp": {"kind": "tmp"} },
1921     "output_path": "/tmp",
1922     "priority": 1,
1923     "runtime_constraints": {}
1924 }`, nil, 2, func(t *TestDockerClient) {
1925                 t.logWriter.Write(dockerLog(1, "hello world\n"))
1926                 t.logWriter.Close()
1927         })
1928
1929         c.Check(api.CalledWith("container.state", "Queued"), NotNil)
1930         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1931         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*No broken node hook.*")
1932 }
1933
1934 func (s *TestSuite) TestFullBrokenDocker3(c *C) {
1935         ech := ""
1936         brokenNodeHook = &ech
1937
1938         api, _, _ := FullRunHelper(c, `{
1939     "command": ["echo", "hello world"],
1940     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1941     "cwd": ".",
1942     "environment": {},
1943     "mounts": {"/tmp": {"kind": "tmp"} },
1944     "output_path": "/tmp",
1945     "priority": 1,
1946     "runtime_constraints": {}
1947 }`, nil, 3, func(t *TestDockerClient) {
1948                 t.logWriter.Write(dockerLog(1, "hello world\n"))
1949                 t.logWriter.Close()
1950         })
1951
1952         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1953         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1954 }
1955
1956 func (s *TestSuite) TestBadCommand1(c *C) {
1957         ech := ""
1958         brokenNodeHook = &ech
1959
1960         api, _, _ := FullRunHelper(c, `{
1961     "command": ["echo", "hello world"],
1962     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1963     "cwd": ".",
1964     "environment": {},
1965     "mounts": {"/tmp": {"kind": "tmp"} },
1966     "output_path": "/tmp",
1967     "priority": 1,
1968     "runtime_constraints": {}
1969 }`, nil, 4, func(t *TestDockerClient) {
1970                 t.logWriter.Write(dockerLog(1, "hello world\n"))
1971                 t.logWriter.Close()
1972         })
1973
1974         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1975         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
1976 }
1977
1978 func (s *TestSuite) TestBadCommand2(c *C) {
1979         ech := ""
1980         brokenNodeHook = &ech
1981
1982         api, _, _ := FullRunHelper(c, `{
1983     "command": ["echo", "hello world"],
1984     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1985     "cwd": ".",
1986     "environment": {},
1987     "mounts": {"/tmp": {"kind": "tmp"} },
1988     "output_path": "/tmp",
1989     "priority": 1,
1990     "runtime_constraints": {}
1991 }`, nil, 5, func(t *TestDockerClient) {
1992                 t.logWriter.Write(dockerLog(1, "hello world\n"))
1993                 t.logWriter.Close()
1994         })
1995
1996         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1997         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
1998 }
1999
2000 func (s *TestSuite) TestBadCommand3(c *C) {
2001         ech := ""
2002         brokenNodeHook = &ech
2003
2004         api, _, _ := FullRunHelper(c, `{
2005     "command": ["echo", "hello world"],
2006     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2007     "cwd": ".",
2008     "environment": {},
2009     "mounts": {"/tmp": {"kind": "tmp"} },
2010     "output_path": "/tmp",
2011     "priority": 1,
2012     "runtime_constraints": {}
2013 }`, nil, 6, func(t *TestDockerClient) {
2014                 t.logWriter.Write(dockerLog(1, "hello world\n"))
2015                 t.logWriter.Close()
2016         })
2017
2018         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2019         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2020 }