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