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