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