Adds checking for request body options that are both valid JSON and readable files
[arvados.git] / services / crunch-run / crunchrun_test.go
1 package main
2
3 import (
4         "bytes"
5         "crypto/md5"
6         "encoding/json"
7         "errors"
8         "fmt"
9         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
10         "git.curoverse.com/arvados.git/sdk/go/keepclient"
11         "git.curoverse.com/arvados.git/sdk/go/manifest"
12         "github.com/curoverse/dockerclient"
13         . "gopkg.in/check.v1"
14         "io"
15         "io/ioutil"
16         "strings"
17         "syscall"
18         "testing"
19         "time"
20 )
21
22 // Gocheck boilerplate
23 func TestCrunchExec(t *testing.T) {
24         TestingT(t)
25 }
26
27 type TestSuite struct{}
28
29 // Gocheck boilerplate
30 var _ = Suite(&TestSuite{})
31
32 type ArvTestClient struct {
33         Total   int64
34         Calls   int
35         Content arvadosclient.Dict
36         ContainerRecord
37         Logs          map[string]*bytes.Buffer
38         WasSetRunning bool
39 }
40
41 type KeepTestClient struct {
42         Called  bool
43         Content []byte
44 }
45
46 var hwManifest = ". 82ab40c24fc8df01798e57ba66795bb1+841216+Aa124ac75e5168396c73c0a18eda641a4f41791c0@569fa8c3 0:841216:9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7.tar\n"
47 var hwPDH = "a45557269dcb65a6b78f9ac061c0850b+120"
48 var hwImageId = "9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7"
49
50 var otherManifest = ". 68a84f561b1d1708c6baff5e019a9ab3+46+Ae5d0af96944a3690becb1decdf60cc1c937f556d@5693216f 0:46:md5sum.txt\n"
51 var otherPDH = "a3e8f74c6f101eae01fa08bfb4e49b3a+54"
52
53 type TestDockerClient struct {
54         imageLoaded  string
55         stdoutReader io.ReadCloser
56         stderrReader io.ReadCloser
57         stdoutWriter io.WriteCloser
58         stderrWriter io.WriteCloser
59         fn           func(t *TestDockerClient)
60         finish       chan dockerclient.WaitResult
61         stop         chan bool
62         cwd          string
63         env          []string
64 }
65
66 func NewTestDockerClient() *TestDockerClient {
67         t := &TestDockerClient{}
68         t.stdoutReader, t.stdoutWriter = io.Pipe()
69         t.stderrReader, t.stderrWriter = io.Pipe()
70         t.finish = make(chan dockerclient.WaitResult)
71         t.stop = make(chan bool)
72         t.cwd = "/"
73         return t
74 }
75
76 func (t *TestDockerClient) StopContainer(id string, timeout int) error {
77         t.stop <- true
78         return nil
79 }
80
81 func (t *TestDockerClient) InspectImage(id string) (*dockerclient.ImageInfo, error) {
82         if t.imageLoaded == id {
83                 return &dockerclient.ImageInfo{}, nil
84         } else {
85                 return nil, errors.New("")
86         }
87 }
88
89 func (t *TestDockerClient) LoadImage(reader io.Reader) error {
90         _, err := io.Copy(ioutil.Discard, reader)
91         if err != nil {
92                 return err
93         } else {
94                 t.imageLoaded = hwImageId
95                 return nil
96         }
97 }
98
99 func (t *TestDockerClient) CreateContainer(config *dockerclient.ContainerConfig, name string, authConfig *dockerclient.AuthConfig) (string, error) {
100         if config.WorkingDir != "" {
101                 t.cwd = config.WorkingDir
102         }
103         t.env = config.Env
104         return "abcde", nil
105 }
106
107 func (t *TestDockerClient) StartContainer(id string, config *dockerclient.HostConfig) error {
108         if id == "abcde" {
109                 go t.fn(t)
110                 return nil
111         } else {
112                 return errors.New("Invalid container id")
113         }
114 }
115
116 func (t *TestDockerClient) ContainerLogs(id string, options *dockerclient.LogOptions) (io.ReadCloser, error) {
117         if options.Stdout {
118                 return t.stdoutReader, nil
119         }
120         if options.Stderr {
121                 return t.stderrReader, nil
122         }
123         return nil, nil
124 }
125
126 func (t *TestDockerClient) Wait(id string) <-chan dockerclient.WaitResult {
127         return t.finish
128 }
129
130 func (*TestDockerClient) RemoveImage(name string, force bool) ([]*dockerclient.ImageDelete, error) {
131         return nil, nil
132 }
133
134 func (this *ArvTestClient) Create(resourceType string,
135         parameters arvadosclient.Dict,
136         output interface{}) error {
137
138         this.Calls += 1
139         this.Content = parameters
140
141         if resourceType == "logs" {
142                 et := parameters["event_type"].(string)
143                 if this.Logs == nil {
144                         this.Logs = make(map[string]*bytes.Buffer)
145                 }
146                 if this.Logs[et] == nil {
147                         this.Logs[et] = &bytes.Buffer{}
148                 }
149                 this.Logs[et].Write([]byte(parameters["properties"].(map[string]string)["text"]))
150         }
151
152         if resourceType == "collections" && output != nil {
153                 mt := parameters["manifest_text"].(string)
154                 outmap := output.(map[string]string)
155                 outmap["portable_data_hash"] = fmt.Sprintf("%x+%d", md5.Sum([]byte(mt)), len(mt))
156         }
157
158         return nil
159 }
160
161 func (this *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
162         if resourceType == "collections" {
163                 if uuid == hwPDH {
164                         output.(*Collection).ManifestText = hwManifest
165                 } else if uuid == otherPDH {
166                         output.(*Collection).ManifestText = otherManifest
167                 }
168         }
169         if resourceType == "containers" {
170                 (*output.(*ContainerRecord)) = this.ContainerRecord
171         }
172         return nil
173 }
174
175 func (this *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
176
177         this.Content = parameters
178         if resourceType == "containers" {
179                 if parameters["state"] == "Running" {
180                         this.WasSetRunning = true
181                 }
182
183         }
184         return nil
185 }
186
187 func (this *KeepTestClient) PutHB(hash string, buf []byte) (string, int, error) {
188         this.Content = buf
189         return fmt.Sprintf("%s+%d", hash, len(buf)), len(buf), nil
190 }
191
192 type FileWrapper struct {
193         io.ReadCloser
194         len uint64
195 }
196
197 func (this FileWrapper) Len() uint64 {
198         return this.len
199 }
200
201 func (this *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.ReadCloserWithLen, error) {
202         if filename == hwImageId+".tar" {
203                 rdr := ioutil.NopCloser(&bytes.Buffer{})
204                 this.Called = true
205                 return FileWrapper{rdr, 1321984}, nil
206         }
207         return nil, nil
208 }
209
210 func (s *TestSuite) TestLoadImage(c *C) {
211         kc := &KeepTestClient{}
212         docker := NewTestDockerClient()
213         cr := NewContainerRunner(&ArvTestClient{}, kc, docker)
214
215         _, err := cr.Docker.RemoveImage(hwImageId, true)
216
217         _, err = cr.Docker.InspectImage(hwImageId)
218         c.Check(err, NotNil)
219
220         cr.ContainerRecord.ContainerImage = hwPDH
221
222         // (1) Test loading image from keep
223         c.Check(kc.Called, Equals, false)
224         c.Check(cr.ContainerConfig.Image, Equals, "")
225
226         err = cr.LoadImage()
227
228         c.Check(err, IsNil)
229         defer func() {
230                 cr.Docker.RemoveImage(hwImageId, true)
231         }()
232
233         c.Check(kc.Called, Equals, true)
234         c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
235
236         _, err = cr.Docker.InspectImage(hwImageId)
237         c.Check(err, IsNil)
238
239         // (2) Test using image that's already loaded
240         kc.Called = false
241         cr.ContainerConfig.Image = ""
242
243         err = cr.LoadImage()
244         c.Check(err, IsNil)
245         c.Check(kc.Called, Equals, false)
246         c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
247
248 }
249
250 type ArvErrorTestClient struct{}
251 type KeepErrorTestClient struct{}
252 type KeepReadErrorTestClient struct{}
253
254 func (this ArvErrorTestClient) Create(resourceType string,
255         parameters arvadosclient.Dict,
256         output interface{}) error {
257         return nil
258 }
259
260 func (this ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
261         return errors.New("ArvError")
262 }
263
264 func (this ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
265         return nil
266 }
267
268 func (this KeepErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
269         return "", 0, nil
270 }
271
272 func (this KeepErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.ReadCloserWithLen, error) {
273         return nil, errors.New("KeepError")
274 }
275
276 func (this KeepReadErrorTestClient) PutHB(hash string, buf []byte) (string, int, error) {
277         return "", 0, nil
278 }
279
280 type ErrorReader struct{}
281
282 func (this ErrorReader) Read(p []byte) (n int, err error) {
283         return 0, errors.New("ErrorReader")
284 }
285
286 func (this ErrorReader) Close() error {
287         return nil
288 }
289
290 func (this ErrorReader) Len() uint64 {
291         return 0
292 }
293
294 func (this KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (keepclient.ReadCloserWithLen, error) {
295         return ErrorReader{}, nil
296 }
297
298 func (s *TestSuite) TestLoadImageArvError(c *C) {
299         // (1) Arvados error
300         cr := NewContainerRunner(ArvErrorTestClient{}, &KeepTestClient{}, nil)
301         cr.ContainerRecord.ContainerImage = hwPDH
302
303         err := cr.LoadImage()
304         c.Check(err.Error(), Equals, "ArvError")
305 }
306
307 func (s *TestSuite) TestLoadImageKeepError(c *C) {
308         // (2) Keep error
309         docker := NewTestDockerClient()
310         cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, docker)
311         cr.ContainerRecord.ContainerImage = hwPDH
312
313         err := cr.LoadImage()
314         c.Check(err.Error(), Equals, "KeepError")
315 }
316
317 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
318         // (3) Collection doesn't contain image
319         cr := NewContainerRunner(&ArvTestClient{}, KeepErrorTestClient{}, nil)
320         cr.ContainerRecord.ContainerImage = otherPDH
321
322         err := cr.LoadImage()
323         c.Check(err.Error(), Equals, "First file in the collection does not end in .tar")
324 }
325
326 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
327         // (4) Collection doesn't contain image
328         docker := NewTestDockerClient()
329         cr := NewContainerRunner(&ArvTestClient{}, KeepReadErrorTestClient{}, docker)
330         cr.ContainerRecord.ContainerImage = hwPDH
331
332         err := cr.LoadImage()
333         c.Check(err, NotNil)
334 }
335
336 type ClosableBuffer struct {
337         bytes.Buffer
338 }
339
340 type TestLogs struct {
341         Stdout ClosableBuffer
342         Stderr ClosableBuffer
343 }
344
345 func (this *ClosableBuffer) Close() error {
346         return nil
347 }
348
349 func (this *TestLogs) NewTestLoggingWriter(logstr string) io.WriteCloser {
350         if logstr == "stdout" {
351                 return &this.Stdout
352         }
353         if logstr == "stderr" {
354                 return &this.Stderr
355         }
356         return nil
357 }
358
359 func (s *TestSuite) TestRunContainer(c *C) {
360         docker := NewTestDockerClient()
361         docker.fn = func(t *TestDockerClient) {
362                 t.stdoutWriter.Write([]byte("Hello world\n"))
363                 t.stdoutWriter.Close()
364                 t.stderrWriter.Close()
365                 t.finish <- dockerclient.WaitResult{}
366         }
367         cr := NewContainerRunner(&ArvTestClient{}, &KeepTestClient{}, docker)
368
369         var logs TestLogs
370         cr.NewLogWriter = logs.NewTestLoggingWriter
371         cr.ContainerRecord.ContainerImage = hwPDH
372         cr.ContainerRecord.Command = []string{"./hw"}
373         err := cr.LoadImage()
374         c.Check(err, IsNil)
375
376         err = cr.StartContainer()
377         c.Check(err, IsNil)
378
379         err = cr.AttachLogs()
380         c.Check(err, IsNil)
381
382         err = cr.WaitFinish()
383         c.Check(err, IsNil)
384
385         c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
386         c.Check(logs.Stderr.String(), Equals, "")
387 }
388
389 func (s *TestSuite) TestCommitLogs(c *C) {
390         api := &ArvTestClient{}
391         kc := &KeepTestClient{}
392         cr := NewContainerRunner(api, kc, nil)
393         cr.ContainerRecord.UUID = "zzzzz-zzzzz-zzzzzzzzzzzzzzz"
394         cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
395
396         cr.CrunchLog.Print("Hello world!")
397         cr.CrunchLog.Print("Goodbye")
398         cr.finalState = "Complete"
399
400         err := cr.CommitLogs()
401         c.Check(err, IsNil)
402
403         c.Check(api.Content["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
404         c.Check(api.Content["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
405         c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
406 }
407
408 func (s *TestSuite) TestUpdateContainerRecordRunning(c *C) {
409         api := &ArvTestClient{}
410         kc := &KeepTestClient{}
411         cr := NewContainerRunner(api, kc, nil)
412         cr.ContainerRecord.UUID = "zzzzz-zzzzz-zzzzzzzzzzzzzzz"
413
414         err := cr.UpdateContainerRecordRunning()
415         c.Check(err, IsNil)
416
417         c.Check(api.Content["state"], Equals, "Running")
418 }
419
420 func (s *TestSuite) TestUpdateContainerRecordComplete(c *C) {
421         api := &ArvTestClient{}
422         kc := &KeepTestClient{}
423         cr := NewContainerRunner(api, kc, nil)
424         cr.ContainerRecord.UUID = "zzzzz-zzzzz-zzzzzzzzzzzzzzz"
425
426         cr.LogsPDH = new(string)
427         *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
428
429         cr.ExitCode = new(int)
430         *cr.ExitCode = 42
431         cr.finalState = "Complete"
432
433         err := cr.UpdateContainerRecordComplete()
434         c.Check(err, IsNil)
435
436         c.Check(api.Content["log"], Equals, *cr.LogsPDH)
437         c.Check(api.Content["exit_code"], Equals, *cr.ExitCode)
438         c.Check(api.Content["state"], Equals, "Complete")
439 }
440
441 func (s *TestSuite) TestUpdateContainerRecordCancelled(c *C) {
442         api := &ArvTestClient{}
443         kc := &KeepTestClient{}
444         cr := NewContainerRunner(api, kc, nil)
445         cr.ContainerRecord.UUID = "zzzzz-zzzzz-zzzzzzzzzzzzzzz"
446         cr.Cancelled = true
447         cr.finalState = "Cancelled"
448
449         err := cr.UpdateContainerRecordComplete()
450         c.Check(err, IsNil)
451
452         c.Check(api.Content["log"], IsNil)
453         c.Check(api.Content["exit_code"], IsNil)
454         c.Check(api.Content["state"], Equals, "Cancelled")
455 }
456
457 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
458 // dress rehersal of the Run() function, starting from a JSON container record.
459 func FullRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner) {
460         rec := ContainerRecord{}
461         err := json.NewDecoder(strings.NewReader(record)).Decode(&rec)
462         c.Check(err, IsNil)
463
464         docker := NewTestDockerClient()
465         docker.fn = fn
466         docker.RemoveImage(hwImageId, true)
467
468         api = &ArvTestClient{ContainerRecord: rec}
469         cr = NewContainerRunner(api, &KeepTestClient{}, docker)
470
471         err = cr.Run("zzzzz-zzzzz-zzzzzzzzzzzzzzz")
472         c.Check(err, IsNil)
473         c.Check(api.WasSetRunning, Equals, true)
474
475         c.Check(api.Content["log"], NotNil)
476
477         if err != nil {
478                 for k, v := range api.Logs {
479                         c.Log(k)
480                         c.Log(v.String())
481                 }
482         }
483
484         return
485 }
486
487 func (s *TestSuite) TestFullRunHello(c *C) {
488         api, _ := FullRunHelper(c, `{
489     "command": ["echo", "hello world"],
490     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
491     "cwd": ".",
492     "environment": {},
493     "mounts": {},
494     "output_path": "/tmp",
495     "priority": 1,
496     "runtime_constraints": {}
497 }`, func(t *TestDockerClient) {
498                 t.stdoutWriter.Write([]byte("hello world\n"))
499                 t.stdoutWriter.Close()
500                 t.stderrWriter.Close()
501                 t.finish <- dockerclient.WaitResult{}
502         })
503
504         c.Check(api.Content["exit_code"], Equals, 0)
505         c.Check(api.Content["state"], Equals, "Complete")
506
507         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
508
509 }
510
511 func (s *TestSuite) TestFullRunStderr(c *C) {
512         api, _ := FullRunHelper(c, `{
513     "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
514     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
515     "cwd": ".",
516     "environment": {},
517     "mounts": {},
518     "output_path": "/tmp",
519     "priority": 1,
520     "runtime_constraints": {}
521 }`, func(t *TestDockerClient) {
522                 t.stdoutWriter.Write([]byte("hello\n"))
523                 t.stderrWriter.Write([]byte("world\n"))
524                 t.stdoutWriter.Close()
525                 t.stderrWriter.Close()
526                 t.finish <- dockerclient.WaitResult{ExitCode: 1}
527         })
528
529         c.Check(api.Content["log"], NotNil)
530         c.Check(api.Content["exit_code"], Equals, 1)
531         c.Check(api.Content["state"], Equals, "Complete")
532
533         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
534         c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
535 }
536
537 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
538         api, _ := FullRunHelper(c, `{
539     "command": ["pwd"],
540     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
541     "cwd": ".",
542     "environment": {},
543     "mounts": {},
544     "output_path": "/tmp",
545     "priority": 1,
546     "runtime_constraints": {}
547 }`, func(t *TestDockerClient) {
548                 t.stdoutWriter.Write([]byte(t.cwd + "\n"))
549                 t.stdoutWriter.Close()
550                 t.stderrWriter.Close()
551                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
552         })
553
554         c.Check(api.Content["exit_code"], Equals, 0)
555         c.Check(api.Content["state"], Equals, "Complete")
556
557         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
558 }
559
560 func (s *TestSuite) TestFullRunSetCwd(c *C) {
561         api, _ := FullRunHelper(c, `{
562     "command": ["pwd"],
563     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
564     "cwd": "/bin",
565     "environment": {},
566     "mounts": {},
567     "output_path": "/tmp",
568     "priority": 1,
569     "runtime_constraints": {}
570 }`, func(t *TestDockerClient) {
571                 t.stdoutWriter.Write([]byte(t.cwd + "\n"))
572                 t.stdoutWriter.Close()
573                 t.stderrWriter.Close()
574                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
575         })
576
577         c.Check(api.Content["exit_code"], Equals, 0)
578         c.Check(api.Content["state"], Equals, "Complete")
579
580         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
581 }
582
583 func (s *TestSuite) TestCancel(c *C) {
584         record := `{
585     "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
586     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
587     "cwd": ".",
588     "environment": {},
589     "mounts": {},
590     "output_path": "/tmp",
591     "priority": 1,
592     "runtime_constraints": {}
593 }`
594
595         rec := ContainerRecord{}
596         err := json.NewDecoder(strings.NewReader(record)).Decode(&rec)
597         c.Check(err, IsNil)
598
599         docker := NewTestDockerClient()
600         docker.fn = func(t *TestDockerClient) {
601                 <-t.stop
602                 t.stdoutWriter.Write([]byte("foo\n"))
603                 t.stdoutWriter.Close()
604                 t.stderrWriter.Close()
605                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
606         }
607         docker.RemoveImage(hwImageId, true)
608
609         api := &ArvTestClient{ContainerRecord: rec}
610         cr := NewContainerRunner(api, &KeepTestClient{}, docker)
611
612         go func() {
613                 for cr.ContainerID == "" {
614                         time.Sleep(1 * time.Second)
615                 }
616                 cr.SigChan <- syscall.SIGINT
617         }()
618
619         err = cr.Run("zzzzz-zzzzz-zzzzzzzzzzzzzzz")
620
621         c.Check(err, IsNil)
622
623         c.Check(api.Content["log"], NotNil)
624
625         if err != nil {
626                 for k, v := range api.Logs {
627                         c.Log(k)
628                         c.Log(v.String())
629                 }
630         }
631
632         c.Check(api.Content["state"], Equals, "Cancelled")
633
634         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "foo\n"), Equals, true)
635
636 }
637
638 func (s *TestSuite) TestFullRunSetEnv(c *C) {
639         api, _ := FullRunHelper(c, `{
640     "command": ["/bin/sh", "-c", "echo $FROBIZ"],
641     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
642     "cwd": "/bin",
643     "environment": {"FROBIZ": "bilbo"},
644     "mounts": {},
645     "output_path": "/tmp",
646     "priority": 1,
647     "runtime_constraints": {}
648 }`, func(t *TestDockerClient) {
649                 t.stdoutWriter.Write([]byte(t.env[0][7:] + "\n"))
650                 t.stdoutWriter.Close()
651                 t.stderrWriter.Close()
652                 t.finish <- dockerclient.WaitResult{ExitCode: 0}
653         })
654
655         c.Check(api.Content["exit_code"], Equals, 0)
656         c.Check(api.Content["state"], Equals, "Complete")
657
658         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)
659 }