Merge branch '14198-crunch-run-tokens' refs #14198
[arvados.git] / services / crunch-run / crunchrun_test.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package main
6
7 import (
8         "bufio"
9         "bytes"
10         "crypto/md5"
11         "encoding/json"
12         "errors"
13         "fmt"
14         "io"
15         "io/ioutil"
16         "net"
17         "os"
18         "os/exec"
19         "runtime/pprof"
20         "sort"
21         "strings"
22         "sync"
23         "syscall"
24         "testing"
25         "time"
26
27         "git.curoverse.com/arvados.git/sdk/go/arvados"
28         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
29         "git.curoverse.com/arvados.git/sdk/go/arvadostest"
30         "git.curoverse.com/arvados.git/sdk/go/manifest"
31         "golang.org/x/net/context"
32
33         dockertypes "github.com/docker/docker/api/types"
34         dockercontainer "github.com/docker/docker/api/types/container"
35         dockernetwork "github.com/docker/docker/api/types/network"
36         . "gopkg.in/check.v1"
37 )
38
39 // Gocheck boilerplate
40 func TestCrunchExec(t *testing.T) {
41         TestingT(t)
42 }
43
44 // Gocheck boilerplate
45 var _ = Suite(&TestSuite{})
46
47 type TestSuite struct {
48         client *arvados.Client
49         docker *TestDockerClient
50         runner *ContainerRunner
51 }
52
53 func (s *TestSuite) SetUpTest(c *C) {
54         s.client = arvados.NewClientFromEnv()
55         s.docker = NewTestDockerClient()
56 }
57
58 type ArvTestClient struct {
59         Total   int64
60         Calls   int
61         Content []arvadosclient.Dict
62         arvados.Container
63         secretMounts []byte
64         Logs         map[string]*bytes.Buffer
65         sync.Mutex
66         WasSetRunning bool
67         callraw       bool
68 }
69
70 type KeepTestClient struct {
71         Called  bool
72         Content []byte
73 }
74
75 var hwManifest = ". 82ab40c24fc8df01798e57ba66795bb1+841216+Aa124ac75e5168396c73c0a18eda641a4f41791c0@569fa8c3 0:841216:9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7.tar\n"
76 var hwPDH = "a45557269dcb65a6b78f9ac061c0850b+120"
77 var hwImageId = "9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7"
78
79 var otherManifest = ". 68a84f561b1d1708c6baff5e019a9ab3+46+Ae5d0af96944a3690becb1decdf60cc1c937f556d@5693216f 0:46:md5sum.txt\n"
80 var otherPDH = "a3e8f74c6f101eae01fa08bfb4e49b3a+54"
81
82 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
83 ./subdir1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
84 ./subdir1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
85 `
86
87 var normalizedWithSubdirsPDH = "a0def87f80dd594d4675809e83bd4f15+367"
88
89 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"
90 var denormalizedWithSubdirsPDH = "b0def87f80dd594d4675809e83bd4f15+367"
91
92 var fakeAuthUUID = "zzzzz-gj3su-55pqoyepgi2glem"
93 var fakeAuthToken = "a3ltuwzqcu2u4sc0q7yhpc2w7s00fdcqecg5d6e0u3pfohmbjt"
94
95 type TestDockerClient struct {
96         imageLoaded string
97         logReader   io.ReadCloser
98         logWriter   io.WriteCloser
99         fn          func(t *TestDockerClient)
100         exitCode    int
101         stop        chan bool
102         cwd         string
103         env         []string
104         api         *ArvTestClient
105         realTemp    string
106         calledWait  bool
107         ctrExited   bool
108 }
109
110 func NewTestDockerClient() *TestDockerClient {
111         t := &TestDockerClient{}
112         t.logReader, t.logWriter = io.Pipe()
113         t.stop = make(chan bool, 1)
114         t.cwd = "/"
115         return t
116 }
117
118 type MockConn struct {
119         net.Conn
120 }
121
122 func (m *MockConn) Write(b []byte) (int, error) {
123         return len(b), nil
124 }
125
126 func NewMockConn() *MockConn {
127         c := &MockConn{}
128         return c
129 }
130
131 func (t *TestDockerClient) ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error) {
132         return dockertypes.HijackedResponse{Conn: NewMockConn(), Reader: bufio.NewReader(t.logReader)}, nil
133 }
134
135 func (t *TestDockerClient) ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig, networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error) {
136         if config.WorkingDir != "" {
137                 t.cwd = config.WorkingDir
138         }
139         t.env = config.Env
140         return dockercontainer.ContainerCreateCreatedBody{ID: "abcde"}, nil
141 }
142
143 func (t *TestDockerClient) ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error {
144         if t.exitCode == 3 {
145                 return errors.New(`Error response from daemon: oci runtime error: container_linux.go:247: starting container process caused "process_linux.go:359: container init caused \"rootfs_linux.go:54: mounting \\\"/tmp/keep453790790/by_id/99999999999999999999999999999999+99999/myGenome\\\" to rootfs \\\"/tmp/docker/overlay2/9999999999999999999999999999999999999999999999999999999999999999/merged\\\" at \\\"/tmp/docker/overlay2/9999999999999999999999999999999999999999999999999999999999999999/merged/keep/99999999999999999999999999999999+99999/myGenome\\\" caused \\\"no such file or directory\\\"\""`)
146         }
147         if t.exitCode == 4 {
148                 return errors.New(`panic: standard_init_linux.go:175: exec user process caused "no such file or directory"`)
149         }
150         if t.exitCode == 5 {
151                 return errors.New(`Error response from daemon: Cannot start container 41f26cbc43bcc1280f4323efb1830a394ba8660c9d1c2b564ba42bf7f7694845: [8] System error: no such file or directory`)
152         }
153         if t.exitCode == 6 {
154                 return errors.New(`Error response from daemon: Cannot start container 58099cd76c834f3dc2a4fb76c8028f049ae6d4fdf0ec373e1f2cfea030670c2d: [8] System error: exec: "foobar": executable file not found in $PATH`)
155         }
156
157         if container == "abcde" {
158                 // t.fn gets executed in ContainerWait
159                 return nil
160         } else {
161                 return errors.New("Invalid container id")
162         }
163 }
164
165 func (t *TestDockerClient) ContainerRemove(ctx context.Context, container string, options dockertypes.ContainerRemoveOptions) error {
166         t.stop <- true
167         return nil
168 }
169
170 func (t *TestDockerClient) ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error) {
171         t.calledWait = true
172         body := make(chan dockercontainer.ContainerWaitOKBody, 1)
173         err := make(chan error)
174         go func() {
175                 t.fn(t)
176                 body <- dockercontainer.ContainerWaitOKBody{StatusCode: int64(t.exitCode)}
177         }()
178         return body, err
179 }
180
181 func (t *TestDockerClient) ContainerInspect(ctx context.Context, id string) (c dockertypes.ContainerJSON, err error) {
182         c.ContainerJSONBase = &dockertypes.ContainerJSONBase{}
183         c.ID = "abcde"
184         if t.ctrExited {
185                 c.State = &dockertypes.ContainerState{Status: "exited", Dead: true}
186         } else {
187                 c.State = &dockertypes.ContainerState{Status: "running", Pid: 1234, Running: true}
188         }
189         return
190 }
191
192 func (t *TestDockerClient) ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error) {
193         if t.exitCode == 2 {
194                 return dockertypes.ImageInspect{}, nil, fmt.Errorf("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?")
195         }
196
197         if t.imageLoaded == image {
198                 return dockertypes.ImageInspect{}, nil, nil
199         } else {
200                 return dockertypes.ImageInspect{}, nil, errors.New("")
201         }
202 }
203
204 func (t *TestDockerClient) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error) {
205         if t.exitCode == 2 {
206                 return dockertypes.ImageLoadResponse{}, fmt.Errorf("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?")
207         }
208         _, err := io.Copy(ioutil.Discard, input)
209         if err != nil {
210                 return dockertypes.ImageLoadResponse{}, err
211         } else {
212                 t.imageLoaded = hwImageId
213                 return dockertypes.ImageLoadResponse{Body: ioutil.NopCloser(input)}, nil
214         }
215 }
216
217 func (*TestDockerClient) ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {
218         return nil, nil
219 }
220
221 func (client *ArvTestClient) Create(resourceType string,
222         parameters arvadosclient.Dict,
223         output interface{}) error {
224
225         client.Mutex.Lock()
226         defer client.Mutex.Unlock()
227
228         client.Calls++
229         client.Content = append(client.Content, parameters)
230
231         if resourceType == "logs" {
232                 et := parameters["log"].(arvadosclient.Dict)["event_type"].(string)
233                 if client.Logs == nil {
234                         client.Logs = make(map[string]*bytes.Buffer)
235                 }
236                 if client.Logs[et] == nil {
237                         client.Logs[et] = &bytes.Buffer{}
238                 }
239                 client.Logs[et].Write([]byte(parameters["log"].(arvadosclient.Dict)["properties"].(map[string]string)["text"]))
240         }
241
242         if resourceType == "collections" && output != nil {
243                 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
244                 outmap := output.(*arvados.Collection)
245                 outmap.PortableDataHash = fmt.Sprintf("%x+%d", md5.Sum([]byte(mt)), len(mt))
246                 outmap.UUID = fmt.Sprintf("zzzzz-4zz18-%15.15x", md5.Sum([]byte(mt)))
247         }
248
249         return nil
250 }
251
252 func (client *ArvTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
253         switch {
254         case method == "GET" && resourceType == "containers" && action == "auth":
255                 return json.Unmarshal([]byte(`{
256                         "kind": "arvados#api_client_authorization",
257                         "uuid": "`+fakeAuthUUID+`",
258                         "api_token": "`+fakeAuthToken+`"
259                         }`), output)
260         case method == "GET" && resourceType == "containers" && action == "secret_mounts":
261                 if client.secretMounts != nil {
262                         return json.Unmarshal(client.secretMounts, output)
263                 } else {
264                         return json.Unmarshal([]byte(`{"secret_mounts":{}}`), output)
265                 }
266         default:
267                 return fmt.Errorf("Not found")
268         }
269 }
270
271 func (client *ArvTestClient) CallRaw(method, resourceType, uuid, action string,
272         parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
273         var j []byte
274         if method == "GET" && resourceType == "nodes" && uuid == "" && action == "" {
275                 j = []byte(`{
276                         "kind": "arvados#nodeList",
277                         "items": [{
278                                 "uuid": "zzzzz-7ekkf-2z3mc76g2q73aio",
279                                 "hostname": "compute2",
280                                 "properties": {"total_cpu_cores": 16}
281                         }]}`)
282         } else if method == "GET" && resourceType == "containers" && action == "" && !client.callraw {
283                 if uuid == "" {
284                         j, err = json.Marshal(map[string]interface{}{
285                                 "items": []interface{}{client.Container},
286                                 "kind":  "arvados#nodeList",
287                         })
288                 } else {
289                         j, err = json.Marshal(client.Container)
290                 }
291         } else {
292                 j = []byte(`{
293                         "command": ["sleep", "1"],
294                         "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
295                         "cwd": ".",
296                         "environment": {},
297                         "mounts": {"/tmp": {"kind": "tmp"}, "/json": {"kind": "json", "content": {"number": 123456789123456789}}},
298                         "output_path": "/tmp",
299                         "priority": 1,
300                         "runtime_constraints": {}
301                 }`)
302         }
303         return ioutil.NopCloser(bytes.NewReader(j)), err
304 }
305
306 func (client *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
307         if resourceType == "collections" {
308                 if uuid == hwPDH {
309                         output.(*arvados.Collection).ManifestText = hwManifest
310                 } else if uuid == otherPDH {
311                         output.(*arvados.Collection).ManifestText = otherManifest
312                 } else if uuid == normalizedWithSubdirsPDH {
313                         output.(*arvados.Collection).ManifestText = normalizedManifestWithSubdirs
314                 } else if uuid == denormalizedWithSubdirsPDH {
315                         output.(*arvados.Collection).ManifestText = denormalizedManifestWithSubdirs
316                 }
317         }
318         if resourceType == "containers" {
319                 (*output.(*arvados.Container)) = client.Container
320         }
321         return nil
322 }
323
324 func (client *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
325         client.Mutex.Lock()
326         defer client.Mutex.Unlock()
327         client.Calls++
328         client.Content = append(client.Content, parameters)
329         if resourceType == "containers" {
330                 if parameters["container"].(arvadosclient.Dict)["state"] == "Running" {
331                         client.WasSetRunning = true
332                 }
333         } else if resourceType == "collections" {
334                 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
335                 output.(*arvados.Collection).UUID = uuid
336                 output.(*arvados.Collection).PortableDataHash = fmt.Sprintf("%x", md5.Sum([]byte(mt)))
337         }
338         return nil
339 }
340
341 var discoveryMap = map[string]interface{}{
342         "defaultTrashLifetime":               float64(1209600),
343         "crunchLimitLogBytesPerJob":          float64(67108864),
344         "crunchLogThrottleBytes":             float64(65536),
345         "crunchLogThrottlePeriod":            float64(60),
346         "crunchLogThrottleLines":             float64(1024),
347         "crunchLogPartialLineThrottlePeriod": float64(5),
348         "crunchLogBytesPerEvent":             float64(4096),
349         "crunchLogSecondsBetweenEvents":      float64(1),
350 }
351
352 func (client *ArvTestClient) Discovery(key string) (interface{}, error) {
353         return discoveryMap[key], nil
354 }
355
356 // CalledWith returns the parameters from the first API call whose
357 // parameters match jpath/string. E.g., CalledWith(c, "foo.bar",
358 // "baz") returns parameters with parameters["foo"]["bar"]=="baz". If
359 // no call matches, it returns nil.
360 func (client *ArvTestClient) CalledWith(jpath string, expect interface{}) arvadosclient.Dict {
361 call:
362         for _, content := range client.Content {
363                 var v interface{} = content
364                 for _, k := range strings.Split(jpath, ".") {
365                         if dict, ok := v.(arvadosclient.Dict); !ok {
366                                 continue call
367                         } else {
368                                 v = dict[k]
369                         }
370                 }
371                 if v == expect {
372                         return content
373                 }
374         }
375         return nil
376 }
377
378 func (client *KeepTestClient) LocalLocator(locator string) (string, error) {
379         return locator, nil
380 }
381
382 func (client *KeepTestClient) PutB(buf []byte) (string, int, error) {
383         client.Content = buf
384         return fmt.Sprintf("%x+%d", md5.Sum(buf), len(buf)), len(buf), nil
385 }
386
387 func (client *KeepTestClient) ReadAt(string, []byte, int) (int, error) {
388         return 0, errors.New("not implemented")
389 }
390
391 func (client *KeepTestClient) ClearBlockCache() {
392 }
393
394 func (client *KeepTestClient) Close() {
395         client.Content = nil
396 }
397
398 type FileWrapper struct {
399         io.ReadCloser
400         len int64
401 }
402
403 func (fw FileWrapper) Readdir(n int) ([]os.FileInfo, error) {
404         return nil, errors.New("not implemented")
405 }
406
407 func (fw FileWrapper) Seek(int64, int) (int64, error) {
408         return 0, errors.New("not implemented")
409 }
410
411 func (fw FileWrapper) Size() int64 {
412         return fw.len
413 }
414
415 func (fw FileWrapper) Stat() (os.FileInfo, error) {
416         return nil, errors.New("not implemented")
417 }
418
419 func (fw FileWrapper) Truncate(int64) error {
420         return errors.New("not implemented")
421 }
422
423 func (fw FileWrapper) Write([]byte) (int, error) {
424         return 0, errors.New("not implemented")
425 }
426
427 func (fw FileWrapper) Sync() error {
428         return errors.New("not implemented")
429 }
430
431 func (client *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
432         if filename == hwImageId+".tar" {
433                 rdr := ioutil.NopCloser(&bytes.Buffer{})
434                 client.Called = true
435                 return FileWrapper{rdr, 1321984}, nil
436         } else if filename == "/file1_in_main.txt" {
437                 rdr := ioutil.NopCloser(strings.NewReader("foo"))
438                 client.Called = true
439                 return FileWrapper{rdr, 3}, nil
440         }
441         return nil, nil
442 }
443
444 func (s *TestSuite) TestLoadImage(c *C) {
445         cr, err := NewContainerRunner(s.client, &ArvTestClient{},
446                 &KeepTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
447         c.Assert(err, IsNil)
448
449         kc := &KeepTestClient{}
450         defer kc.Close()
451         cr.ContainerArvClient = &ArvTestClient{}
452         cr.ContainerKeepClient = kc
453
454         _, err = cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
455         c.Check(err, IsNil)
456
457         _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
458         c.Check(err, NotNil)
459
460         cr.Container.ContainerImage = hwPDH
461
462         // (1) Test loading image from keep
463         c.Check(kc.Called, Equals, false)
464         c.Check(cr.ContainerConfig.Image, Equals, "")
465
466         err = cr.LoadImage()
467
468         c.Check(err, IsNil)
469         defer func() {
470                 cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
471         }()
472
473         c.Check(kc.Called, Equals, true)
474         c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
475
476         _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
477         c.Check(err, IsNil)
478
479         // (2) Test using image that's already loaded
480         kc.Called = false
481         cr.ContainerConfig.Image = ""
482
483         err = cr.LoadImage()
484         c.Check(err, IsNil)
485         c.Check(kc.Called, Equals, false)
486         c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
487
488 }
489
490 type ArvErrorTestClient struct{}
491
492 func (ArvErrorTestClient) Create(resourceType string,
493         parameters arvadosclient.Dict,
494         output interface{}) error {
495         return nil
496 }
497
498 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
499         if method == "GET" && resourceType == "containers" && action == "auth" {
500                 return nil
501         }
502         return errors.New("ArvError")
503 }
504
505 func (ArvErrorTestClient) CallRaw(method, resourceType, uuid, action string,
506         parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
507         return nil, errors.New("ArvError")
508 }
509
510 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
511         return errors.New("ArvError")
512 }
513
514 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
515         return nil
516 }
517
518 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
519         return discoveryMap[key], nil
520 }
521
522 type KeepErrorTestClient struct {
523         KeepTestClient
524 }
525
526 func (*KeepErrorTestClient) ManifestFileReader(manifest.Manifest, string) (arvados.File, error) {
527         return nil, errors.New("KeepError")
528 }
529
530 func (*KeepErrorTestClient) PutB(buf []byte) (string, int, error) {
531         return "", 0, errors.New("KeepError")
532 }
533
534 func (*KeepErrorTestClient) LocalLocator(string) (string, error) {
535         return "", errors.New("KeepError")
536 }
537
538 type KeepReadErrorTestClient struct {
539         KeepTestClient
540 }
541
542 func (*KeepReadErrorTestClient) ReadAt(string, []byte, int) (int, error) {
543         return 0, errors.New("KeepError")
544 }
545
546 type ErrorReader struct {
547         FileWrapper
548 }
549
550 func (ErrorReader) Read(p []byte) (n int, err error) {
551         return 0, errors.New("ErrorReader")
552 }
553
554 func (ErrorReader) Seek(int64, int) (int64, error) {
555         return 0, errors.New("ErrorReader")
556 }
557
558 func (KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
559         return ErrorReader{}, nil
560 }
561
562 func (s *TestSuite) TestLoadImageArvError(c *C) {
563         // (1) Arvados error
564         kc := &KeepTestClient{}
565         defer kc.Close()
566         cr, err := NewContainerRunner(s.client, &ArvErrorTestClient{}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
567         c.Assert(err, IsNil)
568
569         cr.ContainerArvClient = &ArvErrorTestClient{}
570         cr.ContainerKeepClient = &KeepTestClient{}
571
572         cr.Container.ContainerImage = hwPDH
573
574         err = cr.LoadImage()
575         c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
576 }
577
578 func (s *TestSuite) TestLoadImageKeepError(c *C) {
579         // (2) Keep error
580         kc := &KeepErrorTestClient{}
581         cr, err := NewContainerRunner(s.client, &ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
582         c.Assert(err, IsNil)
583
584         cr.ContainerArvClient = &ArvTestClient{}
585         cr.ContainerKeepClient = &KeepErrorTestClient{}
586
587         cr.Container.ContainerImage = hwPDH
588
589         err = cr.LoadImage()
590         c.Assert(err, NotNil)
591         c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
592 }
593
594 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
595         // (3) Collection doesn't contain image
596         kc := &KeepReadErrorTestClient{}
597         cr, err := NewContainerRunner(s.client, &ArvTestClient{}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
598         c.Assert(err, IsNil)
599         cr.Container.ContainerImage = otherPDH
600
601         cr.ContainerArvClient = &ArvTestClient{}
602         cr.ContainerKeepClient = &KeepReadErrorTestClient{}
603
604         err = cr.LoadImage()
605         c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
606 }
607
608 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
609         // (4) Collection doesn't contain image
610         kc := &KeepReadErrorTestClient{}
611         cr, err := NewContainerRunner(s.client, &ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
612         c.Assert(err, IsNil)
613         cr.Container.ContainerImage = hwPDH
614         cr.ContainerArvClient = &ArvTestClient{}
615         cr.ContainerKeepClient = &KeepReadErrorTestClient{}
616
617         err = cr.LoadImage()
618         c.Check(err, NotNil)
619 }
620
621 type ClosableBuffer struct {
622         bytes.Buffer
623 }
624
625 func (*ClosableBuffer) Close() error {
626         return nil
627 }
628
629 type TestLogs struct {
630         Stdout ClosableBuffer
631         Stderr ClosableBuffer
632 }
633
634 func (tl *TestLogs) NewTestLoggingWriter(logstr string) (io.WriteCloser, error) {
635         if logstr == "stdout" {
636                 return &tl.Stdout, nil
637         }
638         if logstr == "stderr" {
639                 return &tl.Stderr, nil
640         }
641         return nil, errors.New("???")
642 }
643
644 func dockerLog(fd byte, msg string) []byte {
645         by := []byte(msg)
646         header := make([]byte, 8+len(by))
647         header[0] = fd
648         header[7] = byte(len(by))
649         copy(header[8:], by)
650         return header
651 }
652
653 func (s *TestSuite) TestRunContainer(c *C) {
654         s.docker.fn = func(t *TestDockerClient) {
655                 t.logWriter.Write(dockerLog(1, "Hello world\n"))
656                 t.logWriter.Close()
657         }
658         kc := &KeepTestClient{}
659         defer kc.Close()
660         cr, err := NewContainerRunner(s.client, &ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
661         c.Assert(err, IsNil)
662
663         cr.ContainerArvClient = &ArvTestClient{}
664         cr.ContainerKeepClient = &KeepTestClient{}
665
666         var logs TestLogs
667         cr.NewLogWriter = logs.NewTestLoggingWriter
668         cr.Container.ContainerImage = hwPDH
669         cr.Container.Command = []string{"./hw"}
670         err = cr.LoadImage()
671         c.Check(err, IsNil)
672
673         err = cr.CreateContainer()
674         c.Check(err, IsNil)
675
676         err = cr.StartContainer()
677         c.Check(err, IsNil)
678
679         err = cr.WaitFinish()
680         c.Check(err, IsNil)
681
682         c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
683         c.Check(logs.Stderr.String(), Equals, "")
684 }
685
686 func (s *TestSuite) TestCommitLogs(c *C) {
687         api := &ArvTestClient{}
688         kc := &KeepTestClient{}
689         defer kc.Close()
690         cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
691         c.Assert(err, IsNil)
692         cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
693
694         cr.CrunchLog.Print("Hello world!")
695         cr.CrunchLog.Print("Goodbye")
696         cr.finalState = "Complete"
697
698         err = cr.CommitLogs()
699         c.Check(err, IsNil)
700
701         c.Check(api.Calls, Equals, 2)
702         c.Check(api.Content[1]["ensure_unique_name"], Equals, true)
703         c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
704         c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
705         c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
706 }
707
708 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
709         api := &ArvTestClient{}
710         kc := &KeepTestClient{}
711         defer kc.Close()
712         cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
713         c.Assert(err, IsNil)
714
715         err = cr.UpdateContainerRunning()
716         c.Check(err, IsNil)
717
718         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
719 }
720
721 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
722         api := &ArvTestClient{}
723         kc := &KeepTestClient{}
724         defer kc.Close()
725         cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
726         c.Assert(err, IsNil)
727
728         cr.LogsPDH = new(string)
729         *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
730
731         cr.ExitCode = new(int)
732         *cr.ExitCode = 42
733         cr.finalState = "Complete"
734
735         err = cr.UpdateContainerFinal()
736         c.Check(err, IsNil)
737
738         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
739         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
740         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
741 }
742
743 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
744         api := &ArvTestClient{}
745         kc := &KeepTestClient{}
746         defer kc.Close()
747         cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
748         c.Assert(err, IsNil)
749         cr.cCancelled = true
750         cr.finalState = "Cancelled"
751
752         err = cr.UpdateContainerFinal()
753         c.Check(err, IsNil)
754
755         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
756         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
757         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
758 }
759
760 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
761 // dress rehearsal of the Run() function, starting from a JSON container record.
762 func (s *TestSuite) fullRunHelper(c *C, record string, extraMounts []string, exitCode int, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, realTemp string) {
763         rec := arvados.Container{}
764         err := json.Unmarshal([]byte(record), &rec)
765         c.Check(err, IsNil)
766
767         var sm struct {
768                 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
769         }
770         err = json.Unmarshal([]byte(record), &sm)
771         c.Check(err, IsNil)
772         secretMounts, err := json.Marshal(sm)
773         c.Logf("%s %q", sm, secretMounts)
774         c.Check(err, IsNil)
775
776         s.docker.exitCode = exitCode
777         s.docker.fn = fn
778         s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
779
780         api = &ArvTestClient{Container: rec}
781         s.docker.api = api
782         kc := &KeepTestClient{}
783         defer kc.Close()
784         cr, err = NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
785         c.Assert(err, IsNil)
786         s.runner = cr
787         cr.statInterval = 100 * time.Millisecond
788         cr.containerWatchdogInterval = time.Second
789         am := &ArvMountCmdLine{}
790         cr.RunArvMount = am.ArvMountTest
791
792         realTemp, err = ioutil.TempDir("", "crunchrun_test1-")
793         c.Assert(err, IsNil)
794         defer os.RemoveAll(realTemp)
795
796         s.docker.realTemp = realTemp
797
798         tempcount := 0
799         cr.MkTempDir = func(_ string, prefix string) (string, error) {
800                 tempcount++
801                 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, tempcount)
802                 err := os.Mkdir(d, os.ModePerm)
803                 if err != nil && strings.Contains(err.Error(), ": file exists") {
804                         // Test case must have pre-populated the tempdir
805                         err = nil
806                 }
807                 return d, err
808         }
809         cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
810                 return &ArvTestClient{secretMounts: secretMounts}, &KeepTestClient{}, nil, nil
811         }
812
813         if extraMounts != nil && len(extraMounts) > 0 {
814                 err := cr.SetupArvMountPoint("keep")
815                 c.Check(err, IsNil)
816
817                 for _, m := range extraMounts {
818                         os.MkdirAll(cr.ArvMountPoint+"/by_id/"+m, os.ModePerm)
819                 }
820         }
821
822         err = cr.Run()
823         if api.CalledWith("container.state", "Complete") != nil {
824                 c.Check(err, IsNil)
825         }
826         if exitCode != 2 {
827                 c.Check(api.WasSetRunning, Equals, true)
828                 c.Check(api.Content[api.Calls-2]["container"].(arvadosclient.Dict)["log"], NotNil)
829         }
830
831         if err != nil {
832                 for k, v := range api.Logs {
833                         c.Log(k)
834                         c.Log(v.String())
835                 }
836         }
837
838         return
839 }
840
841 func (s *TestSuite) TestFullRunHello(c *C) {
842         api, _, _ := s.fullRunHelper(c, `{
843     "command": ["echo", "hello world"],
844     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
845     "cwd": ".",
846     "environment": {},
847     "mounts": {"/tmp": {"kind": "tmp"} },
848     "output_path": "/tmp",
849     "priority": 1,
850         "runtime_constraints": {}
851 }`, nil, 0, func(t *TestDockerClient) {
852                 t.logWriter.Write(dockerLog(1, "hello world\n"))
853                 t.logWriter.Close()
854         })
855
856         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
857         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
858         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
859
860 }
861
862 func (s *TestSuite) TestRunTimeExceeded(c *C) {
863         api, _, _ := s.fullRunHelper(c, `{
864     "command": ["sleep", "3"],
865     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
866     "cwd": ".",
867     "environment": {},
868     "mounts": {"/tmp": {"kind": "tmp"} },
869     "output_path": "/tmp",
870     "priority": 1,
871         "runtime_constraints": {},
872         "scheduling_parameters":{"max_run_time": 1}
873 }`, nil, 0, func(t *TestDockerClient) {
874                 time.Sleep(3 * time.Second)
875                 t.logWriter.Close()
876         })
877
878         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
879         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*maximum run time exceeded.*")
880 }
881
882 func (s *TestSuite) TestContainerWaitFails(c *C) {
883         api, _, _ := s.fullRunHelper(c, `{
884     "command": ["sleep", "3"],
885     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
886     "cwd": ".",
887     "mounts": {"/tmp": {"kind": "tmp"} },
888     "output_path": "/tmp",
889     "priority": 1
890 }`, nil, 0, func(t *TestDockerClient) {
891                 t.ctrExited = true
892                 time.Sleep(10 * time.Second)
893                 t.logWriter.Close()
894         })
895
896         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
897         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Container is not running.*")
898 }
899
900 func (s *TestSuite) TestCrunchstat(c *C) {
901         api, _, _ := s.fullRunHelper(c, `{
902                 "command": ["sleep", "1"],
903                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
904                 "cwd": ".",
905                 "environment": {},
906                 "mounts": {"/tmp": {"kind": "tmp"} },
907                 "output_path": "/tmp",
908                 "priority": 1,
909                 "runtime_constraints": {}
910         }`, nil, 0, func(t *TestDockerClient) {
911                 time.Sleep(time.Second)
912                 t.logWriter.Close()
913         })
914
915         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
916         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
917
918         // We didn't actually start a container, so crunchstat didn't
919         // find accounting files and therefore didn't log any stats.
920         // It should have logged a "can't find accounting files"
921         // message after one poll interval, though, so we can confirm
922         // it's alive:
923         c.Assert(api.Logs["crunchstat"], NotNil)
924         c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
925
926         // The "files never appeared" log assures us that we called
927         // (*crunchstat.Reporter)Stop(), and that we set it up with
928         // the correct container ID "abcde":
929         c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files never appeared for abcde\n`)
930 }
931
932 func (s *TestSuite) TestNodeInfoLog(c *C) {
933         os.Setenv("SLURMD_NODENAME", "compute2")
934         api, _, _ := s.fullRunHelper(c, `{
935                 "command": ["sleep", "1"],
936                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
937                 "cwd": ".",
938                 "environment": {},
939                 "mounts": {"/tmp": {"kind": "tmp"} },
940                 "output_path": "/tmp",
941                 "priority": 1,
942                 "runtime_constraints": {}
943         }`, nil, 0,
944                 func(t *TestDockerClient) {
945                         time.Sleep(time.Second)
946                         t.logWriter.Close()
947                 })
948
949         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
950         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
951
952         c.Assert(api.Logs["node"], NotNil)
953         json := api.Logs["node"].String()
954         c.Check(json, Matches, `(?ms).*"uuid": *"zzzzz-7ekkf-2z3mc76g2q73aio".*`)
955         c.Check(json, Matches, `(?ms).*"total_cpu_cores": *16.*`)
956         c.Check(json, Not(Matches), `(?ms).*"info":.*`)
957
958         c.Assert(api.Logs["node-info"], NotNil)
959         json = api.Logs["node-info"].String()
960         c.Check(json, Matches, `(?ms).*Host Information.*`)
961         c.Check(json, Matches, `(?ms).*CPU Information.*`)
962         c.Check(json, Matches, `(?ms).*Memory Information.*`)
963         c.Check(json, Matches, `(?ms).*Disk Space.*`)
964         c.Check(json, Matches, `(?ms).*Disk INodes.*`)
965 }
966
967 func (s *TestSuite) TestContainerRecordLog(c *C) {
968         api, _, _ := s.fullRunHelper(c, `{
969                 "command": ["sleep", "1"],
970                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
971                 "cwd": ".",
972                 "environment": {},
973                 "mounts": {"/tmp": {"kind": "tmp"} },
974                 "output_path": "/tmp",
975                 "priority": 1,
976                 "runtime_constraints": {}
977         }`, nil, 0,
978                 func(t *TestDockerClient) {
979                         time.Sleep(time.Second)
980                         t.logWriter.Close()
981                 })
982
983         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
984         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
985
986         c.Assert(api.Logs["container"], NotNil)
987         c.Check(api.Logs["container"].String(), Matches, `(?ms).*container_image.*`)
988 }
989
990 func (s *TestSuite) TestFullRunStderr(c *C) {
991         api, _, _ := s.fullRunHelper(c, `{
992     "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
993     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
994     "cwd": ".",
995     "environment": {},
996     "mounts": {"/tmp": {"kind": "tmp"} },
997     "output_path": "/tmp",
998     "priority": 1,
999     "runtime_constraints": {}
1000 }`, nil, 1, func(t *TestDockerClient) {
1001                 t.logWriter.Write(dockerLog(1, "hello\n"))
1002                 t.logWriter.Write(dockerLog(2, "world\n"))
1003                 t.logWriter.Close()
1004         })
1005
1006         final := api.CalledWith("container.state", "Complete")
1007         c.Assert(final, NotNil)
1008         c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1009         c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1010
1011         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
1012         c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
1013 }
1014
1015 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
1016         api, _, _ := s.fullRunHelper(c, `{
1017     "command": ["pwd"],
1018     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1019     "cwd": ".",
1020     "environment": {},
1021     "mounts": {"/tmp": {"kind": "tmp"} },
1022     "output_path": "/tmp",
1023     "priority": 1,
1024     "runtime_constraints": {}
1025 }`, nil, 0, func(t *TestDockerClient) {
1026                 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
1027                 t.logWriter.Close()
1028         })
1029
1030         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1031         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1032         c.Log(api.Logs["stdout"])
1033         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
1034 }
1035
1036 func (s *TestSuite) TestFullRunSetCwd(c *C) {
1037         api, _, _ := s.fullRunHelper(c, `{
1038     "command": ["pwd"],
1039     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1040     "cwd": "/bin",
1041     "environment": {},
1042     "mounts": {"/tmp": {"kind": "tmp"} },
1043     "output_path": "/tmp",
1044     "priority": 1,
1045     "runtime_constraints": {}
1046 }`, nil, 0, func(t *TestDockerClient) {
1047                 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
1048                 t.logWriter.Close()
1049         })
1050
1051         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1052         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1053         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
1054 }
1055
1056 func (s *TestSuite) TestStopOnSignal(c *C) {
1057         s.testStopContainer(c, func(cr *ContainerRunner) {
1058                 go func() {
1059                         for !s.docker.calledWait {
1060                                 time.Sleep(time.Millisecond)
1061                         }
1062                         cr.SigChan <- syscall.SIGINT
1063                 }()
1064         })
1065 }
1066
1067 func (s *TestSuite) TestStopOnArvMountDeath(c *C) {
1068         s.testStopContainer(c, func(cr *ContainerRunner) {
1069                 cr.ArvMountExit = make(chan error)
1070                 go func() {
1071                         cr.ArvMountExit <- exec.Command("true").Run()
1072                         close(cr.ArvMountExit)
1073                 }()
1074         })
1075 }
1076
1077 func (s *TestSuite) testStopContainer(c *C, setup func(cr *ContainerRunner)) {
1078         record := `{
1079     "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
1080     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1081     "cwd": ".",
1082     "environment": {},
1083     "mounts": {"/tmp": {"kind": "tmp"} },
1084     "output_path": "/tmp",
1085     "priority": 1,
1086     "runtime_constraints": {}
1087 }`
1088
1089         rec := arvados.Container{}
1090         err := json.Unmarshal([]byte(record), &rec)
1091         c.Check(err, IsNil)
1092
1093         s.docker.fn = func(t *TestDockerClient) {
1094                 <-t.stop
1095                 t.logWriter.Write(dockerLog(1, "foo\n"))
1096                 t.logWriter.Close()
1097         }
1098         s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
1099
1100         api := &ArvTestClient{Container: rec}
1101         kc := &KeepTestClient{}
1102         defer kc.Close()
1103         cr, err := NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1104         c.Assert(err, IsNil)
1105         cr.RunArvMount = func([]string, string) (*exec.Cmd, error) { return nil, nil }
1106         cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1107                 return &ArvTestClient{}, &KeepTestClient{}, nil, nil
1108         }
1109         setup(cr)
1110
1111         done := make(chan error)
1112         go func() {
1113                 done <- cr.Run()
1114         }()
1115         select {
1116         case <-time.After(20 * time.Second):
1117                 pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
1118                 c.Fatal("timed out")
1119         case err = <-done:
1120                 c.Check(err, IsNil)
1121         }
1122         for k, v := range api.Logs {
1123                 c.Log(k)
1124                 c.Log(v.String())
1125         }
1126
1127         c.Check(api.CalledWith("container.log", nil), NotNil)
1128         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1129         c.Check(api.Logs["stdout"].String(), Matches, "(?ms).*foo\n$")
1130 }
1131
1132 func (s *TestSuite) TestFullRunSetEnv(c *C) {
1133         api, _, _ := s.fullRunHelper(c, `{
1134     "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1135     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1136     "cwd": "/bin",
1137     "environment": {"FROBIZ": "bilbo"},
1138     "mounts": {"/tmp": {"kind": "tmp"} },
1139     "output_path": "/tmp",
1140     "priority": 1,
1141     "runtime_constraints": {}
1142 }`, nil, 0, func(t *TestDockerClient) {
1143                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1144                 t.logWriter.Close()
1145         })
1146
1147         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1148         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1149         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)
1150 }
1151
1152 type ArvMountCmdLine struct {
1153         Cmd   []string
1154         token string
1155 }
1156
1157 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
1158         am.Cmd = c
1159         am.token = token
1160         return nil, nil
1161 }
1162
1163 func stubCert(temp string) string {
1164         path := temp + "/ca-certificates.crt"
1165         crt, _ := os.Create(path)
1166         crt.Close()
1167         arvadosclient.CertFiles = []string{path}
1168         return path
1169 }
1170
1171 func (s *TestSuite) TestSetupMounts(c *C) {
1172         api := &ArvTestClient{}
1173         kc := &KeepTestClient{}
1174         defer kc.Close()
1175         cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1176         c.Assert(err, IsNil)
1177         am := &ArvMountCmdLine{}
1178         cr.RunArvMount = am.ArvMountTest
1179         cr.ContainerArvClient = &ArvTestClient{}
1180         cr.ContainerKeepClient = &KeepTestClient{}
1181
1182         realTemp, err := ioutil.TempDir("", "crunchrun_test1-")
1183         c.Assert(err, IsNil)
1184         certTemp, err := ioutil.TempDir("", "crunchrun_test2-")
1185         c.Assert(err, IsNil)
1186         stubCertPath := stubCert(certTemp)
1187
1188         cr.parentTemp = realTemp
1189
1190         defer os.RemoveAll(realTemp)
1191         defer os.RemoveAll(certTemp)
1192
1193         i := 0
1194         cr.MkTempDir = func(_ string, prefix string) (string, error) {
1195                 i++
1196                 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
1197                 err := os.Mkdir(d, os.ModePerm)
1198                 if err != nil && strings.Contains(err.Error(), ": file exists") {
1199                         // Test case must have pre-populated the tempdir
1200                         err = nil
1201                 }
1202                 return d, err
1203         }
1204
1205         checkEmpty := func() {
1206                 // Should be deleted.
1207                 _, err := os.Stat(realTemp)
1208                 c.Assert(os.IsNotExist(err), Equals, true)
1209
1210                 // Now recreate it for the next test.
1211                 c.Assert(os.Mkdir(realTemp, 0777), IsNil)
1212         }
1213
1214         {
1215                 i = 0
1216                 cr.ArvMountPoint = ""
1217                 cr.Container.Mounts = make(map[string]arvados.Mount)
1218                 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1219                 cr.Container.OutputPath = "/tmp"
1220                 cr.statInterval = 5 * time.Second
1221                 err := cr.SetupMounts()
1222                 c.Check(err, IsNil)
1223                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1224                         "--read-write", "--crunchstat-interval=5",
1225                         "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1226                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp"})
1227                 os.RemoveAll(cr.ArvMountPoint)
1228                 cr.CleanupDirs()
1229                 checkEmpty()
1230         }
1231
1232         {
1233                 i = 0
1234                 cr.ArvMountPoint = ""
1235                 cr.Container.Mounts = make(map[string]arvados.Mount)
1236                 cr.Container.Mounts["/out"] = arvados.Mount{Kind: "tmp"}
1237                 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1238                 cr.Container.OutputPath = "/out"
1239
1240                 err := cr.SetupMounts()
1241                 c.Check(err, IsNil)
1242                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1243                         "--read-write", "--crunchstat-interval=5",
1244                         "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1245                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/out", realTemp + "/tmp3:/tmp"})
1246                 os.RemoveAll(cr.ArvMountPoint)
1247                 cr.CleanupDirs()
1248                 checkEmpty()
1249         }
1250
1251         {
1252                 i = 0
1253                 cr.ArvMountPoint = ""
1254                 cr.Container.Mounts = make(map[string]arvados.Mount)
1255                 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1256                 cr.Container.OutputPath = "/tmp"
1257
1258                 apiflag := true
1259                 cr.Container.RuntimeConstraints.API = &apiflag
1260
1261                 err := cr.SetupMounts()
1262                 c.Check(err, IsNil)
1263                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1264                         "--read-write", "--crunchstat-interval=5",
1265                         "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1266                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", stubCertPath + ":/etc/arvados/ca-certificates.crt:ro"})
1267                 os.RemoveAll(cr.ArvMountPoint)
1268                 cr.CleanupDirs()
1269                 checkEmpty()
1270
1271                 apiflag = false
1272         }
1273
1274         {
1275                 i = 0
1276                 cr.ArvMountPoint = ""
1277                 cr.Container.Mounts = map[string]arvados.Mount{
1278                         "/keeptmp": {Kind: "collection", Writable: true},
1279                 }
1280                 cr.Container.OutputPath = "/keeptmp"
1281
1282                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1283
1284                 err := cr.SetupMounts()
1285                 c.Check(err, IsNil)
1286                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1287                         "--read-write", "--crunchstat-interval=5",
1288                         "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1289                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/tmp0:/keeptmp"})
1290                 os.RemoveAll(cr.ArvMountPoint)
1291                 cr.CleanupDirs()
1292                 checkEmpty()
1293         }
1294
1295         {
1296                 i = 0
1297                 cr.ArvMountPoint = ""
1298                 cr.Container.Mounts = map[string]arvados.Mount{
1299                         "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1300                         "/keepout": {Kind: "collection", Writable: true},
1301                 }
1302                 cr.Container.OutputPath = "/keepout"
1303
1304                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1305                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1306
1307                 err := cr.SetupMounts()
1308                 c.Check(err, IsNil)
1309                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1310                         "--read-write", "--crunchstat-interval=5",
1311                         "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1312                 sort.StringSlice(cr.Binds).Sort()
1313                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1314                         realTemp + "/keep1/tmp0:/keepout"})
1315                 os.RemoveAll(cr.ArvMountPoint)
1316                 cr.CleanupDirs()
1317                 checkEmpty()
1318         }
1319
1320         {
1321                 i = 0
1322                 cr.ArvMountPoint = ""
1323                 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
1324                 cr.Container.Mounts = map[string]arvados.Mount{
1325                         "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1326                         "/keepout": {Kind: "collection", Writable: true},
1327                 }
1328                 cr.Container.OutputPath = "/keepout"
1329
1330                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1331                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1332
1333                 err := cr.SetupMounts()
1334                 c.Check(err, IsNil)
1335                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1336                         "--read-write", "--crunchstat-interval=5",
1337                         "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1338                 sort.StringSlice(cr.Binds).Sort()
1339                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1340                         realTemp + "/keep1/tmp0:/keepout"})
1341                 os.RemoveAll(cr.ArvMountPoint)
1342                 cr.CleanupDirs()
1343                 checkEmpty()
1344         }
1345
1346         for _, test := range []struct {
1347                 in  interface{}
1348                 out string
1349         }{
1350                 {in: "foo", out: `"foo"`},
1351                 {in: nil, out: `null`},
1352                 {in: map[string]int64{"foo": 123456789123456789}, out: `{"foo":123456789123456789}`},
1353         } {
1354                 i = 0
1355                 cr.ArvMountPoint = ""
1356                 cr.Container.Mounts = map[string]arvados.Mount{
1357                         "/mnt/test.json": {Kind: "json", Content: test.in},
1358                 }
1359                 err := cr.SetupMounts()
1360                 c.Check(err, IsNil)
1361                 sort.StringSlice(cr.Binds).Sort()
1362                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/json2/mountdata.json:/mnt/test.json:ro"})
1363                 content, err := ioutil.ReadFile(realTemp + "/json2/mountdata.json")
1364                 c.Check(err, IsNil)
1365                 c.Check(content, DeepEquals, []byte(test.out))
1366                 os.RemoveAll(cr.ArvMountPoint)
1367                 cr.CleanupDirs()
1368                 checkEmpty()
1369         }
1370
1371         for _, test := range []struct {
1372                 in  interface{}
1373                 out string
1374         }{
1375                 {in: "foo", out: `foo`},
1376                 {in: nil, out: "error"},
1377                 {in: map[string]int64{"foo": 123456789123456789}, out: "error"},
1378         } {
1379                 i = 0
1380                 cr.ArvMountPoint = ""
1381                 cr.Container.Mounts = map[string]arvados.Mount{
1382                         "/mnt/test.txt": {Kind: "text", Content: test.in},
1383                 }
1384                 err := cr.SetupMounts()
1385                 if test.out == "error" {
1386                         c.Check(err.Error(), Equals, "content for mount \"/mnt/test.txt\" must be a string")
1387                 } else {
1388                         c.Check(err, IsNil)
1389                         sort.StringSlice(cr.Binds).Sort()
1390                         c.Check(cr.Binds, DeepEquals, []string{realTemp + "/text2/mountdata.text:/mnt/test.txt:ro"})
1391                         content, err := ioutil.ReadFile(realTemp + "/text2/mountdata.text")
1392                         c.Check(err, IsNil)
1393                         c.Check(content, DeepEquals, []byte(test.out))
1394                 }
1395                 os.RemoveAll(cr.ArvMountPoint)
1396                 cr.CleanupDirs()
1397                 checkEmpty()
1398         }
1399
1400         // Read-only mount points are allowed underneath output_dir mount point
1401         {
1402                 i = 0
1403                 cr.ArvMountPoint = ""
1404                 cr.Container.Mounts = make(map[string]arvados.Mount)
1405                 cr.Container.Mounts = map[string]arvados.Mount{
1406                         "/tmp":     {Kind: "tmp"},
1407                         "/tmp/foo": {Kind: "collection"},
1408                 }
1409                 cr.Container.OutputPath = "/tmp"
1410
1411                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1412
1413                 err := cr.SetupMounts()
1414                 c.Check(err, IsNil)
1415                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1416                         "--read-write", "--crunchstat-interval=5",
1417                         "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1418                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", realTemp + "/keep1/tmp0:/tmp/foo:ro"})
1419                 os.RemoveAll(cr.ArvMountPoint)
1420                 cr.CleanupDirs()
1421                 checkEmpty()
1422         }
1423
1424         // Writable mount points copied to output_dir mount point
1425         {
1426                 i = 0
1427                 cr.ArvMountPoint = ""
1428                 cr.Container.Mounts = make(map[string]arvados.Mount)
1429                 cr.Container.Mounts = map[string]arvados.Mount{
1430                         "/tmp": {Kind: "tmp"},
1431                         "/tmp/foo": {Kind: "collection",
1432                                 PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53",
1433                                 Writable:         true},
1434                         "/tmp/bar": {Kind: "collection",
1435                                 PortableDataHash: "59389a8f9ee9d399be35462a0f92541d+53",
1436                                 Path:             "baz",
1437                                 Writable:         true},
1438                 }
1439                 cr.Container.OutputPath = "/tmp"
1440
1441                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1442                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz", os.ModePerm)
1443
1444                 rf, _ := os.Create(realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz/quux")
1445                 rf.Write([]byte("bar"))
1446                 rf.Close()
1447
1448                 err := cr.SetupMounts()
1449                 c.Check(err, IsNil)
1450                 _, err = os.Stat(cr.HostOutputDir + "/foo")
1451                 c.Check(err, IsNil)
1452                 _, err = os.Stat(cr.HostOutputDir + "/bar/quux")
1453                 c.Check(err, IsNil)
1454                 os.RemoveAll(cr.ArvMountPoint)
1455                 cr.CleanupDirs()
1456                 checkEmpty()
1457         }
1458
1459         // Only mount points of kind 'collection' are allowed underneath output_dir mount point
1460         {
1461                 i = 0
1462                 cr.ArvMountPoint = ""
1463                 cr.Container.Mounts = make(map[string]arvados.Mount)
1464                 cr.Container.Mounts = map[string]arvados.Mount{
1465                         "/tmp":     {Kind: "tmp"},
1466                         "/tmp/foo": {Kind: "tmp"},
1467                 }
1468                 cr.Container.OutputPath = "/tmp"
1469
1470                 err := cr.SetupMounts()
1471                 c.Check(err, NotNil)
1472                 c.Check(err, ErrorMatches, `Only mount points of kind 'collection', 'text' or 'json' are supported underneath the output_path.*`)
1473                 os.RemoveAll(cr.ArvMountPoint)
1474                 cr.CleanupDirs()
1475                 checkEmpty()
1476         }
1477
1478         // Only mount point of kind 'collection' is allowed for stdin
1479         {
1480                 i = 0
1481                 cr.ArvMountPoint = ""
1482                 cr.Container.Mounts = make(map[string]arvados.Mount)
1483                 cr.Container.Mounts = map[string]arvados.Mount{
1484                         "stdin": {Kind: "tmp"},
1485                 }
1486
1487                 err := cr.SetupMounts()
1488                 c.Check(err, NotNil)
1489                 c.Check(err, ErrorMatches, `Unsupported mount kind 'tmp' for stdin.*`)
1490                 os.RemoveAll(cr.ArvMountPoint)
1491                 cr.CleanupDirs()
1492                 checkEmpty()
1493         }
1494
1495         // git_tree mounts
1496         {
1497                 i = 0
1498                 cr.ArvMountPoint = ""
1499                 (*GitMountSuite)(nil).useTestGitServer(c)
1500                 cr.token = arvadostest.ActiveToken
1501                 cr.Container.Mounts = make(map[string]arvados.Mount)
1502                 cr.Container.Mounts = map[string]arvados.Mount{
1503                         "/tip": {
1504                                 Kind:   "git_tree",
1505                                 UUID:   arvadostest.Repository2UUID,
1506                                 Commit: "fd3531f42995344f36c30b79f55f27b502f3d344",
1507                                 Path:   "/",
1508                         },
1509                         "/non-tip": {
1510                                 Kind:   "git_tree",
1511                                 UUID:   arvadostest.Repository2UUID,
1512                                 Commit: "5ebfab0522851df01fec11ec55a6d0f4877b542e",
1513                                 Path:   "/",
1514                         },
1515                 }
1516                 cr.Container.OutputPath = "/tmp"
1517
1518                 err := cr.SetupMounts()
1519                 c.Check(err, IsNil)
1520
1521                 // dirMap[mountpoint] == tmpdir
1522                 dirMap := make(map[string]string)
1523                 for _, bind := range cr.Binds {
1524                         tokens := strings.Split(bind, ":")
1525                         dirMap[tokens[1]] = tokens[0]
1526
1527                         if cr.Container.Mounts[tokens[1]].Writable {
1528                                 c.Check(len(tokens), Equals, 2)
1529                         } else {
1530                                 c.Check(len(tokens), Equals, 3)
1531                                 c.Check(tokens[2], Equals, "ro")
1532                         }
1533                 }
1534
1535                 data, err := ioutil.ReadFile(dirMap["/tip"] + "/dir1/dir2/file with mode 0644")
1536                 c.Check(err, IsNil)
1537                 c.Check(string(data), Equals, "\000\001\002\003")
1538                 _, err = ioutil.ReadFile(dirMap["/tip"] + "/file only on testbranch")
1539                 c.Check(err, FitsTypeOf, &os.PathError{})
1540                 c.Check(os.IsNotExist(err), Equals, true)
1541
1542                 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/dir1/dir2/file with mode 0644")
1543                 c.Check(err, IsNil)
1544                 c.Check(string(data), Equals, "\000\001\002\003")
1545                 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/file only on testbranch")
1546                 c.Check(err, IsNil)
1547                 c.Check(string(data), Equals, "testfile\n")
1548
1549                 cr.CleanupDirs()
1550                 checkEmpty()
1551         }
1552 }
1553
1554 func (s *TestSuite) TestStdout(c *C) {
1555         helperRecord := `{
1556                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1557                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1558                 "cwd": "/bin",
1559                 "environment": {"FROBIZ": "bilbo"},
1560                 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1561                 "output_path": "/tmp",
1562                 "priority": 1,
1563                 "runtime_constraints": {}
1564         }`
1565
1566         api, cr, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1567                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1568                 t.logWriter.Close()
1569         })
1570
1571         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1572         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1573         c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1574 }
1575
1576 // Used by the TestStdoutWithWrongPath*()
1577 func (s *TestSuite) stdoutErrorRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, err error) {
1578         rec := arvados.Container{}
1579         err = json.Unmarshal([]byte(record), &rec)
1580         c.Check(err, IsNil)
1581
1582         s.docker.fn = fn
1583         s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
1584
1585         api = &ArvTestClient{Container: rec}
1586         kc := &KeepTestClient{}
1587         defer kc.Close()
1588         cr, err = NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1589         c.Assert(err, IsNil)
1590         am := &ArvMountCmdLine{}
1591         cr.RunArvMount = am.ArvMountTest
1592         cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1593                 return &ArvTestClient{}, &KeepTestClient{}, nil, nil
1594         }
1595
1596         err = cr.Run()
1597         return
1598 }
1599
1600 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1601         _, _, err := s.stdoutErrorRunHelper(c, `{
1602     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1603     "output_path": "/tmp"
1604 }`, func(t *TestDockerClient) {})
1605
1606         c.Check(err, NotNil)
1607         c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
1608 }
1609
1610 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1611         _, _, err := s.stdoutErrorRunHelper(c, `{
1612     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1613     "output_path": "/tmp"
1614 }`, func(t *TestDockerClient) {})
1615
1616         c.Check(err, NotNil)
1617         c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'tmp' for stdout"), Equals, true)
1618 }
1619
1620 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1621         _, _, err := s.stdoutErrorRunHelper(c, `{
1622     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1623     "output_path": "/tmp"
1624 }`, func(t *TestDockerClient) {})
1625
1626         c.Check(err, NotNil)
1627         c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'collection' for stdout"), Equals, true)
1628 }
1629
1630 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1631         defer os.Setenv("ARVADOS_API_HOST", os.Getenv("ARVADOS_API_HOST"))
1632         os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1633         api, _, _ := s.fullRunHelper(c, `{
1634     "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1635     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1636     "cwd": "/bin",
1637     "environment": {},
1638     "mounts": {"/tmp": {"kind": "tmp"} },
1639     "output_path": "/tmp",
1640     "priority": 1,
1641     "runtime_constraints": {"API": true}
1642 }`, nil, 0, func(t *TestDockerClient) {
1643                 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
1644                 t.logWriter.Close()
1645         })
1646
1647         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1648         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1649         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "test.arvados.org\n"), Equals, true)
1650         c.Check(api.CalledWith("container.output", "d41d8cd98f00b204e9800998ecf8427e+0"), NotNil)
1651 }
1652
1653 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1654         defer os.Setenv("ARVADOS_API_HOST", os.Getenv("ARVADOS_API_HOST"))
1655         os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1656         api, _, _ := s.fullRunHelper(c, `{
1657     "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1658     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1659     "cwd": "/bin",
1660     "environment": {},
1661     "mounts": {"/tmp": {"kind": "tmp"} },
1662     "output_path": "/tmp",
1663     "priority": 1,
1664     "runtime_constraints": {"API": true}
1665 }`, nil, 0, func(t *TestDockerClient) {
1666                 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
1667                 t.logWriter.Close()
1668         })
1669
1670         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1671         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1672         c.Check(api.CalledWith("container.output", "d4ab34d3d4f8a72f5c4973051ae69fab+122"), NotNil)
1673 }
1674
1675 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1676         helperRecord := `{
1677                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1678                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1679                 "cwd": "/bin",
1680                 "environment": {"FROBIZ": "bilbo"},
1681                 "mounts": {
1682         "/tmp": {"kind": "tmp"},
1683         "/tmp/foo": {"kind": "collection",
1684                      "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1685                      "exclude_from_output": true
1686         },
1687         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1688     },
1689                 "output_path": "/tmp",
1690                 "priority": 1,
1691                 "runtime_constraints": {}
1692         }`
1693
1694         extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1695
1696         api, cr, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1697                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1698                 t.logWriter.Close()
1699         })
1700
1701         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1702         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1703         c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1704 }
1705
1706 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1707         helperRecord := `{
1708                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1709                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1710                 "cwd": "/bin",
1711                 "environment": {"FROBIZ": "bilbo"},
1712                 "mounts": {
1713         "/tmp": {"kind": "tmp"},
1714         "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1715         "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1716         "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1717         "/tmp/foo/baz/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1718         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1719     },
1720                 "output_path": "/tmp",
1721                 "priority": 1,
1722                 "runtime_constraints": {}
1723         }`
1724
1725         extraMounts := []string{
1726                 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1727                 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1728                 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1729         }
1730
1731         api, runner, realtemp := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1732                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1733                 t.logWriter.Close()
1734         })
1735
1736         c.Check(runner.Binds, DeepEquals, []string{realtemp + "/tmp2:/tmp",
1737                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt:/tmp/foo/bar:ro",
1738                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt:/tmp/foo/baz/sub2file2:ro",
1739                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1:/tmp/foo/sub1:ro",
1740                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt:/tmp/foo/sub1file2:ro",
1741         })
1742
1743         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1744         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1745         for _, v := range api.Content {
1746                 if v["collection"] != nil {
1747                         c.Check(v["ensure_unique_name"], Equals, true)
1748                         collection := v["collection"].(arvadosclient.Dict)
1749                         if strings.Index(collection["name"].(string), "output") == 0 {
1750                                 manifest := collection["manifest_text"].(string)
1751
1752                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1753 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:bar 36:18:sub1file2
1754 ./foo/baz 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2
1755 ./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1756 ./foo/sub1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1757 `)
1758                         }
1759                 }
1760         }
1761 }
1762
1763 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
1764         helperRecord := `{
1765                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1766                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1767                 "cwd": "/bin",
1768                 "environment": {"FROBIZ": "bilbo"},
1769                 "mounts": {
1770         "/tmp": {"kind": "tmp"},
1771         "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/subdir1/file2_in_subdir1.txt"},
1772         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1773     },
1774                 "output_path": "/tmp",
1775                 "priority": 1,
1776                 "runtime_constraints": {}
1777         }`
1778
1779         extraMounts := []string{
1780                 "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1781         }
1782
1783         api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1784                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1785                 t.logWriter.Close()
1786         })
1787
1788         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1789         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1790         for _, v := range api.Content {
1791                 if v["collection"] != nil {
1792                         collection := v["collection"].(arvadosclient.Dict)
1793                         if strings.Index(collection["name"].(string), "output") == 0 {
1794                                 manifest := collection["manifest_text"].(string)
1795
1796                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1797 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 10:17:bar
1798 `)
1799                         }
1800                 }
1801         }
1802 }
1803
1804 func (s *TestSuite) TestOutputError(c *C) {
1805         helperRecord := `{
1806                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1807                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1808                 "cwd": "/bin",
1809                 "environment": {"FROBIZ": "bilbo"},
1810                 "mounts": {
1811         "/tmp": {"kind": "tmp"}
1812     },
1813                 "output_path": "/tmp",
1814                 "priority": 1,
1815                 "runtime_constraints": {}
1816         }`
1817
1818         extraMounts := []string{}
1819
1820         api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1821                 os.Symlink("/etc/hosts", t.realTemp+"/tmp2/baz")
1822                 t.logWriter.Close()
1823         })
1824
1825         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1826 }
1827
1828 func (s *TestSuite) TestStdinCollectionMountPoint(c *C) {
1829         helperRecord := `{
1830                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1831                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1832                 "cwd": "/bin",
1833                 "environment": {"FROBIZ": "bilbo"},
1834                 "mounts": {
1835         "/tmp": {"kind": "tmp"},
1836         "stdin": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/file1_in_main.txt"},
1837         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1838     },
1839                 "output_path": "/tmp",
1840                 "priority": 1,
1841                 "runtime_constraints": {}
1842         }`
1843
1844         extraMounts := []string{
1845                 "b0def87f80dd594d4675809e83bd4f15+367/file1_in_main.txt",
1846         }
1847
1848         api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1849                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1850                 t.logWriter.Close()
1851         })
1852
1853         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1854         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1855         for _, v := range api.Content {
1856                 if v["collection"] != nil {
1857                         collection := v["collection"].(arvadosclient.Dict)
1858                         if strings.Index(collection["name"].(string), "output") == 0 {
1859                                 manifest := collection["manifest_text"].(string)
1860                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1861 `)
1862                         }
1863                 }
1864         }
1865 }
1866
1867 func (s *TestSuite) TestStdinJsonMountPoint(c *C) {
1868         helperRecord := `{
1869                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1870                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1871                 "cwd": "/bin",
1872                 "environment": {"FROBIZ": "bilbo"},
1873                 "mounts": {
1874         "/tmp": {"kind": "tmp"},
1875         "stdin": {"kind": "json", "content": "foo"},
1876         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1877     },
1878                 "output_path": "/tmp",
1879                 "priority": 1,
1880                 "runtime_constraints": {}
1881         }`
1882
1883         api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1884                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1885                 t.logWriter.Close()
1886         })
1887
1888         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1889         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1890         for _, v := range api.Content {
1891                 if v["collection"] != nil {
1892                         collection := v["collection"].(arvadosclient.Dict)
1893                         if strings.Index(collection["name"].(string), "output") == 0 {
1894                                 manifest := collection["manifest_text"].(string)
1895                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1896 `)
1897                         }
1898                 }
1899         }
1900 }
1901
1902 func (s *TestSuite) TestStderrMount(c *C) {
1903         api, cr, _ := s.fullRunHelper(c, `{
1904     "command": ["/bin/sh", "-c", "echo hello;exit 1"],
1905     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1906     "cwd": ".",
1907     "environment": {},
1908     "mounts": {"/tmp": {"kind": "tmp"},
1909                "stdout": {"kind": "file", "path": "/tmp/a/out.txt"},
1910                "stderr": {"kind": "file", "path": "/tmp/b/err.txt"}},
1911     "output_path": "/tmp",
1912     "priority": 1,
1913     "runtime_constraints": {}
1914 }`, nil, 1, func(t *TestDockerClient) {
1915                 t.logWriter.Write(dockerLog(1, "hello\n"))
1916                 t.logWriter.Write(dockerLog(2, "oops\n"))
1917                 t.logWriter.Close()
1918         })
1919
1920         final := api.CalledWith("container.state", "Complete")
1921         c.Assert(final, NotNil)
1922         c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1923         c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1924
1925         c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", "./a b1946ac92492d2347c6235b4d2611184+6 0:6:out.txt\n./b 38af5c54926b620264ab1501150cf189+5 0:5:err.txt\n"), NotNil)
1926 }
1927
1928 func (s *TestSuite) TestNumberRoundTrip(c *C) {
1929         kc := &KeepTestClient{}
1930         defer kc.Close()
1931         cr, err := NewContainerRunner(s.client, &ArvTestClient{callraw: true}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1932         c.Assert(err, IsNil)
1933         cr.fetchContainerRecord()
1934
1935         jsondata, err := json.Marshal(cr.Container.Mounts["/json"].Content)
1936
1937         c.Check(err, IsNil)
1938         c.Check(string(jsondata), Equals, `{"number":123456789123456789}`)
1939 }
1940
1941 func (s *TestSuite) TestFullBrokenDocker1(c *C) {
1942         tf, err := ioutil.TempFile("", "brokenNodeHook-")
1943         c.Assert(err, IsNil)
1944         defer os.Remove(tf.Name())
1945
1946         tf.Write([]byte(`#!/bin/sh
1947 exec echo killme
1948 `))
1949         tf.Close()
1950         os.Chmod(tf.Name(), 0700)
1951
1952         ech := tf.Name()
1953         brokenNodeHook = &ech
1954
1955         api, _, _ := s.fullRunHelper(c, `{
1956     "command": ["echo", "hello world"],
1957     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1958     "cwd": ".",
1959     "environment": {},
1960     "mounts": {"/tmp": {"kind": "tmp"} },
1961     "output_path": "/tmp",
1962     "priority": 1,
1963     "runtime_constraints": {}
1964 }`, nil, 2, func(t *TestDockerClient) {
1965                 t.logWriter.Write(dockerLog(1, "hello world\n"))
1966                 t.logWriter.Close()
1967         })
1968
1969         c.Check(api.CalledWith("container.state", "Queued"), NotNil)
1970         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1971         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Running broken node hook.*")
1972         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*killme.*")
1973
1974 }
1975
1976 func (s *TestSuite) TestFullBrokenDocker2(c *C) {
1977         ech := ""
1978         brokenNodeHook = &ech
1979
1980         api, _, _ := s.fullRunHelper(c, `{
1981     "command": ["echo", "hello world"],
1982     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1983     "cwd": ".",
1984     "environment": {},
1985     "mounts": {"/tmp": {"kind": "tmp"} },
1986     "output_path": "/tmp",
1987     "priority": 1,
1988     "runtime_constraints": {}
1989 }`, nil, 2, func(t *TestDockerClient) {
1990                 t.logWriter.Write(dockerLog(1, "hello world\n"))
1991                 t.logWriter.Close()
1992         })
1993
1994         c.Check(api.CalledWith("container.state", "Queued"), NotNil)
1995         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1996         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*No broken node hook.*")
1997 }
1998
1999 func (s *TestSuite) TestFullBrokenDocker3(c *C) {
2000         ech := ""
2001         brokenNodeHook = &ech
2002
2003         api, _, _ := s.fullRunHelper(c, `{
2004     "command": ["echo", "hello world"],
2005     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2006     "cwd": ".",
2007     "environment": {},
2008     "mounts": {"/tmp": {"kind": "tmp"} },
2009     "output_path": "/tmp",
2010     "priority": 1,
2011     "runtime_constraints": {}
2012 }`, nil, 3, func(t *TestDockerClient) {
2013                 t.logWriter.Write(dockerLog(1, "hello world\n"))
2014                 t.logWriter.Close()
2015         })
2016
2017         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2018         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
2019 }
2020
2021 func (s *TestSuite) TestBadCommand1(c *C) {
2022         ech := ""
2023         brokenNodeHook = &ech
2024
2025         api, _, _ := s.fullRunHelper(c, `{
2026     "command": ["echo", "hello world"],
2027     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2028     "cwd": ".",
2029     "environment": {},
2030     "mounts": {"/tmp": {"kind": "tmp"} },
2031     "output_path": "/tmp",
2032     "priority": 1,
2033     "runtime_constraints": {}
2034 }`, nil, 4, func(t *TestDockerClient) {
2035                 t.logWriter.Write(dockerLog(1, "hello world\n"))
2036                 t.logWriter.Close()
2037         })
2038
2039         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2040         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2041 }
2042
2043 func (s *TestSuite) TestBadCommand2(c *C) {
2044         ech := ""
2045         brokenNodeHook = &ech
2046
2047         api, _, _ := s.fullRunHelper(c, `{
2048     "command": ["echo", "hello world"],
2049     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2050     "cwd": ".",
2051     "environment": {},
2052     "mounts": {"/tmp": {"kind": "tmp"} },
2053     "output_path": "/tmp",
2054     "priority": 1,
2055     "runtime_constraints": {}
2056 }`, nil, 5, func(t *TestDockerClient) {
2057                 t.logWriter.Write(dockerLog(1, "hello world\n"))
2058                 t.logWriter.Close()
2059         })
2060
2061         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2062         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2063 }
2064
2065 func (s *TestSuite) TestBadCommand3(c *C) {
2066         ech := ""
2067         brokenNodeHook = &ech
2068
2069         api, _, _ := s.fullRunHelper(c, `{
2070     "command": ["echo", "hello world"],
2071     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2072     "cwd": ".",
2073     "environment": {},
2074     "mounts": {"/tmp": {"kind": "tmp"} },
2075     "output_path": "/tmp",
2076     "priority": 1,
2077     "runtime_constraints": {}
2078 }`, nil, 6, func(t *TestDockerClient) {
2079                 t.logWriter.Write(dockerLog(1, "hello world\n"))
2080                 t.logWriter.Close()
2081         })
2082
2083         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2084         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2085 }
2086
2087 func (s *TestSuite) TestSecretTextMountPoint(c *C) {
2088         // under normal mounts, gets captured in output, oops
2089         helperRecord := `{
2090                 "command": ["true"],
2091                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2092                 "cwd": "/bin",
2093                 "mounts": {
2094                     "/tmp": {"kind": "tmp"},
2095                     "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2096                 },
2097                 "secret_mounts": {
2098                 },
2099                 "output_path": "/tmp",
2100                 "priority": 1,
2101                 "runtime_constraints": {}
2102         }`
2103
2104         api, cr, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2105                 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2106                 c.Check(err, IsNil)
2107                 c.Check(content, DeepEquals, []byte("mypassword"))
2108                 t.logWriter.Close()
2109         })
2110
2111         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2112         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2113         c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), NotNil)
2114         c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ""), IsNil)
2115
2116         // under secret mounts, not captured in output
2117         helperRecord = `{
2118                 "command": ["true"],
2119                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2120                 "cwd": "/bin",
2121                 "mounts": {
2122                     "/tmp": {"kind": "tmp"}
2123                 },
2124                 "secret_mounts": {
2125                     "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2126                 },
2127                 "output_path": "/tmp",
2128                 "priority": 1,
2129                 "runtime_constraints": {}
2130         }`
2131
2132         api, cr, _ = s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2133                 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2134                 c.Check(err, IsNil)
2135                 c.Check(content, DeepEquals, []byte("mypassword"))
2136                 t.logWriter.Close()
2137         })
2138
2139         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2140         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2141         c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), IsNil)
2142         c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ""), NotNil)
2143 }
2144
2145 type FakeProcess struct {
2146         cmdLine []string
2147 }
2148
2149 func (fp FakeProcess) CmdlineSlice() ([]string, error) {
2150         return fp.cmdLine, nil
2151 }
2152
2153 func (s *TestSuite) helpCheckContainerd(c *C, lp func() ([]PsProcess, error)) error {
2154         kc := &KeepTestClient{}
2155         defer kc.Close()
2156         cr, err := NewContainerRunner(s.client, &ArvTestClient{callraw: true}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
2157         cr.checkContainerd = time.Duration(100 * time.Millisecond)
2158         c.Assert(err, IsNil)
2159         cr.ListProcesses = lp
2160
2161         s.docker.fn = func(t *TestDockerClient) {
2162                 time.Sleep(1 * time.Second)
2163                 t.logWriter.Close()
2164         }
2165
2166         err = cr.CreateContainer()
2167         c.Check(err, IsNil)
2168
2169         err = cr.StartContainer()
2170         c.Check(err, IsNil)
2171
2172         err = cr.WaitFinish()
2173         return err
2174
2175 }
2176
2177 func (s *TestSuite) TestCheckContainerdPresent(c *C) {
2178         err := s.helpCheckContainerd(c, func() ([]PsProcess, error) {
2179                 return []PsProcess{FakeProcess{[]string{"docker-containerd"}}}, nil
2180         })
2181         c.Check(err, IsNil)
2182 }
2183
2184 func (s *TestSuite) TestCheckContainerdMissing(c *C) {
2185         err := s.helpCheckContainerd(c, func() ([]PsProcess, error) {
2186                 return []PsProcess{FakeProcess{[]string{"abc"}}}, nil
2187         })
2188         c.Check(err, ErrorMatches, `'containerd' not found in process list.`)
2189 }