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