Merge branch '17343-workbench1-optional'
[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                 cr.Container.RuntimeConstraints.API = true
1295
1296                 err := cr.SetupMounts()
1297                 c.Check(err, IsNil)
1298                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1299                         "--read-write", "--crunchstat-interval=5",
1300                         "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1301                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", stubCertPath + ":/etc/arvados/ca-certificates.crt:ro"})
1302                 os.RemoveAll(cr.ArvMountPoint)
1303                 cr.CleanupDirs()
1304                 checkEmpty()
1305
1306                 cr.Container.RuntimeConstraints.API = false
1307         }
1308
1309         {
1310                 i = 0
1311                 cr.ArvMountPoint = ""
1312                 cr.Container.Mounts = map[string]arvados.Mount{
1313                         "/keeptmp": {Kind: "collection", Writable: true},
1314                 }
1315                 cr.Container.OutputPath = "/keeptmp"
1316
1317                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1318
1319                 err := cr.SetupMounts()
1320                 c.Check(err, IsNil)
1321                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1322                         "--read-write", "--crunchstat-interval=5",
1323                         "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1324                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/tmp0:/keeptmp"})
1325                 os.RemoveAll(cr.ArvMountPoint)
1326                 cr.CleanupDirs()
1327                 checkEmpty()
1328         }
1329
1330         {
1331                 i = 0
1332                 cr.ArvMountPoint = ""
1333                 cr.Container.Mounts = map[string]arvados.Mount{
1334                         "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1335                         "/keepout": {Kind: "collection", Writable: true},
1336                 }
1337                 cr.Container.OutputPath = "/keepout"
1338
1339                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1340                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1341
1342                 err := cr.SetupMounts()
1343                 c.Check(err, IsNil)
1344                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1345                         "--read-write", "--crunchstat-interval=5",
1346                         "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1347                 sort.StringSlice(cr.Binds).Sort()
1348                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1349                         realTemp + "/keep1/tmp0:/keepout"})
1350                 os.RemoveAll(cr.ArvMountPoint)
1351                 cr.CleanupDirs()
1352                 checkEmpty()
1353         }
1354
1355         {
1356                 i = 0
1357                 cr.ArvMountPoint = ""
1358                 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
1359                 cr.Container.Mounts = map[string]arvados.Mount{
1360                         "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1361                         "/keepout": {Kind: "collection", Writable: true},
1362                 }
1363                 cr.Container.OutputPath = "/keepout"
1364
1365                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1366                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1367
1368                 err := cr.SetupMounts()
1369                 c.Check(err, IsNil)
1370                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1371                         "--read-write", "--crunchstat-interval=5",
1372                         "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1373                 sort.StringSlice(cr.Binds).Sort()
1374                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1375                         realTemp + "/keep1/tmp0:/keepout"})
1376                 os.RemoveAll(cr.ArvMountPoint)
1377                 cr.CleanupDirs()
1378                 checkEmpty()
1379         }
1380
1381         for _, test := range []struct {
1382                 in  interface{}
1383                 out string
1384         }{
1385                 {in: "foo", out: `"foo"`},
1386                 {in: nil, out: `null`},
1387                 {in: map[string]int64{"foo": 123456789123456789}, out: `{"foo":123456789123456789}`},
1388         } {
1389                 i = 0
1390                 cr.ArvMountPoint = ""
1391                 cr.Container.Mounts = map[string]arvados.Mount{
1392                         "/mnt/test.json": {Kind: "json", Content: test.in},
1393                 }
1394                 err := cr.SetupMounts()
1395                 c.Check(err, IsNil)
1396                 sort.StringSlice(cr.Binds).Sort()
1397                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/json2/mountdata.json:/mnt/test.json:ro"})
1398                 content, err := ioutil.ReadFile(realTemp + "/json2/mountdata.json")
1399                 c.Check(err, IsNil)
1400                 c.Check(content, DeepEquals, []byte(test.out))
1401                 os.RemoveAll(cr.ArvMountPoint)
1402                 cr.CleanupDirs()
1403                 checkEmpty()
1404         }
1405
1406         for _, test := range []struct {
1407                 in  interface{}
1408                 out string
1409         }{
1410                 {in: "foo", out: `foo`},
1411                 {in: nil, out: "error"},
1412                 {in: map[string]int64{"foo": 123456789123456789}, out: "error"},
1413         } {
1414                 i = 0
1415                 cr.ArvMountPoint = ""
1416                 cr.Container.Mounts = map[string]arvados.Mount{
1417                         "/mnt/test.txt": {Kind: "text", Content: test.in},
1418                 }
1419                 err := cr.SetupMounts()
1420                 if test.out == "error" {
1421                         c.Check(err.Error(), Equals, "content for mount \"/mnt/test.txt\" must be a string")
1422                 } else {
1423                         c.Check(err, IsNil)
1424                         sort.StringSlice(cr.Binds).Sort()
1425                         c.Check(cr.Binds, DeepEquals, []string{realTemp + "/text2/mountdata.text:/mnt/test.txt:ro"})
1426                         content, err := ioutil.ReadFile(realTemp + "/text2/mountdata.text")
1427                         c.Check(err, IsNil)
1428                         c.Check(content, DeepEquals, []byte(test.out))
1429                 }
1430                 os.RemoveAll(cr.ArvMountPoint)
1431                 cr.CleanupDirs()
1432                 checkEmpty()
1433         }
1434
1435         // Read-only mount points are allowed underneath output_dir mount point
1436         {
1437                 i = 0
1438                 cr.ArvMountPoint = ""
1439                 cr.Container.Mounts = make(map[string]arvados.Mount)
1440                 cr.Container.Mounts = map[string]arvados.Mount{
1441                         "/tmp":     {Kind: "tmp"},
1442                         "/tmp/foo": {Kind: "collection"},
1443                 }
1444                 cr.Container.OutputPath = "/tmp"
1445
1446                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1447
1448                 err := cr.SetupMounts()
1449                 c.Check(err, IsNil)
1450                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1451                         "--read-write", "--crunchstat-interval=5",
1452                         "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1453                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", realTemp + "/keep1/tmp0:/tmp/foo:ro"})
1454                 os.RemoveAll(cr.ArvMountPoint)
1455                 cr.CleanupDirs()
1456                 checkEmpty()
1457         }
1458
1459         // Writable mount points copied to output_dir mount point
1460         {
1461                 i = 0
1462                 cr.ArvMountPoint = ""
1463                 cr.Container.Mounts = make(map[string]arvados.Mount)
1464                 cr.Container.Mounts = map[string]arvados.Mount{
1465                         "/tmp": {Kind: "tmp"},
1466                         "/tmp/foo": {Kind: "collection",
1467                                 PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53",
1468                                 Writable:         true},
1469                         "/tmp/bar": {Kind: "collection",
1470                                 PortableDataHash: "59389a8f9ee9d399be35462a0f92541d+53",
1471                                 Path:             "baz",
1472                                 Writable:         true},
1473                 }
1474                 cr.Container.OutputPath = "/tmp"
1475
1476                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1477                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz", os.ModePerm)
1478
1479                 rf, _ := os.Create(realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz/quux")
1480                 rf.Write([]byte("bar"))
1481                 rf.Close()
1482
1483                 err := cr.SetupMounts()
1484                 c.Check(err, IsNil)
1485                 _, err = os.Stat(cr.HostOutputDir + "/foo")
1486                 c.Check(err, IsNil)
1487                 _, err = os.Stat(cr.HostOutputDir + "/bar/quux")
1488                 c.Check(err, IsNil)
1489                 os.RemoveAll(cr.ArvMountPoint)
1490                 cr.CleanupDirs()
1491                 checkEmpty()
1492         }
1493
1494         // Only mount points of kind 'collection' are allowed underneath output_dir mount point
1495         {
1496                 i = 0
1497                 cr.ArvMountPoint = ""
1498                 cr.Container.Mounts = make(map[string]arvados.Mount)
1499                 cr.Container.Mounts = map[string]arvados.Mount{
1500                         "/tmp":     {Kind: "tmp"},
1501                         "/tmp/foo": {Kind: "tmp"},
1502                 }
1503                 cr.Container.OutputPath = "/tmp"
1504
1505                 err := cr.SetupMounts()
1506                 c.Check(err, NotNil)
1507                 c.Check(err, ErrorMatches, `only mount points of kind 'collection', 'text' or 'json' are supported underneath the output_path.*`)
1508                 os.RemoveAll(cr.ArvMountPoint)
1509                 cr.CleanupDirs()
1510                 checkEmpty()
1511         }
1512
1513         // Only mount point of kind 'collection' is allowed for stdin
1514         {
1515                 i = 0
1516                 cr.ArvMountPoint = ""
1517                 cr.Container.Mounts = make(map[string]arvados.Mount)
1518                 cr.Container.Mounts = map[string]arvados.Mount{
1519                         "stdin": {Kind: "tmp"},
1520                 }
1521
1522                 err := cr.SetupMounts()
1523                 c.Check(err, NotNil)
1524                 c.Check(err, ErrorMatches, `unsupported mount kind 'tmp' for stdin.*`)
1525                 os.RemoveAll(cr.ArvMountPoint)
1526                 cr.CleanupDirs()
1527                 checkEmpty()
1528         }
1529
1530         // git_tree mounts
1531         {
1532                 i = 0
1533                 cr.ArvMountPoint = ""
1534                 (*GitMountSuite)(nil).useTestGitServer(c)
1535                 cr.token = arvadostest.ActiveToken
1536                 cr.Container.Mounts = make(map[string]arvados.Mount)
1537                 cr.Container.Mounts = map[string]arvados.Mount{
1538                         "/tip": {
1539                                 Kind:   "git_tree",
1540                                 UUID:   arvadostest.Repository2UUID,
1541                                 Commit: "fd3531f42995344f36c30b79f55f27b502f3d344",
1542                                 Path:   "/",
1543                         },
1544                         "/non-tip": {
1545                                 Kind:   "git_tree",
1546                                 UUID:   arvadostest.Repository2UUID,
1547                                 Commit: "5ebfab0522851df01fec11ec55a6d0f4877b542e",
1548                                 Path:   "/",
1549                         },
1550                 }
1551                 cr.Container.OutputPath = "/tmp"
1552
1553                 err := cr.SetupMounts()
1554                 c.Check(err, IsNil)
1555
1556                 // dirMap[mountpoint] == tmpdir
1557                 dirMap := make(map[string]string)
1558                 for _, bind := range cr.Binds {
1559                         tokens := strings.Split(bind, ":")
1560                         dirMap[tokens[1]] = tokens[0]
1561
1562                         if cr.Container.Mounts[tokens[1]].Writable {
1563                                 c.Check(len(tokens), Equals, 2)
1564                         } else {
1565                                 c.Check(len(tokens), Equals, 3)
1566                                 c.Check(tokens[2], Equals, "ro")
1567                         }
1568                 }
1569
1570                 data, err := ioutil.ReadFile(dirMap["/tip"] + "/dir1/dir2/file with mode 0644")
1571                 c.Check(err, IsNil)
1572                 c.Check(string(data), Equals, "\000\001\002\003")
1573                 _, err = ioutil.ReadFile(dirMap["/tip"] + "/file only on testbranch")
1574                 c.Check(err, FitsTypeOf, &os.PathError{})
1575                 c.Check(os.IsNotExist(err), Equals, true)
1576
1577                 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/dir1/dir2/file with mode 0644")
1578                 c.Check(err, IsNil)
1579                 c.Check(string(data), Equals, "\000\001\002\003")
1580                 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/file only on testbranch")
1581                 c.Check(err, IsNil)
1582                 c.Check(string(data), Equals, "testfile\n")
1583
1584                 cr.CleanupDirs()
1585                 checkEmpty()
1586         }
1587 }
1588
1589 func (s *TestSuite) TestStdout(c *C) {
1590         helperRecord := `{
1591                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1592                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1593                 "cwd": "/bin",
1594                 "environment": {"FROBIZ": "bilbo"},
1595                 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1596                 "output_path": "/tmp",
1597                 "priority": 1,
1598                 "runtime_constraints": {},
1599                 "state": "Locked"
1600         }`
1601
1602         api, cr, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1603                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1604                 t.logWriter.Close()
1605         })
1606
1607         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1608         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1609         c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1610 }
1611
1612 // Used by the TestStdoutWithWrongPath*()
1613 func (s *TestSuite) stdoutErrorRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, err error) {
1614         rec := arvados.Container{}
1615         err = json.Unmarshal([]byte(record), &rec)
1616         c.Check(err, IsNil)
1617
1618         s.docker.fn = fn
1619         s.docker.ImageRemove(nil, hwImageID, dockertypes.ImageRemoveOptions{})
1620
1621         api = &ArvTestClient{Container: rec}
1622         kc := &KeepTestClient{}
1623         defer kc.Close()
1624         cr, err = NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1625         c.Assert(err, IsNil)
1626         am := &ArvMountCmdLine{}
1627         cr.RunArvMount = am.ArvMountTest
1628         cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1629                 return &ArvTestClient{}, &KeepTestClient{}, nil, nil
1630         }
1631
1632         err = cr.Run()
1633         return
1634 }
1635
1636 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1637         _, _, err := s.stdoutErrorRunHelper(c, `{
1638     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1639     "output_path": "/tmp",
1640     "state": "Locked"
1641 }`, func(t *TestDockerClient) {})
1642
1643         c.Check(err, NotNil)
1644         c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
1645 }
1646
1647 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1648         _, _, err := s.stdoutErrorRunHelper(c, `{
1649     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1650     "output_path": "/tmp",
1651     "state": "Locked"
1652 }`, func(t *TestDockerClient) {})
1653
1654         c.Check(err, NotNil)
1655         c.Check(strings.Contains(err.Error(), "unsupported mount kind 'tmp' for stdout"), Equals, true)
1656 }
1657
1658 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1659         _, _, err := s.stdoutErrorRunHelper(c, `{
1660     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1661     "output_path": "/tmp",
1662     "state": "Locked"
1663 }`, func(t *TestDockerClient) {})
1664
1665         c.Check(err, NotNil)
1666         c.Check(strings.Contains(err.Error(), "unsupported mount kind 'collection' for stdout"), Equals, true)
1667 }
1668
1669 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1670         defer os.Setenv("ARVADOS_API_HOST", os.Getenv("ARVADOS_API_HOST"))
1671         os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1672         api, _, _ := s.fullRunHelper(c, `{
1673     "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1674     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1675     "cwd": "/bin",
1676     "environment": {},
1677     "mounts": {"/tmp": {"kind": "tmp"} },
1678     "output_path": "/tmp",
1679     "priority": 1,
1680     "runtime_constraints": {"API": true},
1681     "state": "Locked"
1682 }`, nil, 0, func(t *TestDockerClient) {
1683                 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
1684                 t.logWriter.Close()
1685         })
1686
1687         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1688         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1689         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "test.arvados.org\n"), Equals, true)
1690         c.Check(api.CalledWith("container.output", "d41d8cd98f00b204e9800998ecf8427e+0"), NotNil)
1691 }
1692
1693 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1694         defer os.Setenv("ARVADOS_API_HOST", os.Getenv("ARVADOS_API_HOST"))
1695         os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1696         api, _, _ := s.fullRunHelper(c, `{
1697     "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1698     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1699     "cwd": "/bin",
1700     "environment": {},
1701     "mounts": {"/tmp": {"kind": "tmp"} },
1702     "output_path": "/tmp",
1703     "priority": 1,
1704     "runtime_constraints": {"API": true},
1705     "state": "Locked"
1706 }`, nil, 0, func(t *TestDockerClient) {
1707                 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
1708                 t.logWriter.Close()
1709         })
1710
1711         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1712         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1713         c.Check(api.CalledWith("container.output", "d4ab34d3d4f8a72f5c4973051ae69fab+122"), NotNil)
1714 }
1715
1716 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1717         helperRecord := `{
1718                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1719                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1720                 "cwd": "/bin",
1721                 "environment": {"FROBIZ": "bilbo"},
1722                 "mounts": {
1723         "/tmp": {"kind": "tmp"},
1724         "/tmp/foo": {"kind": "collection",
1725                      "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1726                      "exclude_from_output": true
1727         },
1728         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1729     },
1730                 "output_path": "/tmp",
1731                 "priority": 1,
1732                 "runtime_constraints": {},
1733                 "state": "Locked"
1734         }`
1735
1736         extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1737
1738         api, cr, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1739                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1740                 t.logWriter.Close()
1741         })
1742
1743         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1744         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1745         c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1746 }
1747
1748 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1749         helperRecord := `{
1750                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1751                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1752                 "cwd": "/bin",
1753                 "environment": {"FROBIZ": "bilbo"},
1754                 "mounts": {
1755         "/tmp": {"kind": "tmp"},
1756         "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1757         "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1758         "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1759         "/tmp/foo/baz/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1760         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1761     },
1762                 "output_path": "/tmp",
1763                 "priority": 1,
1764                 "runtime_constraints": {},
1765                 "state": "Locked"
1766         }`
1767
1768         extraMounts := []string{
1769                 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1770                 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1771                 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1772         }
1773
1774         api, runner, realtemp := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1775                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1776                 t.logWriter.Close()
1777         })
1778
1779         c.Check(runner.Binds, DeepEquals, []string{realtemp + "/tmp2:/tmp",
1780                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt:/tmp/foo/bar:ro",
1781                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt:/tmp/foo/baz/sub2file2:ro",
1782                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1:/tmp/foo/sub1:ro",
1783                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt:/tmp/foo/sub1file2:ro",
1784         })
1785
1786         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1787         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1788         for _, v := range api.Content {
1789                 if v["collection"] != nil {
1790                         c.Check(v["ensure_unique_name"], Equals, true)
1791                         collection := v["collection"].(arvadosclient.Dict)
1792                         if strings.Index(collection["name"].(string), "output") == 0 {
1793                                 manifest := collection["manifest_text"].(string)
1794
1795                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1796 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:bar 36:18:sub1file2
1797 ./foo/baz 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2
1798 ./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1799 ./foo/sub1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1800 `)
1801                         }
1802                 }
1803         }
1804 }
1805
1806 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
1807         helperRecord := `{
1808                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1809                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1810                 "cwd": "/bin",
1811                 "environment": {"FROBIZ": "bilbo"},
1812                 "mounts": {
1813         "/tmp": {"kind": "tmp"},
1814         "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/subdir1/file2_in_subdir1.txt"},
1815         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1816     },
1817                 "output_path": "/tmp",
1818                 "priority": 1,
1819                 "runtime_constraints": {},
1820                 "state": "Locked"
1821         }`
1822
1823         extraMounts := []string{
1824                 "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1825         }
1826
1827         api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1828                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1829                 t.logWriter.Close()
1830         })
1831
1832         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1833         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1834         for _, v := range api.Content {
1835                 if v["collection"] != nil {
1836                         collection := v["collection"].(arvadosclient.Dict)
1837                         if strings.Index(collection["name"].(string), "output") == 0 {
1838                                 manifest := collection["manifest_text"].(string)
1839
1840                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1841 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 10:17:bar
1842 `)
1843                         }
1844                 }
1845         }
1846 }
1847
1848 func (s *TestSuite) TestOutputError(c *C) {
1849         helperRecord := `{
1850                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1851                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1852                 "cwd": "/bin",
1853                 "environment": {"FROBIZ": "bilbo"},
1854                 "mounts": {
1855                         "/tmp": {"kind": "tmp"}
1856                 },
1857                 "output_path": "/tmp",
1858                 "priority": 1,
1859                 "runtime_constraints": {},
1860                 "state": "Locked"
1861         }`
1862
1863         extraMounts := []string{}
1864
1865         api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1866                 os.Symlink("/etc/hosts", t.realTemp+"/tmp2/baz")
1867                 t.logWriter.Close()
1868         })
1869
1870         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1871 }
1872
1873 func (s *TestSuite) TestStdinCollectionMountPoint(c *C) {
1874         helperRecord := `{
1875                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1876                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1877                 "cwd": "/bin",
1878                 "environment": {"FROBIZ": "bilbo"},
1879                 "mounts": {
1880         "/tmp": {"kind": "tmp"},
1881         "stdin": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/file1_in_main.txt"},
1882         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1883     },
1884                 "output_path": "/tmp",
1885                 "priority": 1,
1886                 "runtime_constraints": {},
1887                 "state": "Locked"
1888         }`
1889
1890         extraMounts := []string{
1891                 "b0def87f80dd594d4675809e83bd4f15+367/file1_in_main.txt",
1892         }
1893
1894         api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1895                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1896                 t.logWriter.Close()
1897         })
1898
1899         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1900         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1901         for _, v := range api.Content {
1902                 if v["collection"] != nil {
1903                         collection := v["collection"].(arvadosclient.Dict)
1904                         if strings.Index(collection["name"].(string), "output") == 0 {
1905                                 manifest := collection["manifest_text"].(string)
1906                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1907 `)
1908                         }
1909                 }
1910         }
1911 }
1912
1913 func (s *TestSuite) TestStdinJsonMountPoint(c *C) {
1914         helperRecord := `{
1915                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1916                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1917                 "cwd": "/bin",
1918                 "environment": {"FROBIZ": "bilbo"},
1919                 "mounts": {
1920         "/tmp": {"kind": "tmp"},
1921         "stdin": {"kind": "json", "content": "foo"},
1922         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1923     },
1924                 "output_path": "/tmp",
1925                 "priority": 1,
1926                 "runtime_constraints": {},
1927                 "state": "Locked"
1928         }`
1929
1930         api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1931                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1932                 t.logWriter.Close()
1933         })
1934
1935         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1936         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1937         for _, v := range api.Content {
1938                 if v["collection"] != nil {
1939                         collection := v["collection"].(arvadosclient.Dict)
1940                         if strings.Index(collection["name"].(string), "output") == 0 {
1941                                 manifest := collection["manifest_text"].(string)
1942                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1943 `)
1944                         }
1945                 }
1946         }
1947 }
1948
1949 func (s *TestSuite) TestStderrMount(c *C) {
1950         api, cr, _ := s.fullRunHelper(c, `{
1951     "command": ["/bin/sh", "-c", "echo hello;exit 1"],
1952     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1953     "cwd": ".",
1954     "environment": {},
1955     "mounts": {"/tmp": {"kind": "tmp"},
1956                "stdout": {"kind": "file", "path": "/tmp/a/out.txt"},
1957                "stderr": {"kind": "file", "path": "/tmp/b/err.txt"}},
1958     "output_path": "/tmp",
1959     "priority": 1,
1960     "runtime_constraints": {},
1961     "state": "Locked"
1962 }`, nil, 1, func(t *TestDockerClient) {
1963                 t.logWriter.Write(dockerLog(1, "hello\n"))
1964                 t.logWriter.Write(dockerLog(2, "oops\n"))
1965                 t.logWriter.Close()
1966         })
1967
1968         final := api.CalledWith("container.state", "Complete")
1969         c.Assert(final, NotNil)
1970         c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1971         c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1972
1973         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)
1974 }
1975
1976 func (s *TestSuite) TestNumberRoundTrip(c *C) {
1977         kc := &KeepTestClient{}
1978         defer kc.Close()
1979         cr, err := NewContainerRunner(s.client, &ArvTestClient{callraw: true}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1980         c.Assert(err, IsNil)
1981         cr.fetchContainerRecord()
1982
1983         jsondata, err := json.Marshal(cr.Container.Mounts["/json"].Content)
1984
1985         c.Check(err, IsNil)
1986         c.Check(string(jsondata), Equals, `{"number":123456789123456789}`)
1987 }
1988
1989 func (s *TestSuite) TestFullBrokenDocker1(c *C) {
1990         tf, err := ioutil.TempFile("", "brokenNodeHook-")
1991         c.Assert(err, IsNil)
1992         defer os.Remove(tf.Name())
1993
1994         tf.Write([]byte(`#!/bin/sh
1995 exec echo killme
1996 `))
1997         tf.Close()
1998         os.Chmod(tf.Name(), 0700)
1999
2000         ech := tf.Name()
2001         brokenNodeHook = &ech
2002
2003         api, _, _ := s.fullRunHelper(c, `{
2004     "command": ["echo", "hello world"],
2005     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2006     "cwd": ".",
2007     "environment": {},
2008     "mounts": {"/tmp": {"kind": "tmp"} },
2009     "output_path": "/tmp",
2010     "priority": 1,
2011     "runtime_constraints": {},
2012     "state": "Locked"
2013 }`, nil, 2, func(t *TestDockerClient) {
2014                 t.logWriter.Write(dockerLog(1, "hello world\n"))
2015                 t.logWriter.Close()
2016         })
2017
2018         c.Check(api.CalledWith("container.state", "Queued"), NotNil)
2019         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
2020         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Running broken node hook.*")
2021         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*killme.*")
2022
2023 }
2024
2025 func (s *TestSuite) TestFullBrokenDocker2(c *C) {
2026         ech := ""
2027         brokenNodeHook = &ech
2028
2029         api, _, _ := s.fullRunHelper(c, `{
2030     "command": ["echo", "hello world"],
2031     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2032     "cwd": ".",
2033     "environment": {},
2034     "mounts": {"/tmp": {"kind": "tmp"} },
2035     "output_path": "/tmp",
2036     "priority": 1,
2037     "runtime_constraints": {},
2038     "state": "Locked"
2039 }`, nil, 2, func(t *TestDockerClient) {
2040                 t.logWriter.Write(dockerLog(1, "hello world\n"))
2041                 t.logWriter.Close()
2042         })
2043
2044         c.Check(api.CalledWith("container.state", "Queued"), NotNil)
2045         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
2046         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Writing /var/lock/crunch-run-broken to mark node as broken.*")
2047 }
2048
2049 func (s *TestSuite) TestFullBrokenDocker3(c *C) {
2050         ech := ""
2051         brokenNodeHook = &ech
2052
2053         api, _, _ := s.fullRunHelper(c, `{
2054     "command": ["echo", "hello world"],
2055     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2056     "cwd": ".",
2057     "environment": {},
2058     "mounts": {"/tmp": {"kind": "tmp"} },
2059     "output_path": "/tmp",
2060     "priority": 1,
2061     "runtime_constraints": {},
2062     "state": "Locked"
2063 }`, nil, 3, func(t *TestDockerClient) {
2064                 t.logWriter.Write(dockerLog(1, "hello world\n"))
2065                 t.logWriter.Close()
2066         })
2067
2068         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2069         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
2070 }
2071
2072 func (s *TestSuite) TestBadCommand1(c *C) {
2073         ech := ""
2074         brokenNodeHook = &ech
2075
2076         api, _, _ := s.fullRunHelper(c, `{
2077     "command": ["echo", "hello world"],
2078     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2079     "cwd": ".",
2080     "environment": {},
2081     "mounts": {"/tmp": {"kind": "tmp"} },
2082     "output_path": "/tmp",
2083     "priority": 1,
2084     "runtime_constraints": {},
2085     "state": "Locked"
2086 }`, nil, 4, func(t *TestDockerClient) {
2087                 t.logWriter.Write(dockerLog(1, "hello world\n"))
2088                 t.logWriter.Close()
2089         })
2090
2091         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2092         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2093 }
2094
2095 func (s *TestSuite) TestBadCommand2(c *C) {
2096         ech := ""
2097         brokenNodeHook = &ech
2098
2099         api, _, _ := s.fullRunHelper(c, `{
2100     "command": ["echo", "hello world"],
2101     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2102     "cwd": ".",
2103     "environment": {},
2104     "mounts": {"/tmp": {"kind": "tmp"} },
2105     "output_path": "/tmp",
2106     "priority": 1,
2107     "runtime_constraints": {},
2108     "state": "Locked"
2109 }`, nil, 5, func(t *TestDockerClient) {
2110                 t.logWriter.Write(dockerLog(1, "hello world\n"))
2111                 t.logWriter.Close()
2112         })
2113
2114         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2115         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2116 }
2117
2118 func (s *TestSuite) TestBadCommand3(c *C) {
2119         ech := ""
2120         brokenNodeHook = &ech
2121
2122         api, _, _ := s.fullRunHelper(c, `{
2123     "command": ["echo", "hello world"],
2124     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2125     "cwd": ".",
2126     "environment": {},
2127     "mounts": {"/tmp": {"kind": "tmp"} },
2128     "output_path": "/tmp",
2129     "priority": 1,
2130     "runtime_constraints": {},
2131     "state": "Locked"
2132 }`, nil, 6, func(t *TestDockerClient) {
2133                 t.logWriter.Write(dockerLog(1, "hello world\n"))
2134                 t.logWriter.Close()
2135         })
2136
2137         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2138         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2139 }
2140
2141 func (s *TestSuite) TestSecretTextMountPoint(c *C) {
2142         // under normal mounts, gets captured in output, oops
2143         helperRecord := `{
2144                 "command": ["true"],
2145                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2146                 "cwd": "/bin",
2147                 "mounts": {
2148                     "/tmp": {"kind": "tmp"},
2149                     "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2150                 },
2151                 "secret_mounts": {
2152                 },
2153                 "output_path": "/tmp",
2154                 "priority": 1,
2155                 "runtime_constraints": {},
2156                 "state": "Locked"
2157         }`
2158
2159         api, cr, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2160                 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2161                 c.Check(err, IsNil)
2162                 c.Check(content, DeepEquals, []byte("mypassword"))
2163                 t.logWriter.Close()
2164         })
2165
2166         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2167         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2168         c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), NotNil)
2169         c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ""), IsNil)
2170
2171         // under secret mounts, not captured in output
2172         helperRecord = `{
2173                 "command": ["true"],
2174                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2175                 "cwd": "/bin",
2176                 "mounts": {
2177                     "/tmp": {"kind": "tmp"}
2178                 },
2179                 "secret_mounts": {
2180                     "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2181                 },
2182                 "output_path": "/tmp",
2183                 "priority": 1,
2184                 "runtime_constraints": {},
2185                 "state": "Locked"
2186         }`
2187
2188         api, cr, _ = s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2189                 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2190                 c.Check(err, IsNil)
2191                 c.Check(content, DeepEquals, []byte("mypassword"))
2192                 t.logWriter.Close()
2193         })
2194
2195         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2196         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2197         c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), IsNil)
2198         c.Check(cr.ContainerArvClient.(*ArvTestClient).CalledWith("collection.manifest_text", ""), NotNil)
2199 }
2200
2201 type FakeProcess struct {
2202         cmdLine []string
2203 }
2204
2205 func (fp FakeProcess) CmdlineSlice() ([]string, error) {
2206         return fp.cmdLine, nil
2207 }