Merge branch '14259-pysdk-remote-block-copy'
[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) PutB(buf []byte) (string, int, error) {
379         client.Content = buf
380         return fmt.Sprintf("%x+%d", md5.Sum(buf), len(buf)), len(buf), nil
381 }
382
383 func (client *KeepTestClient) ReadAt(string, []byte, int) (int, error) {
384         return 0, errors.New("not implemented")
385 }
386
387 func (client *KeepTestClient) ClearBlockCache() {
388 }
389
390 func (client *KeepTestClient) Close() {
391         client.Content = nil
392 }
393
394 type FileWrapper struct {
395         io.ReadCloser
396         len int64
397 }
398
399 func (fw FileWrapper) Readdir(n int) ([]os.FileInfo, error) {
400         return nil, errors.New("not implemented")
401 }
402
403 func (fw FileWrapper) Seek(int64, int) (int64, error) {
404         return 0, errors.New("not implemented")
405 }
406
407 func (fw FileWrapper) Size() int64 {
408         return fw.len
409 }
410
411 func (fw FileWrapper) Stat() (os.FileInfo, error) {
412         return nil, errors.New("not implemented")
413 }
414
415 func (fw FileWrapper) Truncate(int64) error {
416         return errors.New("not implemented")
417 }
418
419 func (fw FileWrapper) Write([]byte) (int, error) {
420         return 0, errors.New("not implemented")
421 }
422
423 func (fw FileWrapper) Sync() error {
424         return errors.New("not implemented")
425 }
426
427 func (client *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
428         if filename == hwImageId+".tar" {
429                 rdr := ioutil.NopCloser(&bytes.Buffer{})
430                 client.Called = true
431                 return FileWrapper{rdr, 1321984}, nil
432         } else if filename == "/file1_in_main.txt" {
433                 rdr := ioutil.NopCloser(strings.NewReader("foo"))
434                 client.Called = true
435                 return FileWrapper{rdr, 3}, nil
436         }
437         return nil, nil
438 }
439
440 func (s *TestSuite) TestLoadImage(c *C) {
441         kc := &KeepTestClient{}
442         defer kc.Close()
443         cr, err := NewContainerRunner(s.client, &ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
444         c.Assert(err, IsNil)
445
446         _, err = cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
447         c.Check(err, IsNil)
448
449         _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
450         c.Check(err, NotNil)
451
452         cr.Container.ContainerImage = hwPDH
453
454         // (1) Test loading image from keep
455         c.Check(kc.Called, Equals, false)
456         c.Check(cr.ContainerConfig.Image, Equals, "")
457
458         err = cr.LoadImage()
459
460         c.Check(err, IsNil)
461         defer func() {
462                 cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
463         }()
464
465         c.Check(kc.Called, Equals, true)
466         c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
467
468         _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
469         c.Check(err, IsNil)
470
471         // (2) Test using image that's already loaded
472         kc.Called = false
473         cr.ContainerConfig.Image = ""
474
475         err = cr.LoadImage()
476         c.Check(err, IsNil)
477         c.Check(kc.Called, Equals, false)
478         c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
479
480 }
481
482 type ArvErrorTestClient struct{}
483
484 func (ArvErrorTestClient) Create(resourceType string,
485         parameters arvadosclient.Dict,
486         output interface{}) error {
487         return nil
488 }
489
490 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
491         return errors.New("ArvError")
492 }
493
494 func (ArvErrorTestClient) CallRaw(method, resourceType, uuid, action string,
495         parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
496         return nil, errors.New("ArvError")
497 }
498
499 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
500         return errors.New("ArvError")
501 }
502
503 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
504         return nil
505 }
506
507 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
508         return discoveryMap[key], nil
509 }
510
511 type KeepErrorTestClient struct {
512         KeepTestClient
513 }
514
515 func (*KeepErrorTestClient) ManifestFileReader(manifest.Manifest, string) (arvados.File, error) {
516         return nil, errors.New("KeepError")
517 }
518
519 func (*KeepErrorTestClient) PutB(buf []byte) (string, int, error) {
520         return "", 0, errors.New("KeepError")
521 }
522
523 type KeepReadErrorTestClient struct {
524         KeepTestClient
525 }
526
527 func (*KeepReadErrorTestClient) ReadAt(string, []byte, int) (int, error) {
528         return 0, errors.New("KeepError")
529 }
530
531 type ErrorReader struct {
532         FileWrapper
533 }
534
535 func (ErrorReader) Read(p []byte) (n int, err error) {
536         return 0, errors.New("ErrorReader")
537 }
538
539 func (ErrorReader) Seek(int64, int) (int64, error) {
540         return 0, errors.New("ErrorReader")
541 }
542
543 func (KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
544         return ErrorReader{}, nil
545 }
546
547 func (s *TestSuite) TestLoadImageArvError(c *C) {
548         // (1) Arvados error
549         kc := &KeepTestClient{}
550         defer kc.Close()
551         cr, err := NewContainerRunner(s.client, ArvErrorTestClient{}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
552         c.Assert(err, IsNil)
553         cr.Container.ContainerImage = hwPDH
554
555         err = cr.LoadImage()
556         c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
557 }
558
559 func (s *TestSuite) TestLoadImageKeepError(c *C) {
560         // (2) Keep error
561         cr, err := NewContainerRunner(s.client, &ArvTestClient{}, &KeepErrorTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
562         c.Assert(err, IsNil)
563         cr.Container.ContainerImage = hwPDH
564
565         err = cr.LoadImage()
566         c.Assert(err, NotNil)
567         c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
568 }
569
570 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
571         // (3) Collection doesn't contain image
572         cr, err := NewContainerRunner(s.client, &ArvTestClient{}, &KeepReadErrorTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
573         c.Assert(err, IsNil)
574         cr.Container.ContainerImage = otherPDH
575
576         err = cr.LoadImage()
577         c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
578 }
579
580 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
581         // (4) Collection doesn't contain image
582         cr, err := NewContainerRunner(s.client, &ArvTestClient{}, &KeepReadErrorTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
583         c.Assert(err, IsNil)
584         cr.Container.ContainerImage = hwPDH
585
586         err = cr.LoadImage()
587         c.Check(err, NotNil)
588 }
589
590 type ClosableBuffer struct {
591         bytes.Buffer
592 }
593
594 func (*ClosableBuffer) Close() error {
595         return nil
596 }
597
598 type TestLogs struct {
599         Stdout ClosableBuffer
600         Stderr ClosableBuffer
601 }
602
603 func (tl *TestLogs) NewTestLoggingWriter(logstr string) (io.WriteCloser, error) {
604         if logstr == "stdout" {
605                 return &tl.Stdout, nil
606         }
607         if logstr == "stderr" {
608                 return &tl.Stderr, nil
609         }
610         return nil, errors.New("???")
611 }
612
613 func dockerLog(fd byte, msg string) []byte {
614         by := []byte(msg)
615         header := make([]byte, 8+len(by))
616         header[0] = fd
617         header[7] = byte(len(by))
618         copy(header[8:], by)
619         return header
620 }
621
622 func (s *TestSuite) TestRunContainer(c *C) {
623         s.docker.fn = func(t *TestDockerClient) {
624                 t.logWriter.Write(dockerLog(1, "Hello world\n"))
625                 t.logWriter.Close()
626         }
627         kc := &KeepTestClient{}
628         defer kc.Close()
629         cr, err := NewContainerRunner(s.client, &ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
630         c.Assert(err, IsNil)
631
632         var logs TestLogs
633         cr.NewLogWriter = logs.NewTestLoggingWriter
634         cr.Container.ContainerImage = hwPDH
635         cr.Container.Command = []string{"./hw"}
636         err = cr.LoadImage()
637         c.Check(err, IsNil)
638
639         err = cr.CreateContainer()
640         c.Check(err, IsNil)
641
642         err = cr.StartContainer()
643         c.Check(err, IsNil)
644
645         err = cr.WaitFinish()
646         c.Check(err, IsNil)
647
648         c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
649         c.Check(logs.Stderr.String(), Equals, "")
650 }
651
652 func (s *TestSuite) TestCommitLogs(c *C) {
653         api := &ArvTestClient{}
654         kc := &KeepTestClient{}
655         defer kc.Close()
656         cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
657         c.Assert(err, IsNil)
658         cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
659
660         cr.CrunchLog.Print("Hello world!")
661         cr.CrunchLog.Print("Goodbye")
662         cr.finalState = "Complete"
663
664         err = cr.CommitLogs()
665         c.Check(err, IsNil)
666
667         c.Check(api.Calls, Equals, 2)
668         c.Check(api.Content[1]["ensure_unique_name"], Equals, true)
669         c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
670         c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
671         c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
672 }
673
674 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
675         api := &ArvTestClient{}
676         kc := &KeepTestClient{}
677         defer kc.Close()
678         cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
679         c.Assert(err, IsNil)
680
681         err = cr.UpdateContainerRunning()
682         c.Check(err, IsNil)
683
684         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
685 }
686
687 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
688         api := &ArvTestClient{}
689         kc := &KeepTestClient{}
690         defer kc.Close()
691         cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
692         c.Assert(err, IsNil)
693
694         cr.LogsPDH = new(string)
695         *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
696
697         cr.ExitCode = new(int)
698         *cr.ExitCode = 42
699         cr.finalState = "Complete"
700
701         err = cr.UpdateContainerFinal()
702         c.Check(err, IsNil)
703
704         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
705         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
706         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
707 }
708
709 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
710         api := &ArvTestClient{}
711         kc := &KeepTestClient{}
712         defer kc.Close()
713         cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
714         c.Assert(err, IsNil)
715         cr.cCancelled = true
716         cr.finalState = "Cancelled"
717
718         err = cr.UpdateContainerFinal()
719         c.Check(err, IsNil)
720
721         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
722         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
723         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
724 }
725
726 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
727 // dress rehearsal of the Run() function, starting from a JSON container record.
728 func (s *TestSuite) fullRunHelper(c *C, record string, extraMounts []string, exitCode int, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, realTemp string) {
729         rec := arvados.Container{}
730         err := json.Unmarshal([]byte(record), &rec)
731         c.Check(err, IsNil)
732
733         var sm struct {
734                 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
735         }
736         err = json.Unmarshal([]byte(record), &sm)
737         c.Check(err, IsNil)
738         secretMounts, err := json.Marshal(sm)
739         c.Logf("%s %q", sm, secretMounts)
740         c.Check(err, IsNil)
741
742         s.docker.exitCode = exitCode
743         s.docker.fn = fn
744         s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
745
746         api = &ArvTestClient{Container: rec}
747         s.docker.api = api
748         kc := &KeepTestClient{}
749         defer kc.Close()
750         cr, err = NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
751         c.Assert(err, IsNil)
752         s.runner = cr
753         cr.statInterval = 100 * time.Millisecond
754         cr.containerWatchdogInterval = time.Second
755         am := &ArvMountCmdLine{}
756         cr.RunArvMount = am.ArvMountTest
757
758         realTemp, err = ioutil.TempDir("", "crunchrun_test1-")
759         c.Assert(err, IsNil)
760         defer os.RemoveAll(realTemp)
761
762         s.docker.realTemp = realTemp
763
764         tempcount := 0
765         cr.MkTempDir = func(_ string, prefix string) (string, error) {
766                 tempcount++
767                 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, tempcount)
768                 err := os.Mkdir(d, os.ModePerm)
769                 if err != nil && strings.Contains(err.Error(), ": file exists") {
770                         // Test case must have pre-populated the tempdir
771                         err = nil
772                 }
773                 return d, err
774         }
775         cr.MkArvClient = func(token string) (IArvadosClient, error) {
776                 return &ArvTestClient{secretMounts: secretMounts}, nil
777         }
778
779         if extraMounts != nil && len(extraMounts) > 0 {
780                 err := cr.SetupArvMountPoint("keep")
781                 c.Check(err, IsNil)
782
783                 for _, m := range extraMounts {
784                         os.MkdirAll(cr.ArvMountPoint+"/by_id/"+m, os.ModePerm)
785                 }
786         }
787
788         err = cr.Run()
789         if api.CalledWith("container.state", "Complete") != nil {
790                 c.Check(err, IsNil)
791         }
792         if exitCode != 2 {
793                 c.Check(api.WasSetRunning, Equals, true)
794                 c.Check(api.Content[api.Calls-2]["container"].(arvadosclient.Dict)["log"], NotNil)
795         }
796
797         if err != nil {
798                 for k, v := range api.Logs {
799                         c.Log(k)
800                         c.Log(v.String())
801                 }
802         }
803
804         return
805 }
806
807 func (s *TestSuite) TestFullRunHello(c *C) {
808         api, _, _ := s.fullRunHelper(c, `{
809     "command": ["echo", "hello world"],
810     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
811     "cwd": ".",
812     "environment": {},
813     "mounts": {"/tmp": {"kind": "tmp"} },
814     "output_path": "/tmp",
815     "priority": 1,
816         "runtime_constraints": {}
817 }`, nil, 0, func(t *TestDockerClient) {
818                 t.logWriter.Write(dockerLog(1, "hello world\n"))
819                 t.logWriter.Close()
820         })
821
822         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
823         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
824         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
825
826 }
827
828 func (s *TestSuite) TestRunTimeExceeded(c *C) {
829         api, _, _ := s.fullRunHelper(c, `{
830     "command": ["sleep", "3"],
831     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
832     "cwd": ".",
833     "environment": {},
834     "mounts": {"/tmp": {"kind": "tmp"} },
835     "output_path": "/tmp",
836     "priority": 1,
837         "runtime_constraints": {},
838         "scheduling_parameters":{"max_run_time": 1}
839 }`, nil, 0, func(t *TestDockerClient) {
840                 time.Sleep(3 * time.Second)
841                 t.logWriter.Close()
842         })
843
844         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
845         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*maximum run time exceeded.*")
846 }
847
848 func (s *TestSuite) TestContainerWaitFails(c *C) {
849         api, _, _ := s.fullRunHelper(c, `{
850     "command": ["sleep", "3"],
851     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
852     "cwd": ".",
853     "mounts": {"/tmp": {"kind": "tmp"} },
854     "output_path": "/tmp",
855     "priority": 1
856 }`, nil, 0, func(t *TestDockerClient) {
857                 t.ctrExited = true
858                 time.Sleep(10 * time.Second)
859                 t.logWriter.Close()
860         })
861
862         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
863         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Container is not running.*")
864 }
865
866 func (s *TestSuite) TestCrunchstat(c *C) {
867         api, _, _ := s.fullRunHelper(c, `{
868                 "command": ["sleep", "1"],
869                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
870                 "cwd": ".",
871                 "environment": {},
872                 "mounts": {"/tmp": {"kind": "tmp"} },
873                 "output_path": "/tmp",
874                 "priority": 1,
875                 "runtime_constraints": {}
876         }`, nil, 0, func(t *TestDockerClient) {
877                 time.Sleep(time.Second)
878                 t.logWriter.Close()
879         })
880
881         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
882         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
883
884         // We didn't actually start a container, so crunchstat didn't
885         // find accounting files and therefore didn't log any stats.
886         // It should have logged a "can't find accounting files"
887         // message after one poll interval, though, so we can confirm
888         // it's alive:
889         c.Assert(api.Logs["crunchstat"], NotNil)
890         c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
891
892         // The "files never appeared" log assures us that we called
893         // (*crunchstat.Reporter)Stop(), and that we set it up with
894         // the correct container ID "abcde":
895         c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files never appeared for abcde\n`)
896 }
897
898 func (s *TestSuite) TestNodeInfoLog(c *C) {
899         os.Setenv("SLURMD_NODENAME", "compute2")
900         api, _, _ := s.fullRunHelper(c, `{
901                 "command": ["sleep", "1"],
902                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
903                 "cwd": ".",
904                 "environment": {},
905                 "mounts": {"/tmp": {"kind": "tmp"} },
906                 "output_path": "/tmp",
907                 "priority": 1,
908                 "runtime_constraints": {}
909         }`, nil, 0,
910                 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         c.Assert(api.Logs["node"], NotNil)
919         json := api.Logs["node"].String()
920         c.Check(json, Matches, `(?ms).*"uuid": *"zzzzz-7ekkf-2z3mc76g2q73aio".*`)
921         c.Check(json, Matches, `(?ms).*"total_cpu_cores": *16.*`)
922         c.Check(json, Not(Matches), `(?ms).*"info":.*`)
923
924         c.Assert(api.Logs["node-info"], NotNil)
925         json = api.Logs["node-info"].String()
926         c.Check(json, Matches, `(?ms).*Host Information.*`)
927         c.Check(json, Matches, `(?ms).*CPU Information.*`)
928         c.Check(json, Matches, `(?ms).*Memory Information.*`)
929         c.Check(json, Matches, `(?ms).*Disk Space.*`)
930         c.Check(json, Matches, `(?ms).*Disk INodes.*`)
931 }
932
933 func (s *TestSuite) TestContainerRecordLog(c *C) {
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["container"], NotNil)
953         c.Check(api.Logs["container"].String(), Matches, `(?ms).*container_image.*`)
954 }
955
956 func (s *TestSuite) TestFullRunStderr(c *C) {
957         api, _, _ := s.fullRunHelper(c, `{
958     "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
959     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
960     "cwd": ".",
961     "environment": {},
962     "mounts": {"/tmp": {"kind": "tmp"} },
963     "output_path": "/tmp",
964     "priority": 1,
965     "runtime_constraints": {}
966 }`, nil, 1, func(t *TestDockerClient) {
967                 t.logWriter.Write(dockerLog(1, "hello\n"))
968                 t.logWriter.Write(dockerLog(2, "world\n"))
969                 t.logWriter.Close()
970         })
971
972         final := api.CalledWith("container.state", "Complete")
973         c.Assert(final, NotNil)
974         c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
975         c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
976
977         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
978         c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
979 }
980
981 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
982         api, _, _ := s.fullRunHelper(c, `{
983     "command": ["pwd"],
984     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
985     "cwd": ".",
986     "environment": {},
987     "mounts": {"/tmp": {"kind": "tmp"} },
988     "output_path": "/tmp",
989     "priority": 1,
990     "runtime_constraints": {}
991 }`, nil, 0, func(t *TestDockerClient) {
992                 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
993                 t.logWriter.Close()
994         })
995
996         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
997         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
998         c.Log(api.Logs["stdout"])
999         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
1000 }
1001
1002 func (s *TestSuite) TestFullRunSetCwd(c *C) {
1003         api, _, _ := s.fullRunHelper(c, `{
1004     "command": ["pwd"],
1005     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1006     "cwd": "/bin",
1007     "environment": {},
1008     "mounts": {"/tmp": {"kind": "tmp"} },
1009     "output_path": "/tmp",
1010     "priority": 1,
1011     "runtime_constraints": {}
1012 }`, nil, 0, func(t *TestDockerClient) {
1013                 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
1014                 t.logWriter.Close()
1015         })
1016
1017         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1018         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1019         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
1020 }
1021
1022 func (s *TestSuite) TestStopOnSignal(c *C) {
1023         s.testStopContainer(c, func(cr *ContainerRunner) {
1024                 go func() {
1025                         for !s.docker.calledWait {
1026                                 time.Sleep(time.Millisecond)
1027                         }
1028                         cr.SigChan <- syscall.SIGINT
1029                 }()
1030         })
1031 }
1032
1033 func (s *TestSuite) TestStopOnArvMountDeath(c *C) {
1034         s.testStopContainer(c, func(cr *ContainerRunner) {
1035                 cr.ArvMountExit = make(chan error)
1036                 go func() {
1037                         cr.ArvMountExit <- exec.Command("true").Run()
1038                         close(cr.ArvMountExit)
1039                 }()
1040         })
1041 }
1042
1043 func (s *TestSuite) testStopContainer(c *C, setup func(cr *ContainerRunner)) {
1044         record := `{
1045     "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
1046     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1047     "cwd": ".",
1048     "environment": {},
1049     "mounts": {"/tmp": {"kind": "tmp"} },
1050     "output_path": "/tmp",
1051     "priority": 1,
1052     "runtime_constraints": {}
1053 }`
1054
1055         rec := arvados.Container{}
1056         err := json.Unmarshal([]byte(record), &rec)
1057         c.Check(err, IsNil)
1058
1059         s.docker.fn = func(t *TestDockerClient) {
1060                 <-t.stop
1061                 t.logWriter.Write(dockerLog(1, "foo\n"))
1062                 t.logWriter.Close()
1063         }
1064         s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
1065
1066         api := &ArvTestClient{Container: rec}
1067         kc := &KeepTestClient{}
1068         defer kc.Close()
1069         cr, err := NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1070         c.Assert(err, IsNil)
1071         cr.RunArvMount = func([]string, string) (*exec.Cmd, error) { return nil, nil }
1072         cr.MkArvClient = func(token string) (IArvadosClient, error) {
1073                 return &ArvTestClient{}, nil
1074         }
1075         setup(cr)
1076
1077         done := make(chan error)
1078         go func() {
1079                 done <- cr.Run()
1080         }()
1081         select {
1082         case <-time.After(20 * time.Second):
1083                 pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
1084                 c.Fatal("timed out")
1085         case err = <-done:
1086                 c.Check(err, IsNil)
1087         }
1088         for k, v := range api.Logs {
1089                 c.Log(k)
1090                 c.Log(v.String())
1091         }
1092
1093         c.Check(api.CalledWith("container.log", nil), NotNil)
1094         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1095         c.Check(api.Logs["stdout"].String(), Matches, "(?ms).*foo\n$")
1096 }
1097
1098 func (s *TestSuite) TestFullRunSetEnv(c *C) {
1099         api, _, _ := s.fullRunHelper(c, `{
1100     "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1101     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1102     "cwd": "/bin",
1103     "environment": {"FROBIZ": "bilbo"},
1104     "mounts": {"/tmp": {"kind": "tmp"} },
1105     "output_path": "/tmp",
1106     "priority": 1,
1107     "runtime_constraints": {}
1108 }`, nil, 0, func(t *TestDockerClient) {
1109                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1110                 t.logWriter.Close()
1111         })
1112
1113         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1114         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1115         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)
1116 }
1117
1118 type ArvMountCmdLine struct {
1119         Cmd   []string
1120         token string
1121 }
1122
1123 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
1124         am.Cmd = c
1125         am.token = token
1126         return nil, nil
1127 }
1128
1129 func stubCert(temp string) string {
1130         path := temp + "/ca-certificates.crt"
1131         crt, _ := os.Create(path)
1132         crt.Close()
1133         arvadosclient.CertFiles = []string{path}
1134         return path
1135 }
1136
1137 func (s *TestSuite) TestSetupMounts(c *C) {
1138         api := &ArvTestClient{}
1139         kc := &KeepTestClient{}
1140         defer kc.Close()
1141         cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1142         c.Assert(err, IsNil)
1143         am := &ArvMountCmdLine{}
1144         cr.RunArvMount = am.ArvMountTest
1145
1146         realTemp, err := ioutil.TempDir("", "crunchrun_test1-")
1147         c.Assert(err, IsNil)
1148         certTemp, err := ioutil.TempDir("", "crunchrun_test2-")
1149         c.Assert(err, IsNil)
1150         stubCertPath := stubCert(certTemp)
1151
1152         cr.parentTemp = realTemp
1153
1154         defer os.RemoveAll(realTemp)
1155         defer os.RemoveAll(certTemp)
1156
1157         i := 0
1158         cr.MkTempDir = func(_ string, prefix string) (string, error) {
1159                 i++
1160                 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
1161                 err := os.Mkdir(d, os.ModePerm)
1162                 if err != nil && strings.Contains(err.Error(), ": file exists") {
1163                         // Test case must have pre-populated the tempdir
1164                         err = nil
1165                 }
1166                 return d, err
1167         }
1168
1169         checkEmpty := func() {
1170                 // Should be deleted.
1171                 _, err := os.Stat(realTemp)
1172                 c.Assert(os.IsNotExist(err), Equals, true)
1173
1174                 // Now recreate it for the next test.
1175                 c.Assert(os.Mkdir(realTemp, 0777), IsNil)
1176         }
1177
1178         {
1179                 i = 0
1180                 cr.ArvMountPoint = ""
1181                 cr.Container.Mounts = make(map[string]arvados.Mount)
1182                 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1183                 cr.Container.OutputPath = "/tmp"
1184                 cr.statInterval = 5 * time.Second
1185                 err := cr.SetupMounts()
1186                 c.Check(err, IsNil)
1187                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1188                         "--read-write", "--crunchstat-interval=5",
1189                         "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1190                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp"})
1191                 os.RemoveAll(cr.ArvMountPoint)
1192                 cr.CleanupDirs()
1193                 checkEmpty()
1194         }
1195
1196         {
1197                 i = 0
1198                 cr.ArvMountPoint = ""
1199                 cr.Container.Mounts = make(map[string]arvados.Mount)
1200                 cr.Container.Mounts["/out"] = arvados.Mount{Kind: "tmp"}
1201                 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1202                 cr.Container.OutputPath = "/out"
1203
1204                 err := cr.SetupMounts()
1205                 c.Check(err, IsNil)
1206                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1207                         "--read-write", "--crunchstat-interval=5",
1208                         "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1209                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/out", realTemp + "/tmp3:/tmp"})
1210                 os.RemoveAll(cr.ArvMountPoint)
1211                 cr.CleanupDirs()
1212                 checkEmpty()
1213         }
1214
1215         {
1216                 i = 0
1217                 cr.ArvMountPoint = ""
1218                 cr.Container.Mounts = make(map[string]arvados.Mount)
1219                 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1220                 cr.Container.OutputPath = "/tmp"
1221
1222                 apiflag := true
1223                 cr.Container.RuntimeConstraints.API = &apiflag
1224
1225                 err := cr.SetupMounts()
1226                 c.Check(err, IsNil)
1227                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1228                         "--read-write", "--crunchstat-interval=5",
1229                         "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1230                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", stubCertPath + ":/etc/arvados/ca-certificates.crt:ro"})
1231                 os.RemoveAll(cr.ArvMountPoint)
1232                 cr.CleanupDirs()
1233                 checkEmpty()
1234
1235                 apiflag = false
1236         }
1237
1238         {
1239                 i = 0
1240                 cr.ArvMountPoint = ""
1241                 cr.Container.Mounts = map[string]arvados.Mount{
1242                         "/keeptmp": {Kind: "collection", Writable: true},
1243                 }
1244                 cr.Container.OutputPath = "/keeptmp"
1245
1246                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1247
1248                 err := cr.SetupMounts()
1249                 c.Check(err, IsNil)
1250                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1251                         "--read-write", "--crunchstat-interval=5",
1252                         "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1253                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/tmp0:/keeptmp"})
1254                 os.RemoveAll(cr.ArvMountPoint)
1255                 cr.CleanupDirs()
1256                 checkEmpty()
1257         }
1258
1259         {
1260                 i = 0
1261                 cr.ArvMountPoint = ""
1262                 cr.Container.Mounts = map[string]arvados.Mount{
1263                         "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1264                         "/keepout": {Kind: "collection", Writable: true},
1265                 }
1266                 cr.Container.OutputPath = "/keepout"
1267
1268                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1269                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1270
1271                 err := cr.SetupMounts()
1272                 c.Check(err, IsNil)
1273                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1274                         "--read-write", "--crunchstat-interval=5",
1275                         "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1276                 sort.StringSlice(cr.Binds).Sort()
1277                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1278                         realTemp + "/keep1/tmp0:/keepout"})
1279                 os.RemoveAll(cr.ArvMountPoint)
1280                 cr.CleanupDirs()
1281                 checkEmpty()
1282         }
1283
1284         {
1285                 i = 0
1286                 cr.ArvMountPoint = ""
1287                 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
1288                 cr.Container.Mounts = map[string]arvados.Mount{
1289                         "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1290                         "/keepout": {Kind: "collection", Writable: true},
1291                 }
1292                 cr.Container.OutputPath = "/keepout"
1293
1294                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1295                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1296
1297                 err := cr.SetupMounts()
1298                 c.Check(err, IsNil)
1299                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1300                         "--read-write", "--crunchstat-interval=5",
1301                         "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1302                 sort.StringSlice(cr.Binds).Sort()
1303                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1304                         realTemp + "/keep1/tmp0:/keepout"})
1305                 os.RemoveAll(cr.ArvMountPoint)
1306                 cr.CleanupDirs()
1307                 checkEmpty()
1308         }
1309
1310         for _, test := range []struct {
1311                 in  interface{}
1312                 out string
1313         }{
1314                 {in: "foo", out: `"foo"`},
1315                 {in: nil, out: `null`},
1316                 {in: map[string]int64{"foo": 123456789123456789}, out: `{"foo":123456789123456789}`},
1317         } {
1318                 i = 0
1319                 cr.ArvMountPoint = ""
1320                 cr.Container.Mounts = map[string]arvados.Mount{
1321                         "/mnt/test.json": {Kind: "json", Content: test.in},
1322                 }
1323                 err := cr.SetupMounts()
1324                 c.Check(err, IsNil)
1325                 sort.StringSlice(cr.Binds).Sort()
1326                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/json2/mountdata.json:/mnt/test.json:ro"})
1327                 content, err := ioutil.ReadFile(realTemp + "/json2/mountdata.json")
1328                 c.Check(err, IsNil)
1329                 c.Check(content, DeepEquals, []byte(test.out))
1330                 os.RemoveAll(cr.ArvMountPoint)
1331                 cr.CleanupDirs()
1332                 checkEmpty()
1333         }
1334
1335         for _, test := range []struct {
1336                 in  interface{}
1337                 out string
1338         }{
1339                 {in: "foo", out: `foo`},
1340                 {in: nil, out: "error"},
1341                 {in: map[string]int64{"foo": 123456789123456789}, out: "error"},
1342         } {
1343                 i = 0
1344                 cr.ArvMountPoint = ""
1345                 cr.Container.Mounts = map[string]arvados.Mount{
1346                         "/mnt/test.txt": {Kind: "text", Content: test.in},
1347                 }
1348                 err := cr.SetupMounts()
1349                 if test.out == "error" {
1350                         c.Check(err.Error(), Equals, "content for mount \"/mnt/test.txt\" must be a string")
1351                 } else {
1352                         c.Check(err, IsNil)
1353                         sort.StringSlice(cr.Binds).Sort()
1354                         c.Check(cr.Binds, DeepEquals, []string{realTemp + "/text2/mountdata.text:/mnt/test.txt:ro"})
1355                         content, err := ioutil.ReadFile(realTemp + "/text2/mountdata.text")
1356                         c.Check(err, IsNil)
1357                         c.Check(content, DeepEquals, []byte(test.out))
1358                 }
1359                 os.RemoveAll(cr.ArvMountPoint)
1360                 cr.CleanupDirs()
1361                 checkEmpty()
1362         }
1363
1364         // Read-only mount points are allowed underneath output_dir mount point
1365         {
1366                 i = 0
1367                 cr.ArvMountPoint = ""
1368                 cr.Container.Mounts = make(map[string]arvados.Mount)
1369                 cr.Container.Mounts = map[string]arvados.Mount{
1370                         "/tmp":     {Kind: "tmp"},
1371                         "/tmp/foo": {Kind: "collection"},
1372                 }
1373                 cr.Container.OutputPath = "/tmp"
1374
1375                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1376
1377                 err := cr.SetupMounts()
1378                 c.Check(err, IsNil)
1379                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1380                         "--read-write", "--crunchstat-interval=5",
1381                         "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1382                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", realTemp + "/keep1/tmp0:/tmp/foo:ro"})
1383                 os.RemoveAll(cr.ArvMountPoint)
1384                 cr.CleanupDirs()
1385                 checkEmpty()
1386         }
1387
1388         // Writable mount points copied to output_dir mount point
1389         {
1390                 i = 0
1391                 cr.ArvMountPoint = ""
1392                 cr.Container.Mounts = make(map[string]arvados.Mount)
1393                 cr.Container.Mounts = map[string]arvados.Mount{
1394                         "/tmp": {Kind: "tmp"},
1395                         "/tmp/foo": {Kind: "collection",
1396                                 PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53",
1397                                 Writable:         true},
1398                         "/tmp/bar": {Kind: "collection",
1399                                 PortableDataHash: "59389a8f9ee9d399be35462a0f92541d+53",
1400                                 Path:             "baz",
1401                                 Writable:         true},
1402                 }
1403                 cr.Container.OutputPath = "/tmp"
1404
1405                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1406                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz", os.ModePerm)
1407
1408                 rf, _ := os.Create(realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz/quux")
1409                 rf.Write([]byte("bar"))
1410                 rf.Close()
1411
1412                 err := cr.SetupMounts()
1413                 c.Check(err, IsNil)
1414                 _, err = os.Stat(cr.HostOutputDir + "/foo")
1415                 c.Check(err, IsNil)
1416                 _, err = os.Stat(cr.HostOutputDir + "/bar/quux")
1417                 c.Check(err, IsNil)
1418                 os.RemoveAll(cr.ArvMountPoint)
1419                 cr.CleanupDirs()
1420                 checkEmpty()
1421         }
1422
1423         // Only mount points of kind 'collection' are allowed underneath output_dir mount point
1424         {
1425                 i = 0
1426                 cr.ArvMountPoint = ""
1427                 cr.Container.Mounts = make(map[string]arvados.Mount)
1428                 cr.Container.Mounts = map[string]arvados.Mount{
1429                         "/tmp":     {Kind: "tmp"},
1430                         "/tmp/foo": {Kind: "tmp"},
1431                 }
1432                 cr.Container.OutputPath = "/tmp"
1433
1434                 err := cr.SetupMounts()
1435                 c.Check(err, NotNil)
1436                 c.Check(err, ErrorMatches, `Only mount points of kind 'collection', 'text' or 'json' are supported underneath the output_path.*`)
1437                 os.RemoveAll(cr.ArvMountPoint)
1438                 cr.CleanupDirs()
1439                 checkEmpty()
1440         }
1441
1442         // Only mount point of kind 'collection' is allowed for stdin
1443         {
1444                 i = 0
1445                 cr.ArvMountPoint = ""
1446                 cr.Container.Mounts = make(map[string]arvados.Mount)
1447                 cr.Container.Mounts = map[string]arvados.Mount{
1448                         "stdin": {Kind: "tmp"},
1449                 }
1450
1451                 err := cr.SetupMounts()
1452                 c.Check(err, NotNil)
1453                 c.Check(err, ErrorMatches, `Unsupported mount kind 'tmp' for stdin.*`)
1454                 os.RemoveAll(cr.ArvMountPoint)
1455                 cr.CleanupDirs()
1456                 checkEmpty()
1457         }
1458
1459         // git_tree mounts
1460         {
1461                 i = 0
1462                 cr.ArvMountPoint = ""
1463                 (*GitMountSuite)(nil).useTestGitServer(c)
1464                 cr.token = arvadostest.ActiveToken
1465                 cr.Container.Mounts = make(map[string]arvados.Mount)
1466                 cr.Container.Mounts = map[string]arvados.Mount{
1467                         "/tip": {
1468                                 Kind:   "git_tree",
1469                                 UUID:   arvadostest.Repository2UUID,
1470                                 Commit: "fd3531f42995344f36c30b79f55f27b502f3d344",
1471                                 Path:   "/",
1472                         },
1473                         "/non-tip": {
1474                                 Kind:   "git_tree",
1475                                 UUID:   arvadostest.Repository2UUID,
1476                                 Commit: "5ebfab0522851df01fec11ec55a6d0f4877b542e",
1477                                 Path:   "/",
1478                         },
1479                 }
1480                 cr.Container.OutputPath = "/tmp"
1481
1482                 err := cr.SetupMounts()
1483                 c.Check(err, IsNil)
1484
1485                 // dirMap[mountpoint] == tmpdir
1486                 dirMap := make(map[string]string)
1487                 for _, bind := range cr.Binds {
1488                         tokens := strings.Split(bind, ":")
1489                         dirMap[tokens[1]] = tokens[0]
1490
1491                         if cr.Container.Mounts[tokens[1]].Writable {
1492                                 c.Check(len(tokens), Equals, 2)
1493                         } else {
1494                                 c.Check(len(tokens), Equals, 3)
1495                                 c.Check(tokens[2], Equals, "ro")
1496                         }
1497                 }
1498
1499                 data, err := ioutil.ReadFile(dirMap["/tip"] + "/dir1/dir2/file with mode 0644")
1500                 c.Check(err, IsNil)
1501                 c.Check(string(data), Equals, "\000\001\002\003")
1502                 _, err = ioutil.ReadFile(dirMap["/tip"] + "/file only on testbranch")
1503                 c.Check(err, FitsTypeOf, &os.PathError{})
1504                 c.Check(os.IsNotExist(err), Equals, true)
1505
1506                 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/dir1/dir2/file with mode 0644")
1507                 c.Check(err, IsNil)
1508                 c.Check(string(data), Equals, "\000\001\002\003")
1509                 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/file only on testbranch")
1510                 c.Check(err, IsNil)
1511                 c.Check(string(data), Equals, "testfile\n")
1512
1513                 cr.CleanupDirs()
1514                 checkEmpty()
1515         }
1516 }
1517
1518 func (s *TestSuite) TestStdout(c *C) {
1519         helperRecord := `{
1520                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1521                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1522                 "cwd": "/bin",
1523                 "environment": {"FROBIZ": "bilbo"},
1524                 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1525                 "output_path": "/tmp",
1526                 "priority": 1,
1527                 "runtime_constraints": {}
1528         }`
1529
1530         api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1531                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1532                 t.logWriter.Close()
1533         })
1534
1535         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1536         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1537         c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1538 }
1539
1540 // Used by the TestStdoutWithWrongPath*()
1541 func (s *TestSuite) stdoutErrorRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, err error) {
1542         rec := arvados.Container{}
1543         err = json.Unmarshal([]byte(record), &rec)
1544         c.Check(err, IsNil)
1545
1546         s.docker.fn = fn
1547         s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
1548
1549         api = &ArvTestClient{Container: rec}
1550         kc := &KeepTestClient{}
1551         defer kc.Close()
1552         cr, err = NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1553         c.Assert(err, IsNil)
1554         am := &ArvMountCmdLine{}
1555         cr.RunArvMount = am.ArvMountTest
1556         cr.MkArvClient = func(token string) (IArvadosClient, error) {
1557                 return &ArvTestClient{}, nil
1558         }
1559
1560         err = cr.Run()
1561         return
1562 }
1563
1564 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1565         _, _, err := s.stdoutErrorRunHelper(c, `{
1566     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1567     "output_path": "/tmp"
1568 }`, func(t *TestDockerClient) {})
1569
1570         c.Check(err, NotNil)
1571         c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
1572 }
1573
1574 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1575         _, _, err := s.stdoutErrorRunHelper(c, `{
1576     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1577     "output_path": "/tmp"
1578 }`, func(t *TestDockerClient) {})
1579
1580         c.Check(err, NotNil)
1581         c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'tmp' for stdout"), Equals, true)
1582 }
1583
1584 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1585         _, _, err := s.stdoutErrorRunHelper(c, `{
1586     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1587     "output_path": "/tmp"
1588 }`, func(t *TestDockerClient) {})
1589
1590         c.Check(err, NotNil)
1591         c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'collection' for stdout"), Equals, true)
1592 }
1593
1594 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1595         defer os.Setenv("ARVADOS_API_HOST", os.Getenv("ARVADOS_API_HOST"))
1596         os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1597         api, _, _ := s.fullRunHelper(c, `{
1598     "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1599     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1600     "cwd": "/bin",
1601     "environment": {},
1602     "mounts": {"/tmp": {"kind": "tmp"} },
1603     "output_path": "/tmp",
1604     "priority": 1,
1605     "runtime_constraints": {"API": true}
1606 }`, nil, 0, func(t *TestDockerClient) {
1607                 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
1608                 t.logWriter.Close()
1609         })
1610
1611         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1612         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1613         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "test.arvados.org\n"), Equals, true)
1614         c.Check(api.CalledWith("container.output", "d41d8cd98f00b204e9800998ecf8427e+0"), NotNil)
1615 }
1616
1617 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1618         defer os.Setenv("ARVADOS_API_HOST", os.Getenv("ARVADOS_API_HOST"))
1619         os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1620         api, _, _ := s.fullRunHelper(c, `{
1621     "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1622     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1623     "cwd": "/bin",
1624     "environment": {},
1625     "mounts": {"/tmp": {"kind": "tmp"} },
1626     "output_path": "/tmp",
1627     "priority": 1,
1628     "runtime_constraints": {"API": true}
1629 }`, nil, 0, func(t *TestDockerClient) {
1630                 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
1631                 t.logWriter.Close()
1632         })
1633
1634         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1635         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1636         c.Check(api.CalledWith("container.output", "d4ab34d3d4f8a72f5c4973051ae69fab+122"), NotNil)
1637 }
1638
1639 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1640         helperRecord := `{
1641                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1642                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1643                 "cwd": "/bin",
1644                 "environment": {"FROBIZ": "bilbo"},
1645                 "mounts": {
1646         "/tmp": {"kind": "tmp"},
1647         "/tmp/foo": {"kind": "collection",
1648                      "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1649                      "exclude_from_output": true
1650         },
1651         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1652     },
1653                 "output_path": "/tmp",
1654                 "priority": 1,
1655                 "runtime_constraints": {}
1656         }`
1657
1658         extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1659
1660         api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1661                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1662                 t.logWriter.Close()
1663         })
1664
1665         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1666         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1667         c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1668 }
1669
1670 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1671         helperRecord := `{
1672                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1673                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1674                 "cwd": "/bin",
1675                 "environment": {"FROBIZ": "bilbo"},
1676                 "mounts": {
1677         "/tmp": {"kind": "tmp"},
1678         "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1679         "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1680         "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1681         "/tmp/foo/baz/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1682         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1683     },
1684                 "output_path": "/tmp",
1685                 "priority": 1,
1686                 "runtime_constraints": {}
1687         }`
1688
1689         extraMounts := []string{
1690                 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1691                 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1692                 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1693         }
1694
1695         api, runner, realtemp := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1696                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1697                 t.logWriter.Close()
1698         })
1699
1700         c.Check(runner.Binds, DeepEquals, []string{realtemp + "/tmp2:/tmp",
1701                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt:/tmp/foo/bar:ro",
1702                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt:/tmp/foo/baz/sub2file2:ro",
1703                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1:/tmp/foo/sub1:ro",
1704                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt:/tmp/foo/sub1file2:ro",
1705         })
1706
1707         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1708         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1709         for _, v := range api.Content {
1710                 if v["collection"] != nil {
1711                         c.Check(v["ensure_unique_name"], Equals, true)
1712                         collection := v["collection"].(arvadosclient.Dict)
1713                         if strings.Index(collection["name"].(string), "output") == 0 {
1714                                 manifest := collection["manifest_text"].(string)
1715
1716                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1717 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:bar 36:18:sub1file2
1718 ./foo/baz 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2
1719 ./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1720 ./foo/sub1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1721 `)
1722                         }
1723                 }
1724         }
1725 }
1726
1727 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
1728         helperRecord := `{
1729                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1730                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1731                 "cwd": "/bin",
1732                 "environment": {"FROBIZ": "bilbo"},
1733                 "mounts": {
1734         "/tmp": {"kind": "tmp"},
1735         "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/subdir1/file2_in_subdir1.txt"},
1736         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1737     },
1738                 "output_path": "/tmp",
1739                 "priority": 1,
1740                 "runtime_constraints": {}
1741         }`
1742
1743         extraMounts := []string{
1744                 "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1745         }
1746
1747         api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1748                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1749                 t.logWriter.Close()
1750         })
1751
1752         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1753         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1754         for _, v := range api.Content {
1755                 if v["collection"] != nil {
1756                         collection := v["collection"].(arvadosclient.Dict)
1757                         if strings.Index(collection["name"].(string), "output") == 0 {
1758                                 manifest := collection["manifest_text"].(string)
1759
1760                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1761 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 10:17:bar
1762 `)
1763                         }
1764                 }
1765         }
1766 }
1767
1768 func (s *TestSuite) TestOutputError(c *C) {
1769         helperRecord := `{
1770                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1771                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1772                 "cwd": "/bin",
1773                 "environment": {"FROBIZ": "bilbo"},
1774                 "mounts": {
1775         "/tmp": {"kind": "tmp"}
1776     },
1777                 "output_path": "/tmp",
1778                 "priority": 1,
1779                 "runtime_constraints": {}
1780         }`
1781
1782         extraMounts := []string{}
1783
1784         api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1785                 os.Symlink("/etc/hosts", t.realTemp+"/tmp2/baz")
1786                 t.logWriter.Close()
1787         })
1788
1789         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1790 }
1791
1792 func (s *TestSuite) TestStdinCollectionMountPoint(c *C) {
1793         helperRecord := `{
1794                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1795                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1796                 "cwd": "/bin",
1797                 "environment": {"FROBIZ": "bilbo"},
1798                 "mounts": {
1799         "/tmp": {"kind": "tmp"},
1800         "stdin": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/file1_in_main.txt"},
1801         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1802     },
1803                 "output_path": "/tmp",
1804                 "priority": 1,
1805                 "runtime_constraints": {}
1806         }`
1807
1808         extraMounts := []string{
1809                 "b0def87f80dd594d4675809e83bd4f15+367/file1_in_main.txt",
1810         }
1811
1812         api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1813                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1814                 t.logWriter.Close()
1815         })
1816
1817         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1818         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1819         for _, v := range api.Content {
1820                 if v["collection"] != nil {
1821                         collection := v["collection"].(arvadosclient.Dict)
1822                         if strings.Index(collection["name"].(string), "output") == 0 {
1823                                 manifest := collection["manifest_text"].(string)
1824                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1825 `)
1826                         }
1827                 }
1828         }
1829 }
1830
1831 func (s *TestSuite) TestStdinJsonMountPoint(c *C) {
1832         helperRecord := `{
1833                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1834                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1835                 "cwd": "/bin",
1836                 "environment": {"FROBIZ": "bilbo"},
1837                 "mounts": {
1838         "/tmp": {"kind": "tmp"},
1839         "stdin": {"kind": "json", "content": "foo"},
1840         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1841     },
1842                 "output_path": "/tmp",
1843                 "priority": 1,
1844                 "runtime_constraints": {}
1845         }`
1846
1847         api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1848                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1849                 t.logWriter.Close()
1850         })
1851
1852         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1853         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1854         for _, v := range api.Content {
1855                 if v["collection"] != nil {
1856                         collection := v["collection"].(arvadosclient.Dict)
1857                         if strings.Index(collection["name"].(string), "output") == 0 {
1858                                 manifest := collection["manifest_text"].(string)
1859                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1860 `)
1861                         }
1862                 }
1863         }
1864 }
1865
1866 func (s *TestSuite) TestStderrMount(c *C) {
1867         api, _, _ := s.fullRunHelper(c, `{
1868     "command": ["/bin/sh", "-c", "echo hello;exit 1"],
1869     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1870     "cwd": ".",
1871     "environment": {},
1872     "mounts": {"/tmp": {"kind": "tmp"},
1873                "stdout": {"kind": "file", "path": "/tmp/a/out.txt"},
1874                "stderr": {"kind": "file", "path": "/tmp/b/err.txt"}},
1875     "output_path": "/tmp",
1876     "priority": 1,
1877     "runtime_constraints": {}
1878 }`, nil, 1, func(t *TestDockerClient) {
1879                 t.logWriter.Write(dockerLog(1, "hello\n"))
1880                 t.logWriter.Write(dockerLog(2, "oops\n"))
1881                 t.logWriter.Close()
1882         })
1883
1884         final := api.CalledWith("container.state", "Complete")
1885         c.Assert(final, NotNil)
1886         c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1887         c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1888
1889         c.Check(api.CalledWith("collection.manifest_text", "./a b1946ac92492d2347c6235b4d2611184+6 0:6:out.txt\n./b 38af5c54926b620264ab1501150cf189+5 0:5:err.txt\n"), NotNil)
1890 }
1891
1892 func (s *TestSuite) TestNumberRoundTrip(c *C) {
1893         kc := &KeepTestClient{}
1894         defer kc.Close()
1895         cr, err := NewContainerRunner(s.client, &ArvTestClient{callraw: true}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1896         c.Assert(err, IsNil)
1897         cr.fetchContainerRecord()
1898
1899         jsondata, err := json.Marshal(cr.Container.Mounts["/json"].Content)
1900
1901         c.Check(err, IsNil)
1902         c.Check(string(jsondata), Equals, `{"number":123456789123456789}`)
1903 }
1904
1905 func (s *TestSuite) TestFullBrokenDocker1(c *C) {
1906         tf, err := ioutil.TempFile("", "brokenNodeHook-")
1907         c.Assert(err, IsNil)
1908         defer os.Remove(tf.Name())
1909
1910         tf.Write([]byte(`#!/bin/sh
1911 exec echo killme
1912 `))
1913         tf.Close()
1914         os.Chmod(tf.Name(), 0700)
1915
1916         ech := tf.Name()
1917         brokenNodeHook = &ech
1918
1919         api, _, _ := s.fullRunHelper(c, `{
1920     "command": ["echo", "hello world"],
1921     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1922     "cwd": ".",
1923     "environment": {},
1924     "mounts": {"/tmp": {"kind": "tmp"} },
1925     "output_path": "/tmp",
1926     "priority": 1,
1927     "runtime_constraints": {}
1928 }`, nil, 2, func(t *TestDockerClient) {
1929                 t.logWriter.Write(dockerLog(1, "hello world\n"))
1930                 t.logWriter.Close()
1931         })
1932
1933         c.Check(api.CalledWith("container.state", "Queued"), NotNil)
1934         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1935         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Running broken node hook.*")
1936         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*killme.*")
1937
1938 }
1939
1940 func (s *TestSuite) TestFullBrokenDocker2(c *C) {
1941         ech := ""
1942         brokenNodeHook = &ech
1943
1944         api, _, _ := s.fullRunHelper(c, `{
1945     "command": ["echo", "hello world"],
1946     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1947     "cwd": ".",
1948     "environment": {},
1949     "mounts": {"/tmp": {"kind": "tmp"} },
1950     "output_path": "/tmp",
1951     "priority": 1,
1952     "runtime_constraints": {}
1953 }`, nil, 2, func(t *TestDockerClient) {
1954                 t.logWriter.Write(dockerLog(1, "hello world\n"))
1955                 t.logWriter.Close()
1956         })
1957
1958         c.Check(api.CalledWith("container.state", "Queued"), NotNil)
1959         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1960         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*No broken node hook.*")
1961 }
1962
1963 func (s *TestSuite) TestFullBrokenDocker3(c *C) {
1964         ech := ""
1965         brokenNodeHook = &ech
1966
1967         api, _, _ := s.fullRunHelper(c, `{
1968     "command": ["echo", "hello world"],
1969     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1970     "cwd": ".",
1971     "environment": {},
1972     "mounts": {"/tmp": {"kind": "tmp"} },
1973     "output_path": "/tmp",
1974     "priority": 1,
1975     "runtime_constraints": {}
1976 }`, nil, 3, func(t *TestDockerClient) {
1977                 t.logWriter.Write(dockerLog(1, "hello world\n"))
1978                 t.logWriter.Close()
1979         })
1980
1981         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1982         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1983 }
1984
1985 func (s *TestSuite) TestBadCommand1(c *C) {
1986         ech := ""
1987         brokenNodeHook = &ech
1988
1989         api, _, _ := s.fullRunHelper(c, `{
1990     "command": ["echo", "hello world"],
1991     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1992     "cwd": ".",
1993     "environment": {},
1994     "mounts": {"/tmp": {"kind": "tmp"} },
1995     "output_path": "/tmp",
1996     "priority": 1,
1997     "runtime_constraints": {}
1998 }`, nil, 4, func(t *TestDockerClient) {
1999                 t.logWriter.Write(dockerLog(1, "hello world\n"))
2000                 t.logWriter.Close()
2001         })
2002
2003         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2004         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2005 }
2006
2007 func (s *TestSuite) TestBadCommand2(c *C) {
2008         ech := ""
2009         brokenNodeHook = &ech
2010
2011         api, _, _ := s.fullRunHelper(c, `{
2012     "command": ["echo", "hello world"],
2013     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2014     "cwd": ".",
2015     "environment": {},
2016     "mounts": {"/tmp": {"kind": "tmp"} },
2017     "output_path": "/tmp",
2018     "priority": 1,
2019     "runtime_constraints": {}
2020 }`, nil, 5, func(t *TestDockerClient) {
2021                 t.logWriter.Write(dockerLog(1, "hello world\n"))
2022                 t.logWriter.Close()
2023         })
2024
2025         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2026         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2027 }
2028
2029 func (s *TestSuite) TestBadCommand3(c *C) {
2030         ech := ""
2031         brokenNodeHook = &ech
2032
2033         api, _, _ := s.fullRunHelper(c, `{
2034     "command": ["echo", "hello world"],
2035     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2036     "cwd": ".",
2037     "environment": {},
2038     "mounts": {"/tmp": {"kind": "tmp"} },
2039     "output_path": "/tmp",
2040     "priority": 1,
2041     "runtime_constraints": {}
2042 }`, nil, 6, func(t *TestDockerClient) {
2043                 t.logWriter.Write(dockerLog(1, "hello world\n"))
2044                 t.logWriter.Close()
2045         })
2046
2047         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2048         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2049 }
2050
2051 func (s *TestSuite) TestSecretTextMountPoint(c *C) {
2052         // under normal mounts, gets captured in output, oops
2053         helperRecord := `{
2054                 "command": ["true"],
2055                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2056                 "cwd": "/bin",
2057                 "mounts": {
2058                     "/tmp": {"kind": "tmp"},
2059                     "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2060                 },
2061                 "secret_mounts": {
2062                 },
2063                 "output_path": "/tmp",
2064                 "priority": 1,
2065                 "runtime_constraints": {}
2066         }`
2067
2068         api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2069                 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2070                 c.Check(err, IsNil)
2071                 c.Check(content, DeepEquals, []byte("mypassword"))
2072                 t.logWriter.Close()
2073         })
2074
2075         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2076         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2077         c.Check(api.CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), NotNil)
2078         c.Check(api.CalledWith("collection.manifest_text", ""), IsNil)
2079
2080         // under secret mounts, not captured in output
2081         helperRecord = `{
2082                 "command": ["true"],
2083                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2084                 "cwd": "/bin",
2085                 "mounts": {
2086                     "/tmp": {"kind": "tmp"}
2087                 },
2088                 "secret_mounts": {
2089                     "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2090                 },
2091                 "output_path": "/tmp",
2092                 "priority": 1,
2093                 "runtime_constraints": {}
2094         }`
2095
2096         api, _, _ = s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2097                 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2098                 c.Check(err, IsNil)
2099                 c.Check(content, DeepEquals, []byte("mypassword"))
2100                 t.logWriter.Close()
2101         })
2102
2103         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2104         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2105         c.Check(api.CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), IsNil)
2106         c.Check(api.CalledWith("collection.manifest_text", ""), NotNil)
2107 }
2108
2109 type FakeProcess struct {
2110         cmdLine []string
2111 }
2112
2113 func (fp FakeProcess) CmdlineSlice() ([]string, error) {
2114         return fp.cmdLine, nil
2115 }
2116
2117 func (s *TestSuite) helpCheckContainerd(c *C, lp func() ([]PsProcess, error)) error {
2118         kc := &KeepTestClient{}
2119         defer kc.Close()
2120         cr, err := NewContainerRunner(s.client, &ArvTestClient{callraw: true}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
2121         cr.checkContainerd = time.Duration(100 * time.Millisecond)
2122         c.Assert(err, IsNil)
2123         cr.ListProcesses = lp
2124
2125         s.docker.fn = func(t *TestDockerClient) {
2126                 time.Sleep(1 * time.Second)
2127                 t.logWriter.Close()
2128         }
2129
2130         err = cr.CreateContainer()
2131         c.Check(err, IsNil)
2132
2133         err = cr.StartContainer()
2134         c.Check(err, IsNil)
2135
2136         err = cr.WaitFinish()
2137         return err
2138
2139 }
2140
2141 func (s *TestSuite) TestCheckContainerdPresent(c *C) {
2142         err := s.helpCheckContainerd(c, func() ([]PsProcess, error) {
2143                 return []PsProcess{FakeProcess{[]string{"docker-containerd"}}}, nil
2144         })
2145         c.Check(err, IsNil)
2146 }
2147
2148 func (s *TestSuite) TestCheckContainerdMissing(c *C) {
2149         err := s.helpCheckContainerd(c, func() ([]PsProcess, error) {
2150                 return []PsProcess{FakeProcess{[]string{"abc"}}}, nil
2151         })
2152         c.Check(err, ErrorMatches, `'containerd' not found in process list.`)
2153 }