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