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