7491: Add test that default replication is read from discovery document.
[arvados.git] / sdk / go / keepclient / keepclient_test.go
1 package keepclient
2
3 import (
4         "crypto/md5"
5         "flag"
6         "fmt"
7         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
8         "git.curoverse.com/arvados.git/sdk/go/arvadostest"
9         "git.curoverse.com/arvados.git/sdk/go/streamer"
10         . "gopkg.in/check.v1"
11         "io"
12         "io/ioutil"
13         "log"
14         "net"
15         "net/http"
16         "os"
17         "testing"
18 )
19
20 // Gocheck boilerplate
21 func Test(t *testing.T) {
22         TestingT(t)
23 }
24
25 // Gocheck boilerplate
26 var _ = Suite(&ServerRequiredSuite{})
27 var _ = Suite(&StandaloneSuite{})
28
29 var no_server = flag.Bool("no-server", false, "Skip 'ServerRequireSuite'")
30
31 // Tests that require the Keep server running
32 type ServerRequiredSuite struct{}
33
34 // Standalone tests
35 type StandaloneSuite struct{}
36
37 func pythonDir() string {
38         cwd, _ := os.Getwd()
39         return fmt.Sprintf("%s/../../python/tests", cwd)
40 }
41
42 func (s *ServerRequiredSuite) SetUpSuite(c *C) {
43         if *no_server {
44                 c.Skip("Skipping tests that require server")
45                 return
46         }
47         arvadostest.StartAPI()
48         arvadostest.StartKeep()
49 }
50
51 func (s *ServerRequiredSuite) TearDownSuite(c *C) {
52         if *no_server {
53                 return
54         }
55         arvadostest.StopKeep()
56         arvadostest.StopAPI()
57 }
58
59 func (s *ServerRequiredSuite) TestMakeKeepClient(c *C) {
60         arv, err := arvadosclient.MakeArvadosClient()
61         c.Assert(err, Equals, nil)
62
63         kc, err := MakeKeepClient(&arv)
64
65         c.Assert(err, Equals, nil)
66         c.Check(len(kc.LocalRoots()), Equals, 2)
67         for _, root := range kc.LocalRoots() {
68                 c.Check(root, Matches, "http://localhost:\\d+")
69         }
70 }
71
72 func (s *ServerRequiredSuite) TestDefaultReplications(c *C) {
73         arv, err := arvadosclient.MakeArvadosClient()
74         c.Assert(err, Equals, nil)
75
76         kc, err := MakeKeepClient(&arv)
77         c.Assert(kc.Want_replicas, Equals, 2)
78
79         arv.DiscoveryDoc["defaultCollectionReplication"] = 3.0
80         kc, err = MakeKeepClient(&arv)
81         c.Assert(kc.Want_replicas, Equals, 3)
82
83         arv.DiscoveryDoc["defaultCollectionReplication"] = 1.0
84         kc, err = MakeKeepClient(&arv)
85         c.Assert(kc.Want_replicas, Equals, 1)
86 }
87
88 type StubPutHandler struct {
89         c              *C
90         expectPath     string
91         expectApiToken string
92         expectBody     string
93         handled        chan string
94 }
95
96 func (sph StubPutHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
97         sph.c.Check(req.URL.Path, Equals, "/"+sph.expectPath)
98         sph.c.Check(req.Header.Get("Authorization"), Equals, fmt.Sprintf("OAuth2 %s", sph.expectApiToken))
99         body, err := ioutil.ReadAll(req.Body)
100         sph.c.Check(err, Equals, nil)
101         sph.c.Check(body, DeepEquals, []byte(sph.expectBody))
102         resp.WriteHeader(200)
103         sph.handled <- fmt.Sprintf("http://%s", req.Host)
104 }
105
106 func RunFakeKeepServer(st http.Handler) (ks KeepServer) {
107         var err error
108         ks.listener, err = net.ListenTCP("tcp", &net.TCPAddr{Port: 0})
109         if err != nil {
110                 panic(fmt.Sprintf("Could not listen on any port"))
111         }
112         ks.url = fmt.Sprintf("http://%s", ks.listener.Addr().String())
113         go http.Serve(ks.listener, st)
114         return
115 }
116
117 func UploadToStubHelper(c *C, st http.Handler, f func(*KeepClient, string,
118         io.ReadCloser, io.WriteCloser, chan uploadStatus)) {
119
120         ks := RunFakeKeepServer(st)
121         defer ks.listener.Close()
122
123         arv, _ := arvadosclient.MakeArvadosClient()
124         arv.ApiToken = "abc123"
125
126         kc, _ := MakeKeepClient(&arv)
127
128         reader, writer := io.Pipe()
129         upload_status := make(chan uploadStatus)
130
131         f(kc, ks.url, reader, writer, upload_status)
132 }
133
134 func (s *StandaloneSuite) TestUploadToStubKeepServer(c *C) {
135         log.Printf("TestUploadToStubKeepServer")
136
137         st := StubPutHandler{
138                 c,
139                 "acbd18db4cc2f85cedef654fccc4a4d8",
140                 "abc123",
141                 "foo",
142                 make(chan string)}
143
144         UploadToStubHelper(c, st,
145                 func(kc *KeepClient, url string, reader io.ReadCloser,
146                         writer io.WriteCloser, upload_status chan uploadStatus) {
147
148                         go kc.uploadToKeepServer(url, st.expectPath, reader, upload_status, int64(len("foo")), "TestUploadToStubKeepServer")
149
150                         writer.Write([]byte("foo"))
151                         writer.Close()
152
153                         <-st.handled
154                         status := <-upload_status
155                         c.Check(status, DeepEquals, uploadStatus{nil, fmt.Sprintf("%s/%s", url, st.expectPath), 200, 1, ""})
156                 })
157
158         log.Printf("TestUploadToStubKeepServer done")
159 }
160
161 func (s *StandaloneSuite) TestUploadToStubKeepServerBufferReader(c *C) {
162         log.Printf("TestUploadToStubKeepServerBufferReader")
163
164         st := StubPutHandler{
165                 c,
166                 "acbd18db4cc2f85cedef654fccc4a4d8",
167                 "abc123",
168                 "foo",
169                 make(chan string)}
170
171         UploadToStubHelper(c, st,
172                 func(kc *KeepClient, url string, reader io.ReadCloser,
173                         writer io.WriteCloser, upload_status chan uploadStatus) {
174
175                         tr := streamer.AsyncStreamFromReader(512, reader)
176                         defer tr.Close()
177
178                         br1 := tr.MakeStreamReader()
179
180                         go kc.uploadToKeepServer(url, st.expectPath, br1, upload_status, 3, "TestUploadToStubKeepServerBufferReader")
181
182                         writer.Write([]byte("foo"))
183                         writer.Close()
184
185                         <-st.handled
186
187                         status := <-upload_status
188                         c.Check(status, DeepEquals, uploadStatus{nil, fmt.Sprintf("%s/%s", url, st.expectPath), 200, 1, ""})
189                 })
190
191         log.Printf("TestUploadToStubKeepServerBufferReader done")
192 }
193
194 type FailHandler struct {
195         handled chan string
196 }
197
198 func (fh FailHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
199         resp.WriteHeader(500)
200         fh.handled <- fmt.Sprintf("http://%s", req.Host)
201 }
202
203 type FailThenSucceedHandler struct {
204         handled        chan string
205         count          int
206         successhandler StubGetHandler
207 }
208
209 func (fh *FailThenSucceedHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
210         if fh.count == 0 {
211                 resp.WriteHeader(500)
212                 fh.count += 1
213                 fh.handled <- fmt.Sprintf("http://%s", req.Host)
214         } else {
215                 fh.successhandler.ServeHTTP(resp, req)
216         }
217 }
218
219 type Error404Handler struct {
220         handled chan string
221 }
222
223 func (fh Error404Handler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
224         resp.WriteHeader(404)
225         fh.handled <- fmt.Sprintf("http://%s", req.Host)
226 }
227
228 func (s *StandaloneSuite) TestFailedUploadToStubKeepServer(c *C) {
229         log.Printf("TestFailedUploadToStubKeepServer")
230
231         st := FailHandler{
232                 make(chan string)}
233
234         hash := "acbd18db4cc2f85cedef654fccc4a4d8"
235
236         UploadToStubHelper(c, st,
237                 func(kc *KeepClient, url string, reader io.ReadCloser,
238                         writer io.WriteCloser, upload_status chan uploadStatus) {
239
240                         go kc.uploadToKeepServer(url, hash, reader, upload_status, 3, "TestFailedUploadToStubKeepServer")
241
242                         writer.Write([]byte("foo"))
243                         writer.Close()
244
245                         <-st.handled
246
247                         status := <-upload_status
248                         c.Check(status.url, Equals, fmt.Sprintf("%s/%s", url, hash))
249                         c.Check(status.statusCode, Equals, 500)
250                 })
251         log.Printf("TestFailedUploadToStubKeepServer done")
252 }
253
254 type KeepServer struct {
255         listener net.Listener
256         url      string
257 }
258
259 func RunSomeFakeKeepServers(st http.Handler, n int) (ks []KeepServer) {
260         ks = make([]KeepServer, n)
261
262         for i := 0; i < n; i += 1 {
263                 ks[i] = RunFakeKeepServer(st)
264         }
265
266         return ks
267 }
268
269 func (s *StandaloneSuite) TestPutB(c *C) {
270         log.Printf("TestPutB")
271
272         hash := Md5String("foo")
273
274         st := StubPutHandler{
275                 c,
276                 hash,
277                 "abc123",
278                 "foo",
279                 make(chan string, 5)}
280
281         arv, _ := arvadosclient.MakeArvadosClient()
282         kc, _ := MakeKeepClient(&arv)
283
284         kc.Want_replicas = 2
285         arv.ApiToken = "abc123"
286         localRoots := make(map[string]string)
287         writableLocalRoots := make(map[string]string)
288
289         ks := RunSomeFakeKeepServers(st, 5)
290
291         for i, k := range ks {
292                 localRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", i)] = k.url
293                 writableLocalRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", i)] = k.url
294                 defer k.listener.Close()
295         }
296
297         kc.SetServiceRoots(localRoots, writableLocalRoots, nil)
298
299         kc.PutB([]byte("foo"))
300
301         shuff := NewRootSorter(
302                 kc.LocalRoots(), Md5String("foo")).GetSortedRoots()
303
304         s1 := <-st.handled
305         s2 := <-st.handled
306         c.Check((s1 == shuff[0] && s2 == shuff[1]) ||
307                 (s1 == shuff[1] && s2 == shuff[0]),
308                 Equals,
309                 true)
310
311         log.Printf("TestPutB done")
312 }
313
314 func (s *StandaloneSuite) TestPutHR(c *C) {
315         log.Printf("TestPutHR")
316
317         hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
318
319         st := StubPutHandler{
320                 c,
321                 hash,
322                 "abc123",
323                 "foo",
324                 make(chan string, 5)}
325
326         arv, _ := arvadosclient.MakeArvadosClient()
327         kc, _ := MakeKeepClient(&arv)
328
329         kc.Want_replicas = 2
330         arv.ApiToken = "abc123"
331         localRoots := make(map[string]string)
332         writableLocalRoots := make(map[string]string)
333
334         ks := RunSomeFakeKeepServers(st, 5)
335
336         for i, k := range ks {
337                 localRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", i)] = k.url
338                 writableLocalRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", i)] = k.url
339                 defer k.listener.Close()
340         }
341
342         kc.SetServiceRoots(localRoots, writableLocalRoots, nil)
343
344         reader, writer := io.Pipe()
345
346         go func() {
347                 writer.Write([]byte("foo"))
348                 writer.Close()
349         }()
350
351         kc.PutHR(hash, reader, 3)
352
353         shuff := NewRootSorter(kc.LocalRoots(), hash).GetSortedRoots()
354         log.Print(shuff)
355
356         s1 := <-st.handled
357         s2 := <-st.handled
358
359         c.Check((s1 == shuff[0] && s2 == shuff[1]) ||
360                 (s1 == shuff[1] && s2 == shuff[0]),
361                 Equals,
362                 true)
363
364         log.Printf("TestPutHR done")
365 }
366
367 func (s *StandaloneSuite) TestPutWithFail(c *C) {
368         log.Printf("TestPutWithFail")
369
370         hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
371
372         st := StubPutHandler{
373                 c,
374                 hash,
375                 "abc123",
376                 "foo",
377                 make(chan string, 4)}
378
379         fh := FailHandler{
380                 make(chan string, 1)}
381
382         arv, err := arvadosclient.MakeArvadosClient()
383         kc, _ := MakeKeepClient(&arv)
384
385         kc.Want_replicas = 2
386         arv.ApiToken = "abc123"
387         localRoots := make(map[string]string)
388         writableLocalRoots := make(map[string]string)
389
390         ks1 := RunSomeFakeKeepServers(st, 4)
391         ks2 := RunSomeFakeKeepServers(fh, 1)
392
393         for i, k := range ks1 {
394                 localRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", i)] = k.url
395                 writableLocalRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", i)] = k.url
396                 defer k.listener.Close()
397         }
398         for i, k := range ks2 {
399                 localRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", i+len(ks1))] = k.url
400                 writableLocalRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", i+len(ks1))] = k.url
401                 defer k.listener.Close()
402         }
403
404         kc.SetServiceRoots(localRoots, writableLocalRoots, nil)
405
406         shuff := NewRootSorter(
407                 kc.LocalRoots(), Md5String("foo")).GetSortedRoots()
408
409         phash, replicas, err := kc.PutB([]byte("foo"))
410
411         <-fh.handled
412
413         c.Check(err, Equals, nil)
414         c.Check(phash, Equals, "")
415         c.Check(replicas, Equals, 2)
416
417         s1 := <-st.handled
418         s2 := <-st.handled
419
420         c.Check((s1 == shuff[1] && s2 == shuff[2]) ||
421                 (s1 == shuff[2] && s2 == shuff[1]),
422                 Equals,
423                 true)
424 }
425
426 func (s *StandaloneSuite) TestPutWithTooManyFail(c *C) {
427         log.Printf("TestPutWithTooManyFail")
428
429         hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
430
431         st := StubPutHandler{
432                 c,
433                 hash,
434                 "abc123",
435                 "foo",
436                 make(chan string, 1)}
437
438         fh := FailHandler{
439                 make(chan string, 4)}
440
441         arv, err := arvadosclient.MakeArvadosClient()
442         kc, _ := MakeKeepClient(&arv)
443
444         kc.Want_replicas = 2
445         arv.ApiToken = "abc123"
446         localRoots := make(map[string]string)
447         writableLocalRoots := make(map[string]string)
448
449         ks1 := RunSomeFakeKeepServers(st, 1)
450         ks2 := RunSomeFakeKeepServers(fh, 4)
451
452         for i, k := range ks1 {
453                 localRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", i)] = k.url
454                 writableLocalRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", i)] = k.url
455                 defer k.listener.Close()
456         }
457         for i, k := range ks2 {
458                 localRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", i+len(ks1))] = k.url
459                 writableLocalRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", i+len(ks1))] = k.url
460                 defer k.listener.Close()
461         }
462
463         kc.SetServiceRoots(localRoots, writableLocalRoots, nil)
464
465         _, replicas, err := kc.PutB([]byte("foo"))
466
467         c.Check(err, Equals, InsufficientReplicasError)
468         c.Check(replicas, Equals, 1)
469         c.Check(<-st.handled, Equals, ks1[0].url)
470
471         log.Printf("TestPutWithTooManyFail done")
472 }
473
474 type StubGetHandler struct {
475         c              *C
476         expectPath     string
477         expectApiToken string
478         httpStatus     int
479         body           []byte
480 }
481
482 func (sgh StubGetHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
483         sgh.c.Check(req.URL.Path, Equals, "/"+sgh.expectPath)
484         sgh.c.Check(req.Header.Get("Authorization"), Equals, fmt.Sprintf("OAuth2 %s", sgh.expectApiToken))
485         resp.WriteHeader(sgh.httpStatus)
486         resp.Header().Set("Content-Length", fmt.Sprintf("%d", len(sgh.body)))
487         resp.Write(sgh.body)
488 }
489
490 func (s *StandaloneSuite) TestGet(c *C) {
491         log.Printf("TestGet")
492
493         hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
494
495         st := StubGetHandler{
496                 c,
497                 hash,
498                 "abc123",
499                 http.StatusOK,
500                 []byte("foo")}
501
502         ks := RunFakeKeepServer(st)
503         defer ks.listener.Close()
504
505         arv, err := arvadosclient.MakeArvadosClient()
506         kc, _ := MakeKeepClient(&arv)
507         arv.ApiToken = "abc123"
508         kc.SetServiceRoots(map[string]string{"x": ks.url}, map[string]string{ks.url: ""}, nil)
509
510         r, n, url2, err := kc.Get(hash)
511         defer r.Close()
512         c.Check(err, Equals, nil)
513         c.Check(n, Equals, int64(3))
514         c.Check(url2, Equals, fmt.Sprintf("%s/%s", ks.url, hash))
515
516         content, err2 := ioutil.ReadAll(r)
517         c.Check(err2, Equals, nil)
518         c.Check(content, DeepEquals, []byte("foo"))
519
520         log.Printf("TestGet done")
521 }
522
523 func (s *StandaloneSuite) TestGet404(c *C) {
524         hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
525
526         st := Error404Handler{make(chan string, 1)}
527
528         ks := RunFakeKeepServer(st)
529         defer ks.listener.Close()
530
531         arv, err := arvadosclient.MakeArvadosClient()
532         kc, _ := MakeKeepClient(&arv)
533         arv.ApiToken = "abc123"
534         kc.SetServiceRoots(map[string]string{"x": ks.url}, map[string]string{ks.url: ""}, nil)
535
536         r, n, url2, err := kc.Get(hash)
537         c.Check(err, Equals, BlockNotFound)
538         c.Check(n, Equals, int64(0))
539         c.Check(url2, Equals, "")
540         c.Check(r, Equals, nil)
541 }
542
543 func (s *StandaloneSuite) TestGetFail(c *C) {
544         hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
545
546         st := FailHandler{make(chan string, 1)}
547
548         ks := RunFakeKeepServer(st)
549         defer ks.listener.Close()
550
551         arv, err := arvadosclient.MakeArvadosClient()
552         kc, _ := MakeKeepClient(&arv)
553         arv.ApiToken = "abc123"
554         kc.SetServiceRoots(map[string]string{"x": ks.url}, map[string]string{ks.url: ""}, nil)
555
556         r, n, url2, err := kc.Get(hash)
557         c.Check(err, Equals, KeepServerError)
558         c.Check(n, Equals, int64(0))
559         c.Check(url2, Equals, "")
560         c.Check(r, Equals, nil)
561 }
562
563 func (s *StandaloneSuite) TestGetFailRetry(c *C) {
564         hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
565
566         st := &FailThenSucceedHandler{make(chan string, 1), 0,
567                 StubGetHandler{
568                         c,
569                         hash,
570                         "abc123",
571                         http.StatusOK,
572                         []byte("foo")}}
573
574         ks := RunFakeKeepServer(st)
575         defer ks.listener.Close()
576
577         arv, err := arvadosclient.MakeArvadosClient()
578         kc, _ := MakeKeepClient(&arv)
579         arv.ApiToken = "abc123"
580         kc.SetServiceRoots(map[string]string{"x": ks.url}, map[string]string{ks.url: ""}, nil)
581
582         r, n, url2, err := kc.Get(hash)
583         defer r.Close()
584         c.Check(err, Equals, nil)
585         c.Check(n, Equals, int64(3))
586         c.Check(url2, Equals, fmt.Sprintf("%s/%s", ks.url, hash))
587
588         content, err2 := ioutil.ReadAll(r)
589         c.Check(err2, Equals, nil)
590         c.Check(content, DeepEquals, []byte("foo"))
591 }
592
593 func (s *StandaloneSuite) TestGetNetError(c *C) {
594         hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
595
596         arv, err := arvadosclient.MakeArvadosClient()
597         kc, _ := MakeKeepClient(&arv)
598         arv.ApiToken = "abc123"
599         kc.SetServiceRoots(map[string]string{"x": "http://localhost:62222"}, map[string]string{"http://localhost:62222": ""}, nil)
600
601         r, n, url2, err := kc.Get(hash)
602         c.Check(err, Equals, KeepServerError)
603         c.Check(n, Equals, int64(0))
604         c.Check(url2, Equals, "")
605         c.Check(r, Equals, nil)
606 }
607
608 func (s *StandaloneSuite) TestGetWithServiceHint(c *C) {
609         uuid := "zzzzz-bi6l4-123451234512345"
610         hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
611
612         // This one shouldn't be used:
613         ks0 := RunFakeKeepServer(StubGetHandler{
614                 c,
615                 "error if used",
616                 "abc123",
617                 http.StatusOK,
618                 []byte("foo")})
619         defer ks0.listener.Close()
620         // This one should be used:
621         ks := RunFakeKeepServer(StubGetHandler{
622                 c,
623                 hash + "+K@" + uuid,
624                 "abc123",
625                 http.StatusOK,
626                 []byte("foo")})
627         defer ks.listener.Close()
628
629         arv, err := arvadosclient.MakeArvadosClient()
630         kc, _ := MakeKeepClient(&arv)
631         arv.ApiToken = "abc123"
632         kc.SetServiceRoots(
633                 map[string]string{"x": ks0.url},
634                 map[string]string{"x": ks0.url},
635                 map[string]string{uuid: ks.url})
636
637         r, n, uri, err := kc.Get(hash + "+K@" + uuid)
638         defer r.Close()
639         c.Check(err, Equals, nil)
640         c.Check(n, Equals, int64(3))
641         c.Check(uri, Equals, fmt.Sprintf("%s/%s", ks.url, hash+"+K@"+uuid))
642
643         content, err := ioutil.ReadAll(r)
644         c.Check(err, Equals, nil)
645         c.Check(content, DeepEquals, []byte("foo"))
646 }
647
648 // Use a service hint to fetch from a local disk service, overriding
649 // rendezvous probe order.
650 func (s *StandaloneSuite) TestGetWithLocalServiceHint(c *C) {
651         uuid := "zzzzz-bi6l4-zzzzzzzzzzzzzzz"
652         hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
653
654         // This one shouldn't be used, although it appears first in
655         // rendezvous probe order:
656         ks0 := RunFakeKeepServer(StubGetHandler{
657                 c,
658                 "error if used",
659                 "abc123",
660                 http.StatusOK,
661                 []byte("foo")})
662         defer ks0.listener.Close()
663         // This one should be used:
664         ks := RunFakeKeepServer(StubGetHandler{
665                 c,
666                 hash + "+K@" + uuid,
667                 "abc123",
668                 http.StatusOK,
669                 []byte("foo")})
670         defer ks.listener.Close()
671
672         arv, err := arvadosclient.MakeArvadosClient()
673         kc, _ := MakeKeepClient(&arv)
674         arv.ApiToken = "abc123"
675         kc.SetServiceRoots(
676                 map[string]string{
677                         "zzzzz-bi6l4-yyyyyyyyyyyyyyy": ks0.url,
678                         "zzzzz-bi6l4-xxxxxxxxxxxxxxx": ks0.url,
679                         "zzzzz-bi6l4-wwwwwwwwwwwwwww": ks0.url,
680                         uuid: ks.url},
681                 map[string]string{
682                         "zzzzz-bi6l4-yyyyyyyyyyyyyyy": ks0.url,
683                         "zzzzz-bi6l4-xxxxxxxxxxxxxxx": ks0.url,
684                         "zzzzz-bi6l4-wwwwwwwwwwwwwww": ks0.url,
685                         uuid: ks.url},
686                 map[string]string{
687                         "zzzzz-bi6l4-yyyyyyyyyyyyyyy": ks0.url,
688                         "zzzzz-bi6l4-xxxxxxxxxxxxxxx": ks0.url,
689                         "zzzzz-bi6l4-wwwwwwwwwwwwwww": ks0.url,
690                         uuid: ks.url},
691         )
692
693         r, n, uri, err := kc.Get(hash + "+K@" + uuid)
694         defer r.Close()
695         c.Check(err, Equals, nil)
696         c.Check(n, Equals, int64(3))
697         c.Check(uri, Equals, fmt.Sprintf("%s/%s", ks.url, hash+"+K@"+uuid))
698
699         content, err := ioutil.ReadAll(r)
700         c.Check(err, Equals, nil)
701         c.Check(content, DeepEquals, []byte("foo"))
702 }
703
704 func (s *StandaloneSuite) TestGetWithServiceHintFailoverToLocals(c *C) {
705         uuid := "zzzzz-bi6l4-123451234512345"
706         hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
707
708         ksLocal := RunFakeKeepServer(StubGetHandler{
709                 c,
710                 hash + "+K@" + uuid,
711                 "abc123",
712                 http.StatusOK,
713                 []byte("foo")})
714         defer ksLocal.listener.Close()
715         ksGateway := RunFakeKeepServer(StubGetHandler{
716                 c,
717                 hash + "+K@" + uuid,
718                 "abc123",
719                 http.StatusInternalServerError,
720                 []byte("Error")})
721         defer ksGateway.listener.Close()
722
723         arv, err := arvadosclient.MakeArvadosClient()
724         kc, _ := MakeKeepClient(&arv)
725         arv.ApiToken = "abc123"
726         kc.SetServiceRoots(
727                 map[string]string{"zzzzz-bi6l4-keepdisk0000000": ksLocal.url},
728                 map[string]string{"zzzzz-bi6l4-keepdisk0000000": ksLocal.url},
729                 map[string]string{uuid: ksGateway.url})
730
731         r, n, uri, err := kc.Get(hash + "+K@" + uuid)
732         c.Assert(err, Equals, nil)
733         defer r.Close()
734         c.Check(n, Equals, int64(3))
735         c.Check(uri, Equals, fmt.Sprintf("%s/%s", ksLocal.url, hash+"+K@"+uuid))
736
737         content, err := ioutil.ReadAll(r)
738         c.Check(err, Equals, nil)
739         c.Check(content, DeepEquals, []byte("foo"))
740 }
741
742 type BarHandler struct {
743         handled chan string
744 }
745
746 func (this BarHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
747         resp.Write([]byte("bar"))
748         this.handled <- fmt.Sprintf("http://%s", req.Host)
749 }
750
751 func (s *StandaloneSuite) TestChecksum(c *C) {
752         foohash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
753         barhash := fmt.Sprintf("%x", md5.Sum([]byte("bar")))
754
755         st := BarHandler{make(chan string, 1)}
756
757         ks := RunFakeKeepServer(st)
758         defer ks.listener.Close()
759
760         arv, err := arvadosclient.MakeArvadosClient()
761         kc, _ := MakeKeepClient(&arv)
762         arv.ApiToken = "abc123"
763         kc.SetServiceRoots(map[string]string{"x": ks.url}, map[string]string{ks.url: ""}, nil)
764
765         r, n, _, err := kc.Get(barhash)
766         _, err = ioutil.ReadAll(r)
767         c.Check(n, Equals, int64(3))
768         c.Check(err, Equals, nil)
769
770         <-st.handled
771
772         r, n, _, err = kc.Get(foohash)
773         _, err = ioutil.ReadAll(r)
774         c.Check(n, Equals, int64(3))
775         c.Check(err, Equals, BadChecksum)
776
777         <-st.handled
778 }
779
780 func (s *StandaloneSuite) TestGetWithFailures(c *C) {
781         content := []byte("waz")
782         hash := fmt.Sprintf("%x", md5.Sum(content))
783
784         fh := Error404Handler{
785                 make(chan string, 4)}
786
787         st := StubGetHandler{
788                 c,
789                 hash,
790                 "abc123",
791                 http.StatusOK,
792                 content}
793
794         arv, err := arvadosclient.MakeArvadosClient()
795         kc, _ := MakeKeepClient(&arv)
796         arv.ApiToken = "abc123"
797         localRoots := make(map[string]string)
798         writableLocalRoots := make(map[string]string)
799
800         ks1 := RunSomeFakeKeepServers(st, 1)
801         ks2 := RunSomeFakeKeepServers(fh, 4)
802
803         for i, k := range ks1 {
804                 localRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", i)] = k.url
805                 writableLocalRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", i)] = k.url
806                 defer k.listener.Close()
807         }
808         for i, k := range ks2 {
809                 localRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", i+len(ks1))] = k.url
810                 writableLocalRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", i+len(ks1))] = k.url
811                 defer k.listener.Close()
812         }
813
814         kc.SetServiceRoots(localRoots, writableLocalRoots, nil)
815
816         // This test works only if one of the failing services is
817         // attempted before the succeeding service. Otherwise,
818         // <-fh.handled below will just hang! (Probe order depends on
819         // the choice of block content "waz" and the UUIDs of the fake
820         // servers, so we just tried different strings until we found
821         // an example that passes this Assert.)
822         c.Assert(NewRootSorter(localRoots, hash).GetSortedRoots()[0], Not(Equals), ks1[0].url)
823
824         r, n, url2, err := kc.Get(hash)
825
826         <-fh.handled
827         c.Check(err, Equals, nil)
828         c.Check(n, Equals, int64(3))
829         c.Check(url2, Equals, fmt.Sprintf("%s/%s", ks1[0].url, hash))
830
831         read_content, err2 := ioutil.ReadAll(r)
832         c.Check(err2, Equals, nil)
833         c.Check(read_content, DeepEquals, content)
834 }
835
836 func (s *ServerRequiredSuite) TestPutGetHead(c *C) {
837         content := []byte("TestPutGetHead")
838
839         arv, err := arvadosclient.MakeArvadosClient()
840         kc, err := MakeKeepClient(&arv)
841         c.Assert(err, Equals, nil)
842
843         hash := fmt.Sprintf("%x", md5.Sum(content))
844
845         {
846                 n, _, err := kc.Ask(hash)
847                 c.Check(err, Equals, BlockNotFound)
848                 c.Check(n, Equals, int64(0))
849         }
850         {
851                 hash2, replicas, err := kc.PutB(content)
852                 c.Check(hash2, Matches, fmt.Sprintf(`%s\+%d\b.*`, hash, len(content)))
853                 c.Check(replicas, Equals, 2)
854                 c.Check(err, Equals, nil)
855         }
856         {
857                 r, n, url2, err := kc.Get(hash)
858                 c.Check(err, Equals, nil)
859                 c.Check(n, Equals, int64(len(content)))
860                 c.Check(url2, Matches, fmt.Sprintf("http://localhost:\\d+/%s", hash))
861
862                 read_content, err2 := ioutil.ReadAll(r)
863                 c.Check(err2, Equals, nil)
864                 c.Check(read_content, DeepEquals, content)
865         }
866         {
867                 n, url2, err := kc.Ask(hash)
868                 c.Check(err, Equals, nil)
869                 c.Check(n, Equals, int64(len(content)))
870                 c.Check(url2, Matches, fmt.Sprintf("http://localhost:\\d+/%s", hash))
871         }
872 }
873
874 type StubProxyHandler struct {
875         handled chan string
876 }
877
878 func (this StubProxyHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
879         resp.Header().Set("X-Keep-Replicas-Stored", "2")
880         this.handled <- fmt.Sprintf("http://%s", req.Host)
881 }
882
883 func (s *StandaloneSuite) TestPutProxy(c *C) {
884         log.Printf("TestPutProxy")
885
886         st := StubProxyHandler{make(chan string, 1)}
887
888         arv, err := arvadosclient.MakeArvadosClient()
889         kc, _ := MakeKeepClient(&arv)
890
891         kc.Want_replicas = 2
892         kc.Using_proxy = true
893         arv.ApiToken = "abc123"
894         localRoots := make(map[string]string)
895         writableLocalRoots := make(map[string]string)
896
897         ks1 := RunSomeFakeKeepServers(st, 1)
898
899         for i, k := range ks1 {
900                 localRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", i)] = k.url
901                 writableLocalRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", i)] = k.url
902                 defer k.listener.Close()
903         }
904
905         kc.SetServiceRoots(localRoots, writableLocalRoots, nil)
906
907         _, replicas, err := kc.PutB([]byte("foo"))
908         <-st.handled
909
910         c.Check(err, Equals, nil)
911         c.Check(replicas, Equals, 2)
912
913         log.Printf("TestPutProxy done")
914 }
915
916 func (s *StandaloneSuite) TestPutProxyInsufficientReplicas(c *C) {
917         log.Printf("TestPutProxy")
918
919         st := StubProxyHandler{make(chan string, 1)}
920
921         arv, err := arvadosclient.MakeArvadosClient()
922         kc, _ := MakeKeepClient(&arv)
923
924         kc.Want_replicas = 3
925         kc.Using_proxy = true
926         arv.ApiToken = "abc123"
927         localRoots := make(map[string]string)
928         writableLocalRoots := make(map[string]string)
929
930         ks1 := RunSomeFakeKeepServers(st, 1)
931
932         for i, k := range ks1 {
933                 localRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", i)] = k.url
934                 writableLocalRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", i)] = k.url
935                 defer k.listener.Close()
936         }
937         kc.SetServiceRoots(localRoots, writableLocalRoots, nil)
938
939         _, replicas, err := kc.PutB([]byte("foo"))
940         <-st.handled
941
942         c.Check(err, Equals, InsufficientReplicasError)
943         c.Check(replicas, Equals, 2)
944
945         log.Printf("TestPutProxy done")
946 }
947
948 func (s *StandaloneSuite) TestMakeLocator(c *C) {
949         l, err := MakeLocator("91f372a266fe2bf2823cb8ec7fda31ce+3+Aabcde@12345678")
950         c.Check(err, Equals, nil)
951         c.Check(l.Hash, Equals, "91f372a266fe2bf2823cb8ec7fda31ce")
952         c.Check(l.Size, Equals, 3)
953         c.Check(l.Hints, DeepEquals, []string{"3", "Aabcde@12345678"})
954 }
955
956 func (s *StandaloneSuite) TestMakeLocatorNoHints(c *C) {
957         l, err := MakeLocator("91f372a266fe2bf2823cb8ec7fda31ce")
958         c.Check(err, Equals, nil)
959         c.Check(l.Hash, Equals, "91f372a266fe2bf2823cb8ec7fda31ce")
960         c.Check(l.Size, Equals, -1)
961         c.Check(l.Hints, DeepEquals, []string{})
962 }
963
964 func (s *StandaloneSuite) TestMakeLocatorNoSizeHint(c *C) {
965         l, err := MakeLocator("91f372a266fe2bf2823cb8ec7fda31ce+Aabcde@12345678")
966         c.Check(err, Equals, nil)
967         c.Check(l.Hash, Equals, "91f372a266fe2bf2823cb8ec7fda31ce")
968         c.Check(l.Size, Equals, -1)
969         c.Check(l.Hints, DeepEquals, []string{"Aabcde@12345678"})
970 }
971
972 func (s *StandaloneSuite) TestMakeLocatorPreservesUnrecognizedHints(c *C) {
973         str := "91f372a266fe2bf2823cb8ec7fda31ce+3+Unknown+Kzzzzz+Afoobar"
974         l, err := MakeLocator(str)
975         c.Check(err, Equals, nil)
976         c.Check(l.Hash, Equals, "91f372a266fe2bf2823cb8ec7fda31ce")
977         c.Check(l.Size, Equals, 3)
978         c.Check(l.Hints, DeepEquals, []string{"3", "Unknown", "Kzzzzz", "Afoobar"})
979         c.Check(l.String(), Equals, str)
980 }
981
982 func (s *StandaloneSuite) TestMakeLocatorInvalidInput(c *C) {
983         _, err := MakeLocator("91f372a266fe2bf2823cb8ec7fda31c")
984         c.Check(err, Equals, InvalidLocatorError)
985 }
986
987 func (s *StandaloneSuite) TestPutBWant2ReplicasWithOnlyOneWritableLocalRoot(c *C) {
988         hash := Md5String("foo")
989
990         st := StubPutHandler{
991                 c,
992                 hash,
993                 "abc123",
994                 "foo",
995                 make(chan string, 5)}
996
997         arv, _ := arvadosclient.MakeArvadosClient()
998         kc, _ := MakeKeepClient(&arv)
999
1000         kc.Want_replicas = 2
1001         arv.ApiToken = "abc123"
1002         localRoots := make(map[string]string)
1003         writableLocalRoots := make(map[string]string)
1004
1005         ks := RunSomeFakeKeepServers(st, 5)
1006
1007         for i, k := range ks {
1008                 localRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", i)] = k.url
1009                 if i == 0 {
1010                         writableLocalRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", i)] = k.url
1011                 }
1012                 defer k.listener.Close()
1013         }
1014
1015         kc.SetServiceRoots(localRoots, writableLocalRoots, nil)
1016
1017         _, replicas, err := kc.PutB([]byte("foo"))
1018
1019         c.Check(err, Equals, InsufficientReplicasError)
1020         c.Check(replicas, Equals, 1)
1021
1022         c.Check(<-st.handled, Equals, localRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", 0)])
1023 }
1024
1025 func (s *StandaloneSuite) TestPutBWithNoWritableLocalRoots(c *C) {
1026         hash := Md5String("foo")
1027
1028         st := StubPutHandler{
1029                 c,
1030                 hash,
1031                 "abc123",
1032                 "foo",
1033                 make(chan string, 5)}
1034
1035         arv, _ := arvadosclient.MakeArvadosClient()
1036         kc, _ := MakeKeepClient(&arv)
1037
1038         kc.Want_replicas = 2
1039         arv.ApiToken = "abc123"
1040         localRoots := make(map[string]string)
1041         writableLocalRoots := make(map[string]string)
1042
1043         ks := RunSomeFakeKeepServers(st, 5)
1044
1045         for i, k := range ks {
1046                 localRoots[fmt.Sprintf("zzzzz-bi6l4-fakefakefake%03d", i)] = k.url
1047                 defer k.listener.Close()
1048         }
1049
1050         kc.SetServiceRoots(localRoots, writableLocalRoots, nil)
1051
1052         _, replicas, err := kc.PutB([]byte("foo"))
1053
1054         c.Check(err, Equals, InsufficientReplicasError)
1055         c.Check(replicas, Equals, 0)
1056 }
1057
1058 type StubGetIndexHandler struct {
1059         c              *C
1060         expectPath     string
1061         expectAPIToken string
1062         httpStatus     int
1063         body           []byte
1064 }
1065
1066 func (h StubGetIndexHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
1067         h.c.Check(req.URL.Path, Equals, h.expectPath)
1068         h.c.Check(req.Header.Get("Authorization"), Equals, fmt.Sprintf("OAuth2 %s", h.expectAPIToken))
1069         resp.WriteHeader(h.httpStatus)
1070         resp.Header().Set("Content-Length", fmt.Sprintf("%d", len(h.body)))
1071         resp.Write(h.body)
1072 }
1073
1074 func (s *StandaloneSuite) TestGetIndexWithNoPrefix(c *C) {
1075         hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
1076
1077         st := StubGetIndexHandler{
1078                 c,
1079                 "/index",
1080                 "abc123",
1081                 http.StatusOK,
1082                 []byte(hash + "+3 1443559274\n\n")}
1083
1084         ks := RunFakeKeepServer(st)
1085         defer ks.listener.Close()
1086
1087         arv, err := arvadosclient.MakeArvadosClient()
1088         kc, _ := MakeKeepClient(&arv)
1089         arv.ApiToken = "abc123"
1090         kc.SetServiceRoots(map[string]string{"x": ks.url}, map[string]string{ks.url: ""}, nil)
1091
1092         r, err := kc.GetIndex("x", "")
1093         c.Check(err, Equals, nil)
1094
1095         content, err2 := ioutil.ReadAll(r)
1096         c.Check(err2, Equals, nil)
1097         c.Check(content, DeepEquals, st.body[0:len(st.body)-1])
1098 }
1099
1100 func (s *StandaloneSuite) TestGetIndexWithPrefix(c *C) {
1101         hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
1102
1103         st := StubGetIndexHandler{
1104                 c,
1105                 "/index/" + hash[0:3],
1106                 "abc123",
1107                 http.StatusOK,
1108                 []byte(hash + "+3 1443559274\n\n")}
1109
1110         ks := RunFakeKeepServer(st)
1111         defer ks.listener.Close()
1112
1113         arv, err := arvadosclient.MakeArvadosClient()
1114         kc, _ := MakeKeepClient(&arv)
1115         arv.ApiToken = "abc123"
1116         kc.SetServiceRoots(map[string]string{"x": ks.url}, map[string]string{ks.url: ""}, nil)
1117
1118         r, err := kc.GetIndex("x", hash[0:3])
1119         c.Check(err, Equals, nil)
1120
1121         content, err2 := ioutil.ReadAll(r)
1122         c.Check(err2, Equals, nil)
1123         c.Check(content, DeepEquals, st.body[0:len(st.body)-1])
1124 }
1125
1126 func (s *StandaloneSuite) TestGetIndexIncomplete(c *C) {
1127         hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
1128
1129         st := StubGetIndexHandler{
1130                 c,
1131                 "/index/" + hash[0:3],
1132                 "abc123",
1133                 http.StatusOK,
1134                 []byte(hash)}
1135
1136         ks := RunFakeKeepServer(st)
1137         defer ks.listener.Close()
1138
1139         arv, err := arvadosclient.MakeArvadosClient()
1140         kc, _ := MakeKeepClient(&arv)
1141         arv.ApiToken = "abc123"
1142         kc.SetServiceRoots(map[string]string{"x": ks.url}, map[string]string{ks.url: ""}, nil)
1143
1144         _, err = kc.GetIndex("x", hash[0:3])
1145         c.Check(err, Equals, ErrIncompleteIndex)
1146 }
1147
1148 func (s *StandaloneSuite) TestGetIndexWithNoSuchServer(c *C) {
1149         hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
1150
1151         st := StubGetIndexHandler{
1152                 c,
1153                 "/index/" + hash[0:3],
1154                 "abc123",
1155                 http.StatusOK,
1156                 []byte(hash)}
1157
1158         ks := RunFakeKeepServer(st)
1159         defer ks.listener.Close()
1160
1161         arv, err := arvadosclient.MakeArvadosClient()
1162         kc, _ := MakeKeepClient(&arv)
1163         arv.ApiToken = "abc123"
1164         kc.SetServiceRoots(map[string]string{"x": ks.url}, map[string]string{ks.url: ""}, nil)
1165
1166         _, err = kc.GetIndex("y", hash[0:3])
1167         c.Check(err, Equals, ErrNoSuchKeepServer)
1168 }
1169
1170 func (s *StandaloneSuite) TestGetIndexWithNoSuchPrefix(c *C) {
1171         st := StubGetIndexHandler{
1172                 c,
1173                 "/index/abcd",
1174                 "abc123",
1175                 http.StatusOK,
1176                 []byte("\n")}
1177
1178         ks := RunFakeKeepServer(st)
1179         defer ks.listener.Close()
1180
1181         arv, err := arvadosclient.MakeArvadosClient()
1182         kc, _ := MakeKeepClient(&arv)
1183         arv.ApiToken = "abc123"
1184         kc.SetServiceRoots(map[string]string{"x": ks.url}, map[string]string{ks.url: ""}, nil)
1185
1186         r, err := kc.GetIndex("x", "abcd")
1187         c.Check(err, Equals, nil)
1188
1189         content, err2 := ioutil.ReadAll(r)
1190         c.Check(err2, Equals, nil)
1191         c.Check(content, DeepEquals, st.body[0:len(st.body)-1])
1192 }