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