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