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