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