8465: test clean up
[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{}{"defaultTrashLifetime": float64(1209600)}
253
254 func (client *ArvTestClient) Discovery(key string) (interface{}, error) {
255         return discoveryMap[key], nil
256 }
257
258 // CalledWith returns the parameters from the first API call whose
259 // parameters match jpath/string. E.g., CalledWith(c, "foo.bar",
260 // "baz") returns parameters with parameters["foo"]["bar"]=="baz". If
261 // no call matches, it returns nil.
262 func (client *ArvTestClient) CalledWith(jpath string, expect interface{}) arvadosclient.Dict {
263 call:
264         for _, content := range client.Content {
265                 var v interface{} = content
266                 for _, k := range strings.Split(jpath, ".") {
267                         if dict, ok := v.(arvadosclient.Dict); !ok {
268                                 continue call
269                         } else {
270                                 v = dict[k]
271                         }
272                 }
273                 if v == expect {
274                         return content
275                 }
276         }
277         return nil
278 }
279
280 func (client *KeepTestClient) PutHB(hash string, buf []byte) (string, int, error) {
281         client.Content = buf
282         return fmt.Sprintf("%s+%d", hash, len(buf)), len(buf), nil
283 }
284
285 type FileWrapper struct {
286         io.ReadCloser
287         len uint64
288 }
289
290 func (fw FileWrapper) Len() uint64 {
291         return fw.len
292 }
293
294 func (fw FileWrapper) Seek(int64, int) (int64, error) {
295         return 0, errors.New("not implemented")
296 }
297
298 func (client *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.Reader, error) {
299         if filename == hwImageId+".tar" {
300                 rdr := ioutil.NopCloser(&bytes.Buffer{})
301                 client.Called = true
302                 return FileWrapper{rdr, 1321984}, nil
303         }
304         return nil, nil
305 }
306
307 func (client *KeepTestClient) CollectionFileReader(collection map[string]interface{}, filename string) (keepclient.Reader, error) {
308         if filename == "/file1_in_main.txt" {
309                 rdr := ioutil.NopCloser(strings.NewReader("foo"))
310                 client.Called = true
311                 return FileWrapper{rdr, 3}, nil
312         }
313         return nil, nil
314 }
315
316 func (s *TestSuite) TestLoadImage(c *C) {
317         kc := &KeepTestClient{}
318         docker := NewTestDockerClient(0)
319         cr := NewContainerRunner(&ArvTestClient{}, kc, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
320
321         _, err := cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
322
323         _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
324         c.Check(err, NotNil)
325
326         cr.Container.ContainerImage = hwPDH
327
328         // (1) Test loading image from keep
329         c.Check(kc.Called, Equals, false)
330         c.Check(cr.ContainerConfig.Image, Equals, "")
331
332         err = cr.LoadImage()
333
334         c.Check(err, IsNil)
335         defer func() {
336                 cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
337         }()
338
339         c.Check(kc.Called, Equals, true)
340         c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
341
342         _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
343         c.Check(err, IsNil)
344
345         // (2) Test using image that's already loaded
346         kc.Called = false
347         cr.ContainerConfig.Image = ""
348
349         err = cr.LoadImage()
350         c.Check(err, IsNil)
351         c.Check(kc.Called, Equals, false)
352         c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
353
354 }
355
356 type ArvErrorTestClient struct{}
357
358 func (ArvErrorTestClient) Create(resourceType string,
359         parameters arvadosclient.Dict,
360         output interface{}) error {
361         return nil
362 }
363
364 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
365         return errors.New("ArvError")
366 }
367
368 func (ArvErrorTestClient) CallRaw(method, resourceType, uuid, action string,
369         parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
370         return nil, errors.New("ArvError")
371 }
372
373 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
374         return errors.New("ArvError")
375 }
376
377 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
378         return nil
379 }
380
381 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
382         return discoveryMap[key], nil
383 }
384
385 type KeepErrorTestClient struct{}
386
387 func (KeepErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
388         return "", 0, errors.New("KeepError")
389 }
390
391 func (KeepErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.Reader, error) {
392         return nil, errors.New("KeepError")
393 }
394
395 func (KeepErrorTestClient) CollectionFileReader(c map[string]interface{}, f 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 (KeepReadErrorTestClient) CollectionFileReader(c map[string]interface{}, f string) (keepclient.Reader, error) {
428         return ErrorReader{}, nil
429 }
430
431 func (s *TestSuite) TestLoadImageArvError(c *C) {
432         // (1) Arvados error
433         cr := NewContainerRunner(ArvErrorTestClient{}, &KeepTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
434         cr.Container.ContainerImage = hwPDH
435
436         err := cr.LoadImage()
437         c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
438 }
439
440 func (s *TestSuite) TestLoadImageKeepError(c *C) {
441         // (2) Keep error
442         docker := NewTestDockerClient(0)
443         cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
444         cr.Container.ContainerImage = hwPDH
445
446         err := cr.LoadImage()
447         c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
448 }
449
450 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
451         // (3) Collection doesn't contain image
452         cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
453         cr.Container.ContainerImage = otherPDH
454
455         err := cr.LoadImage()
456         c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
457 }
458
459 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
460         // (4) Collection doesn't contain image
461         docker := NewTestDockerClient(0)
462         cr := NewContainerRunner(&ArvTestClient{}, KeepReadErrorTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
463         cr.Container.ContainerImage = hwPDH
464
465         err := cr.LoadImage()
466         c.Check(err, NotNil)
467 }
468
469 type ClosableBuffer struct {
470         bytes.Buffer
471 }
472
473 func (*ClosableBuffer) Close() error {
474         return nil
475 }
476
477 type TestLogs struct {
478         Stdout ClosableBuffer
479         Stderr ClosableBuffer
480 }
481
482 func (tl *TestLogs) NewTestLoggingWriter(logstr string) io.WriteCloser {
483         if logstr == "stdout" {
484                 return &tl.Stdout
485         }
486         if logstr == "stderr" {
487                 return &tl.Stderr
488         }
489         return nil
490 }
491
492 func dockerLog(fd byte, msg string) []byte {
493         by := []byte(msg)
494         header := make([]byte, 8+len(by))
495         header[0] = fd
496         header[7] = byte(len(by))
497         copy(header[8:], by)
498         return header
499 }
500
501 func (s *TestSuite) TestRunContainer(c *C) {
502         docker := NewTestDockerClient(0)
503         docker.fn = func(t *TestDockerClient) {
504                 t.logWriter.Write(dockerLog(1, "Hello world\n"))
505                 t.logWriter.Close()
506         }
507         cr := NewContainerRunner(&ArvTestClient{}, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
508
509         var logs TestLogs
510         cr.NewLogWriter = logs.NewTestLoggingWriter
511         cr.Container.ContainerImage = hwPDH
512         cr.Container.Command = []string{"./hw"}
513         err := cr.LoadImage()
514         c.Check(err, IsNil)
515
516         err = cr.CreateContainer()
517         c.Check(err, IsNil)
518
519         err = cr.StartContainer()
520         c.Check(err, IsNil)
521
522         err = cr.WaitFinish()
523         c.Check(err, IsNil)
524
525         c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
526         c.Check(logs.Stderr.String(), Equals, "")
527 }
528
529 func (s *TestSuite) TestCommitLogs(c *C) {
530         api := &ArvTestClient{}
531         kc := &KeepTestClient{}
532         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
533         cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
534
535         cr.CrunchLog.Print("Hello world!")
536         cr.CrunchLog.Print("Goodbye")
537         cr.finalState = "Complete"
538
539         err := cr.CommitLogs()
540         c.Check(err, IsNil)
541
542         c.Check(api.Calls, Equals, 2)
543         c.Check(api.Content[1]["ensure_unique_name"], Equals, true)
544         c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
545         c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
546         c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
547 }
548
549 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
550         api := &ArvTestClient{}
551         kc := &KeepTestClient{}
552         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
553
554         err := cr.UpdateContainerRunning()
555         c.Check(err, IsNil)
556
557         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
558 }
559
560 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
561         api := &ArvTestClient{}
562         kc := &KeepTestClient{}
563         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
564
565         cr.LogsPDH = new(string)
566         *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
567
568         cr.ExitCode = new(int)
569         *cr.ExitCode = 42
570         cr.finalState = "Complete"
571
572         err := cr.UpdateContainerFinal()
573         c.Check(err, IsNil)
574
575         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
576         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
577         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
578 }
579
580 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
581         api := &ArvTestClient{}
582         kc := &KeepTestClient{}
583         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
584         cr.cCancelled = true
585         cr.finalState = "Cancelled"
586
587         err := cr.UpdateContainerFinal()
588         c.Check(err, IsNil)
589
590         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
591         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
592         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
593 }
594
595 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
596 // dress rehearsal of the Run() function, starting from a JSON container record.
597 func FullRunHelper(c *C, record string, extraMounts []string, exitCode int, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, realTemp string) {
598         rec := arvados.Container{}
599         err := json.Unmarshal([]byte(record), &rec)
600         c.Check(err, IsNil)
601
602         docker := NewTestDockerClient(exitCode)
603         docker.fn = fn
604         docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
605
606         api = &ArvTestClient{Container: rec}
607         docker.api = api
608         cr = NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
609         cr.statInterval = 100 * time.Millisecond
610         am := &ArvMountCmdLine{}
611         cr.RunArvMount = am.ArvMountTest
612
613         realTemp, err = ioutil.TempDir("", "crunchrun_test1-")
614         c.Assert(err, IsNil)
615         defer os.RemoveAll(realTemp)
616
617         tempcount := 0
618         cr.MkTempDir = func(_ string, prefix string) (string, error) {
619                 tempcount++
620                 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, tempcount)
621                 err := os.Mkdir(d, os.ModePerm)
622                 if err != nil && strings.Contains(err.Error(), ": file exists") {
623                         // Test case must have pre-populated the tempdir
624                         err = nil
625                 }
626                 return d, err
627         }
628
629         if extraMounts != nil && len(extraMounts) > 0 {
630                 err := cr.SetupArvMountPoint("keep")
631                 c.Check(err, IsNil)
632
633                 for _, m := range extraMounts {
634                         os.MkdirAll(cr.ArvMountPoint+"/by_id/"+m, os.ModePerm)
635                 }
636         }
637
638         err = cr.Run()
639         c.Check(err, IsNil)
640         c.Check(api.WasSetRunning, Equals, true)
641
642         c.Check(api.Content[api.Calls-1]["container"].(arvadosclient.Dict)["log"], NotNil)
643
644         if err != nil {
645                 for k, v := range api.Logs {
646                         c.Log(k)
647                         c.Log(v.String())
648                 }
649         }
650
651         return
652 }
653
654 func (s *TestSuite) TestFullRunHello(c *C) {
655         api, _, _ := FullRunHelper(c, `{
656     "command": ["echo", "hello world"],
657     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
658     "cwd": ".",
659     "environment": {},
660     "mounts": {"/tmp": {"kind": "tmp"} },
661     "output_path": "/tmp",
662     "priority": 1,
663     "runtime_constraints": {}
664 }`, nil, 0, func(t *TestDockerClient) {
665                 t.logWriter.Write(dockerLog(1, "hello world\n"))
666                 t.logWriter.Close()
667         })
668
669         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
670         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
671         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
672
673 }
674
675 func (s *TestSuite) TestCrunchstat(c *C) {
676         api, _, _ := FullRunHelper(c, `{
677                 "command": ["sleep", "1"],
678                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
679                 "cwd": ".",
680                 "environment": {},
681                 "mounts": {"/tmp": {"kind": "tmp"} },
682                 "output_path": "/tmp",
683                 "priority": 1,
684                 "runtime_constraints": {}
685         }`, nil, 0, func(t *TestDockerClient) {
686                 time.Sleep(time.Second)
687                 t.logWriter.Close()
688         })
689
690         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
691         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
692
693         // We didn't actually start a container, so crunchstat didn't
694         // find accounting files and therefore didn't log any stats.
695         // It should have logged a "can't find accounting files"
696         // message after one poll interval, though, so we can confirm
697         // it's alive:
698         c.Assert(api.Logs["crunchstat"], NotNil)
699         c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
700
701         // The "files never appeared" log assures us that we called
702         // (*crunchstat.Reporter)Stop(), and that we set it up with
703         // the correct container ID "abcde":
704         c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files never appeared for abcde\n`)
705 }
706
707 func (s *TestSuite) TestNodeInfoLog(c *C) {
708         api, _, _ := FullRunHelper(c, `{
709                 "command": ["sleep", "1"],
710                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
711                 "cwd": ".",
712                 "environment": {},
713                 "mounts": {"/tmp": {"kind": "tmp"} },
714                 "output_path": "/tmp",
715                 "priority": 1,
716                 "runtime_constraints": {}
717         }`, nil, 0,
718                 func(t *TestDockerClient) {
719                         time.Sleep(time.Second)
720                         t.logWriter.Close()
721                 })
722
723         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
724         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
725
726         c.Assert(api.Logs["node-info"], NotNil)
727         c.Check(api.Logs["node-info"].String(), Matches, `(?ms).*Host Information.*`)
728         c.Check(api.Logs["node-info"].String(), Matches, `(?ms).*CPU Information.*`)
729         c.Check(api.Logs["node-info"].String(), Matches, `(?ms).*Memory Information.*`)
730         c.Check(api.Logs["node-info"].String(), Matches, `(?ms).*Disk Space.*`)
731         c.Check(api.Logs["node-info"].String(), Matches, `(?ms).*Disk INodes.*`)
732 }
733
734 func (s *TestSuite) TestContainerRecordLog(c *C) {
735         api, _, _ := FullRunHelper(c, `{
736                 "command": ["sleep", "1"],
737                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
738                 "cwd": ".",
739                 "environment": {},
740                 "mounts": {"/tmp": {"kind": "tmp"} },
741                 "output_path": "/tmp",
742                 "priority": 1,
743                 "runtime_constraints": {}
744         }`, nil, 0,
745                 func(t *TestDockerClient) {
746                         time.Sleep(time.Second)
747                         t.logWriter.Close()
748                 })
749
750         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
751         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
752
753         c.Assert(api.Logs["container"], NotNil)
754         c.Check(api.Logs["container"].String(), Matches, `(?ms).*container_image.*`)
755 }
756
757 func (s *TestSuite) TestFullRunStderr(c *C) {
758         api, _, _ := FullRunHelper(c, `{
759     "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
760     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
761     "cwd": ".",
762     "environment": {},
763     "mounts": {"/tmp": {"kind": "tmp"} },
764     "output_path": "/tmp",
765     "priority": 1,
766     "runtime_constraints": {}
767 }`, nil, 1, func(t *TestDockerClient) {
768                 t.logWriter.Write(dockerLog(1, "hello\n"))
769                 t.logWriter.Write(dockerLog(2, "world\n"))
770                 t.logWriter.Close()
771         })
772
773         final := api.CalledWith("container.state", "Complete")
774         c.Assert(final, NotNil)
775         c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
776         c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
777
778         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
779         c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
780 }
781
782 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
783         api, _, _ := FullRunHelper(c, `{
784     "command": ["pwd"],
785     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
786     "cwd": ".",
787     "environment": {},
788     "mounts": {"/tmp": {"kind": "tmp"} },
789     "output_path": "/tmp",
790     "priority": 1,
791     "runtime_constraints": {}
792 }`, nil, 0, func(t *TestDockerClient) {
793                 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
794                 t.logWriter.Close()
795         })
796
797         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
798         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
799         c.Log(api.Logs["stdout"])
800         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
801 }
802
803 func (s *TestSuite) TestFullRunSetCwd(c *C) {
804         api, _, _ := FullRunHelper(c, `{
805     "command": ["pwd"],
806     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
807     "cwd": "/bin",
808     "environment": {},
809     "mounts": {"/tmp": {"kind": "tmp"} },
810     "output_path": "/tmp",
811     "priority": 1,
812     "runtime_constraints": {}
813 }`, nil, 0, func(t *TestDockerClient) {
814                 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
815                 t.logWriter.Close()
816         })
817
818         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
819         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
820         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
821 }
822
823 func (s *TestSuite) TestStopOnSignal(c *C) {
824         s.testStopContainer(c, func(cr *ContainerRunner) {
825                 go func() {
826                         for !cr.cStarted {
827                                 time.Sleep(time.Millisecond)
828                         }
829                         cr.SigChan <- syscall.SIGINT
830                 }()
831         })
832 }
833
834 func (s *TestSuite) TestStopOnArvMountDeath(c *C) {
835         s.testStopContainer(c, func(cr *ContainerRunner) {
836                 cr.ArvMountExit = make(chan error)
837                 go func() {
838                         cr.ArvMountExit <- exec.Command("true").Run()
839                         close(cr.ArvMountExit)
840                 }()
841         })
842 }
843
844 func (s *TestSuite) testStopContainer(c *C, setup func(cr *ContainerRunner)) {
845         record := `{
846     "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
847     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
848     "cwd": ".",
849     "environment": {},
850     "mounts": {"/tmp": {"kind": "tmp"} },
851     "output_path": "/tmp",
852     "priority": 1,
853     "runtime_constraints": {}
854 }`
855
856         rec := arvados.Container{}
857         err := json.Unmarshal([]byte(record), &rec)
858         c.Check(err, IsNil)
859
860         docker := NewTestDockerClient(0)
861         docker.fn = func(t *TestDockerClient) {
862                 <-t.stop
863                 t.logWriter.Write(dockerLog(1, "foo\n"))
864                 t.logWriter.Close()
865         }
866         docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
867
868         api := &ArvTestClient{Container: rec}
869         cr := NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
870         cr.RunArvMount = func([]string, string) (*exec.Cmd, error) { return nil, nil }
871         setup(cr)
872
873         done := make(chan error)
874         go func() {
875                 done <- cr.Run()
876         }()
877         select {
878         case <-time.After(20 * time.Second):
879                 pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
880                 c.Fatal("timed out")
881         case err = <-done:
882                 c.Check(err, IsNil)
883         }
884         for k, v := range api.Logs {
885                 c.Log(k)
886                 c.Log(v.String())
887         }
888
889         c.Check(api.CalledWith("container.log", nil), NotNil)
890         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
891         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "foo\n"), Equals, true)
892 }
893
894 func (s *TestSuite) TestFullRunSetEnv(c *C) {
895         api, _, _ := FullRunHelper(c, `{
896     "command": ["/bin/sh", "-c", "echo $FROBIZ"],
897     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
898     "cwd": "/bin",
899     "environment": {"FROBIZ": "bilbo"},
900     "mounts": {"/tmp": {"kind": "tmp"} },
901     "output_path": "/tmp",
902     "priority": 1,
903     "runtime_constraints": {}
904 }`, nil, 0, func(t *TestDockerClient) {
905                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
906                 t.logWriter.Close()
907         })
908
909         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
910         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
911         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)
912 }
913
914 type ArvMountCmdLine struct {
915         Cmd   []string
916         token string
917 }
918
919 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
920         am.Cmd = c
921         am.token = token
922         return nil, nil
923 }
924
925 func stubCert(temp string) string {
926         path := temp + "/ca-certificates.crt"
927         crt, _ := os.Create(path)
928         crt.Close()
929         arvadosclient.CertFiles = []string{path}
930         return path
931 }
932
933 func (s *TestSuite) TestSetupMounts(c *C) {
934         api := &ArvTestClient{}
935         kc := &KeepTestClient{}
936         cr := NewContainerRunner(api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
937         am := &ArvMountCmdLine{}
938         cr.RunArvMount = am.ArvMountTest
939
940         realTemp, err := ioutil.TempDir("", "crunchrun_test1-")
941         c.Assert(err, IsNil)
942         certTemp, err := ioutil.TempDir("", "crunchrun_test2-")
943         c.Assert(err, IsNil)
944         stubCertPath := stubCert(certTemp)
945
946         defer os.RemoveAll(realTemp)
947         defer os.RemoveAll(certTemp)
948
949         i := 0
950         cr.MkTempDir = func(_ string, prefix string) (string, error) {
951                 i++
952                 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
953                 err := os.Mkdir(d, os.ModePerm)
954                 if err != nil && strings.Contains(err.Error(), ": file exists") {
955                         // Test case must have pre-populated the tempdir
956                         err = nil
957                 }
958                 return d, err
959         }
960
961         checkEmpty := func() {
962                 filepath.Walk(realTemp, func(path string, _ os.FileInfo, err error) error {
963                         c.Check(path, Equals, realTemp)
964                         c.Check(err, IsNil)
965                         return nil
966                 })
967         }
968
969         {
970                 i = 0
971                 cr.ArvMountPoint = ""
972                 cr.Container.Mounts = make(map[string]arvados.Mount)
973                 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
974                 cr.OutputPath = "/tmp"
975
976                 err := cr.SetupMounts()
977                 c.Check(err, IsNil)
978                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
979                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/tmp"})
980                 cr.CleanupDirs()
981                 checkEmpty()
982         }
983
984         {
985                 i = 0
986                 cr.ArvMountPoint = ""
987                 cr.Container.Mounts = make(map[string]arvados.Mount)
988                 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
989                 cr.OutputPath = "/tmp"
990
991                 apiflag := true
992                 cr.Container.RuntimeConstraints.API = &apiflag
993
994                 err := cr.SetupMounts()
995                 c.Check(err, IsNil)
996                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
997                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/tmp", stubCertPath + ":/etc/arvados/ca-certificates.crt:ro"})
998                 cr.CleanupDirs()
999                 checkEmpty()
1000
1001                 apiflag = false
1002         }
1003
1004         {
1005                 i = 0
1006                 cr.ArvMountPoint = ""
1007                 cr.Container.Mounts = map[string]arvados.Mount{
1008                         "/keeptmp": {Kind: "collection", Writable: true},
1009                 }
1010                 cr.OutputPath = "/keeptmp"
1011
1012                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1013
1014                 err := cr.SetupMounts()
1015                 c.Check(err, IsNil)
1016                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1017                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/tmp0:/keeptmp"})
1018                 cr.CleanupDirs()
1019                 checkEmpty()
1020         }
1021
1022         {
1023                 i = 0
1024                 cr.ArvMountPoint = ""
1025                 cr.Container.Mounts = map[string]arvados.Mount{
1026                         "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1027                         "/keepout": {Kind: "collection", Writable: true},
1028                 }
1029                 cr.OutputPath = "/keepout"
1030
1031                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1032                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1033
1034                 err := cr.SetupMounts()
1035                 c.Check(err, IsNil)
1036                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1037                 sort.StringSlice(cr.Binds).Sort()
1038                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1039                         realTemp + "/keep1/tmp0:/keepout"})
1040                 cr.CleanupDirs()
1041                 checkEmpty()
1042         }
1043
1044         {
1045                 i = 0
1046                 cr.ArvMountPoint = ""
1047                 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
1048                 cr.Container.Mounts = map[string]arvados.Mount{
1049                         "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1050                         "/keepout": {Kind: "collection", Writable: true},
1051                 }
1052                 cr.OutputPath = "/keepout"
1053
1054                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1055                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1056
1057                 err := cr.SetupMounts()
1058                 c.Check(err, IsNil)
1059                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1060                 sort.StringSlice(cr.Binds).Sort()
1061                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1062                         realTemp + "/keep1/tmp0:/keepout"})
1063                 cr.CleanupDirs()
1064                 checkEmpty()
1065         }
1066
1067         for _, test := range []struct {
1068                 in  interface{}
1069                 out string
1070         }{
1071                 {in: "foo", out: `"foo"`},
1072                 {in: nil, out: `null`},
1073                 {in: map[string]int{"foo": 123}, out: `{"foo":123}`},
1074         } {
1075                 i = 0
1076                 cr.ArvMountPoint = ""
1077                 cr.Container.Mounts = map[string]arvados.Mount{
1078                         "/mnt/test.json": {Kind: "json", Content: test.in},
1079                 }
1080                 err := cr.SetupMounts()
1081                 c.Check(err, IsNil)
1082                 sort.StringSlice(cr.Binds).Sort()
1083                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2/mountdata.json:/mnt/test.json:ro"})
1084                 content, err := ioutil.ReadFile(realTemp + "/2/mountdata.json")
1085                 c.Check(err, IsNil)
1086                 c.Check(content, DeepEquals, []byte(test.out))
1087                 cr.CleanupDirs()
1088                 checkEmpty()
1089         }
1090
1091         // Read-only mount points are allowed underneath output_dir mount point
1092         {
1093                 i = 0
1094                 cr.ArvMountPoint = ""
1095                 cr.Container.Mounts = make(map[string]arvados.Mount)
1096                 cr.Container.Mounts = map[string]arvados.Mount{
1097                         "/tmp":     {Kind: "tmp"},
1098                         "/tmp/foo": {Kind: "collection"},
1099                 }
1100                 cr.OutputPath = "/tmp"
1101
1102                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1103
1104                 err := cr.SetupMounts()
1105                 c.Check(err, IsNil)
1106                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other", "--read-write", "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1107                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/2:/tmp", realTemp + "/keep1/tmp0:/tmp/foo:ro"})
1108                 cr.CleanupDirs()
1109                 checkEmpty()
1110         }
1111
1112         // Writable mount points are not allowed underneath output_dir mount point
1113         {
1114                 i = 0
1115                 cr.ArvMountPoint = ""
1116                 cr.Container.Mounts = make(map[string]arvados.Mount)
1117                 cr.Container.Mounts = map[string]arvados.Mount{
1118                         "/tmp":     {Kind: "tmp"},
1119                         "/tmp/foo": {Kind: "collection", Writable: true},
1120                 }
1121                 cr.OutputPath = "/tmp"
1122
1123                 err := cr.SetupMounts()
1124                 c.Check(err, NotNil)
1125                 c.Check(err, ErrorMatches, `Writable mount points are not permitted underneath the output_path.*`)
1126                 cr.CleanupDirs()
1127                 checkEmpty()
1128         }
1129
1130         // Only mount points of kind 'collection' are allowed underneath output_dir mount point
1131         {
1132                 i = 0
1133                 cr.ArvMountPoint = ""
1134                 cr.Container.Mounts = make(map[string]arvados.Mount)
1135                 cr.Container.Mounts = map[string]arvados.Mount{
1136                         "/tmp":     {Kind: "tmp"},
1137                         "/tmp/foo": {Kind: "json"},
1138                 }
1139                 cr.OutputPath = "/tmp"
1140
1141                 err := cr.SetupMounts()
1142                 c.Check(err, NotNil)
1143                 c.Check(err, ErrorMatches, `Only mount points of kind 'collection' are supported underneath the output_path.*`)
1144                 cr.CleanupDirs()
1145                 checkEmpty()
1146         }
1147
1148         // Only mount point of kind 'collection' is allowed for stdin
1149         {
1150                 i = 0
1151                 cr.ArvMountPoint = ""
1152                 cr.Container.Mounts = make(map[string]arvados.Mount)
1153                 cr.Container.Mounts = map[string]arvados.Mount{
1154                         "stdin": {Kind: "tmp"},
1155                 }
1156
1157                 err := cr.SetupMounts()
1158                 c.Check(err, NotNil)
1159                 c.Check(err, ErrorMatches, `Unsupported mount kind 'tmp' for stdin.*`)
1160                 cr.CleanupDirs()
1161                 checkEmpty()
1162         }
1163 }
1164
1165 func (s *TestSuite) TestStdout(c *C) {
1166         helperRecord := `{
1167                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1168                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1169                 "cwd": "/bin",
1170                 "environment": {"FROBIZ": "bilbo"},
1171                 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1172                 "output_path": "/tmp",
1173                 "priority": 1,
1174                 "runtime_constraints": {}
1175         }`
1176
1177         api, _, _ := FullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1178                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1179                 t.logWriter.Close()
1180         })
1181
1182         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1183         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1184         c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1185 }
1186
1187 // Used by the TestStdoutWithWrongPath*()
1188 func StdoutErrorRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, err error) {
1189         rec := arvados.Container{}
1190         err = json.Unmarshal([]byte(record), &rec)
1191         c.Check(err, IsNil)
1192
1193         docker := NewTestDockerClient(0)
1194         docker.fn = fn
1195         docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
1196
1197         api = &ArvTestClient{Container: rec}
1198         cr = NewContainerRunner(api, &KeepTestClient{}, docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1199         am := &ArvMountCmdLine{}
1200         cr.RunArvMount = am.ArvMountTest
1201
1202         err = cr.Run()
1203         return
1204 }
1205
1206 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1207         _, _, err := StdoutErrorRunHelper(c, `{
1208     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1209     "output_path": "/tmp"
1210 }`, func(t *TestDockerClient) {})
1211
1212         c.Check(err, NotNil)
1213         c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
1214 }
1215
1216 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1217         _, _, err := StdoutErrorRunHelper(c, `{
1218     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1219     "output_path": "/tmp"
1220 }`, func(t *TestDockerClient) {})
1221
1222         c.Check(err, NotNil)
1223         c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'tmp' for stdout"), Equals, true)
1224 }
1225
1226 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1227         _, _, err := StdoutErrorRunHelper(c, `{
1228     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1229     "output_path": "/tmp"
1230 }`, func(t *TestDockerClient) {})
1231
1232         c.Check(err, NotNil)
1233         c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'collection' for stdout"), Equals, true)
1234 }
1235
1236 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1237         os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1238         defer os.Unsetenv("ARVADOS_API_HOST")
1239         api, _, _ := FullRunHelper(c, `{
1240     "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1241     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1242     "cwd": "/bin",
1243     "environment": {},
1244     "mounts": {"/tmp": {"kind": "tmp"} },
1245     "output_path": "/tmp",
1246     "priority": 1,
1247     "runtime_constraints": {"API": true}
1248 }`, nil, 0, func(t *TestDockerClient) {
1249                 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
1250                 t.logWriter.Close()
1251         })
1252
1253         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1254         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1255         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "test.arvados.org\n"), Equals, true)
1256         c.Check(api.CalledWith("container.output", "d41d8cd98f00b204e9800998ecf8427e+0"), NotNil)
1257 }
1258
1259 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1260         os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1261         defer os.Unsetenv("ARVADOS_API_HOST")
1262         api, _, _ := FullRunHelper(c, `{
1263     "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1264     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1265     "cwd": "/bin",
1266     "environment": {},
1267     "mounts": {"/tmp": {"kind": "tmp"} },
1268     "output_path": "/tmp",
1269     "priority": 1,
1270     "runtime_constraints": {"API": true}
1271 }`, nil, 0, func(t *TestDockerClient) {
1272                 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
1273                 t.logWriter.Close()
1274         })
1275
1276         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1277         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1278         c.Check(api.CalledWith("container.output", "d4ab34d3d4f8a72f5c4973051ae69fab+122"), NotNil)
1279 }
1280
1281 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1282         helperRecord := `{
1283                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1284                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1285                 "cwd": "/bin",
1286                 "environment": {"FROBIZ": "bilbo"},
1287                 "mounts": {
1288         "/tmp": {"kind": "tmp"},
1289         "/tmp/foo": {"kind": "collection",
1290                      "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1291                      "exclude_from_output": true
1292         },
1293         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1294     },
1295                 "output_path": "/tmp",
1296                 "priority": 1,
1297                 "runtime_constraints": {}
1298         }`
1299
1300         extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1301
1302         api, _, _ := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1303                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1304                 t.logWriter.Close()
1305         })
1306
1307         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1308         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1309         c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1310 }
1311
1312 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1313         helperRecord := `{
1314                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1315                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1316                 "cwd": "/bin",
1317                 "environment": {"FROBIZ": "bilbo"},
1318                 "mounts": {
1319         "/tmp": {"kind": "tmp"},
1320         "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1321         "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1322         "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1323         "/tmp/foo/baz/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1324         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1325     },
1326                 "output_path": "/tmp",
1327                 "priority": 1,
1328                 "runtime_constraints": {}
1329         }`
1330
1331         extraMounts := []string{
1332                 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1333                 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1334                 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1335         }
1336
1337         api, runner, realtemp := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1338                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1339                 t.logWriter.Close()
1340         })
1341
1342         c.Check(runner.Binds, DeepEquals, []string{realtemp + "/2:/tmp",
1343                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt:/tmp/foo/bar:ro",
1344                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt:/tmp/foo/baz/sub2file2:ro",
1345                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1:/tmp/foo/sub1:ro",
1346                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt:/tmp/foo/sub1file2:ro",
1347         })
1348
1349         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1350         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1351         for _, v := range api.Content {
1352                 if v["collection"] != nil {
1353                         c.Check(v["ensure_unique_name"], Equals, true)
1354                         collection := v["collection"].(arvadosclient.Dict)
1355                         if strings.Index(collection["name"].(string), "output") == 0 {
1356                                 manifest := collection["manifest_text"].(string)
1357
1358                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1359 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 9:18:bar 9:18:sub1file2
1360 ./foo/baz 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2
1361 ./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1362 ./foo/sub1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1363 `)
1364                         }
1365                 }
1366         }
1367 }
1368
1369 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
1370         helperRecord := `{
1371                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1372                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1373                 "cwd": "/bin",
1374                 "environment": {"FROBIZ": "bilbo"},
1375                 "mounts": {
1376         "/tmp": {"kind": "tmp"},
1377         "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt"},
1378         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1379     },
1380                 "output_path": "/tmp",
1381                 "priority": 1,
1382                 "runtime_constraints": {}
1383         }`
1384
1385         extraMounts := []string{
1386                 "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1387         }
1388
1389         api, _, _ := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1390                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1391                 t.logWriter.Close()
1392         })
1393
1394         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1395         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1396         for _, v := range api.Content {
1397                 if v["collection"] != nil {
1398                         collection := v["collection"].(arvadosclient.Dict)
1399                         if strings.Index(collection["name"].(string), "output") == 0 {
1400                                 manifest := collection["manifest_text"].(string)
1401
1402                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1403 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 10:17:bar
1404 `)
1405                         }
1406                 }
1407         }
1408 }
1409
1410 func (s *TestSuite) TestStdinCollectionMountPoint(c *C) {
1411         helperRecord := `{
1412                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1413                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1414                 "cwd": "/bin",
1415                 "environment": {"FROBIZ": "bilbo"},
1416                 "mounts": {
1417         "/tmp": {"kind": "tmp"},
1418         "stdin": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/file1_in_main.txt"},
1419         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1420     },
1421                 "output_path": "/tmp",
1422                 "priority": 1,
1423                 "runtime_constraints": {}
1424         }`
1425
1426         extraMounts := []string{
1427                 "b0def87f80dd594d4675809e83bd4f15+367/file1_in_main.txt",
1428         }
1429
1430         api, _, _ := FullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1431                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1432                 t.logWriter.Close()
1433         })
1434
1435         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1436         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1437         for _, v := range api.Content {
1438                 if v["collection"] != nil {
1439                         collection := v["collection"].(arvadosclient.Dict)
1440                         if strings.Index(collection["name"].(string), "output") == 0 {
1441                                 manifest := collection["manifest_text"].(string)
1442
1443                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1444 `)
1445                         }
1446                 }
1447         }
1448 }
1449
1450 func (s *TestSuite) TestStdinJsonMountPoint(c *C) {
1451         helperRecord := `{
1452                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1453                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1454                 "cwd": "/bin",
1455                 "environment": {"FROBIZ": "bilbo"},
1456                 "mounts": {
1457         "/tmp": {"kind": "tmp"},
1458         "stdin": {"kind": "json", "content": "foo"},
1459         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1460     },
1461                 "output_path": "/tmp",
1462                 "priority": 1,
1463                 "runtime_constraints": {}
1464         }`
1465
1466         api, _, _ := FullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1467                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1468                 t.logWriter.Close()
1469         })
1470
1471         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1472         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1473         for _, v := range api.Content {
1474                 if v["collection"] != nil {
1475                         collection := v["collection"].(arvadosclient.Dict)
1476                         if strings.Index(collection["name"].(string), "output") == 0 {
1477                                 manifest := collection["manifest_text"].(string)
1478
1479                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1480 `)
1481                         }
1482                 }
1483         }
1484 }