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