-
Notifications
You must be signed in to change notification settings - Fork 213
/
rpc_test.go
1816 lines (1661 loc) · 52.2 KB
/
rpc_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2016 The GoHBase Authors. All rights reserved.
// This file is part of GoHBase.
// Use of this source code is governed by the Apache License 2.0
// that can be found in the COPYING file.
package gohbase
import (
"bytes"
"context"
"errors"
"fmt"
"log/slog"
"math/rand"
"net"
"reflect"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/tsuna/gohbase/compression"
"github.com/tsuna/gohbase/hrpc"
"github.com/tsuna/gohbase/pb"
"github.com/tsuna/gohbase/region"
"github.com/tsuna/gohbase/test"
"github.com/tsuna/gohbase/test/mock"
mockRegion "github.com/tsuna/gohbase/test/mock/region"
mockZk "github.com/tsuna/gohbase/test/mock/zk"
"github.com/tsuna/gohbase/zk"
"go.uber.org/mock/gomock"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/wrapperspb"
"modernc.org/b/v2"
)
func newRegionClientFn(addr string) func() hrpc.RegionClient {
return func() hrpc.RegionClient {
return newMockRegionClient(addr, region.RegionClient,
0, 0, "root", region.DefaultReadTimeout, nil, nil, slog.Default())
}
}
func newMockClient(zkClient zk.Client) *client {
return &client{
clientType: region.RegionClient,
regions: keyRegionCache{
logger: slog.Default(),
regions: b.TreeNew[[]byte, hrpc.RegionInfo](region.Compare),
},
clients: clientRegionCache{
logger: slog.Default(),
regions: make(map[hrpc.RegionClient]map[hrpc.RegionInfo]struct{}),
},
rpcQueueSize: defaultRPCQueueSize,
flushInterval: defaultFlushInterval,
metaRegionInfo: region.NewInfo(0, []byte("hbase"), []byte("meta"),
[]byte("hbase:meta,,1"), nil, nil),
zkTimeout: defaultZkTimeout,
zkClient: zkClient,
regionLookupTimeout: region.DefaultLookupTimeout,
regionReadTimeout: region.DefaultReadTimeout,
newRegionClientFn: newMockRegionClient,
logger: slog.Default(),
}
}
func TestSendRPCSanity(t *testing.T) {
ctrl := test.NewController(t)
defer ctrl.Finish()
// we expect to ask zookeeper for where metaregion is
zkClient := mockZk.NewMockClient(ctrl)
zkClient.EXPECT().LocateResource(zk.Meta).Return("regionserver:1", nil).MinTimes(1)
c := newMockClient(zkClient)
// ask for "theKey" in table "test"
mockCall := mock.NewMockCall(ctrl)
mockCall.EXPECT().Context().Return(context.Background()).AnyTimes()
mockCall.EXPECT().Description().AnyTimes()
mockCall.EXPECT().Table().Return([]byte("test")).AnyTimes()
mockCall.EXPECT().Key().Return([]byte("theKey")).AnyTimes()
mockCall.EXPECT().SetRegion(gomock.Any()).AnyTimes()
result := make(chan hrpc.RPCResult, 1)
// pretend that response is successful
expMsg := &pb.ScanResponse{}
result <- hrpc.RPCResult{Msg: expMsg}
mockCall.EXPECT().ResultChan().Return(result).Times(1)
msg, err := c.SendRPC(mockCall)
if err != nil {
t.Fatal(err)
}
if !proto.Equal(expMsg, msg) {
t.Errorf("expected %v, got %v", expMsg, msg)
}
if len(c.clients.regions) != 2 {
t.Errorf("Expected 2 clients in cache, got %d", len(c.clients.regions))
}
// addr -> region name
expClients := map[string]string{
"regionserver:1": "hbase:meta,,1",
"regionserver:2": "test,,1434573235908.56f833d5569a27c7a43fbf547b4924a4.",
}
// make sure those are the right clients
for c, rs := range c.clients.regions {
name, ok := expClients[c.Addr()]
if !ok {
t.Errorf("Got unexpected client %s in cache", c.Addr())
continue
}
if len(rs) != 1 {
t.Errorf("Expected to have only 1 region in cache for client %s", c.Addr())
continue
}
for r := range rs {
if string(r.Name()) != name {
t.Errorf("Unexpected name of region %q for client %s, expected %q",
r.Name(), c.Addr(), name)
}
// check bidirectional mapping, they have to be the same objects
rc := r.Client()
if c != rc {
t.Errorf("Invalid bidirectional mapping: forward=%s, backward=%s",
c.Addr(), rc.Addr())
}
}
}
if c.regions.regions.Len() != 1 {
// expecting only one region because meta isn't in cache, it's hard-coded
t.Errorf("Expected 1 regions in cache, got %d", c.regions.regions.Len())
}
}
func TestReestablishRegionSplit(t *testing.T) {
ctrl := test.NewController(t)
defer ctrl.Finish()
// we expect to ask zookeeper for where metaregion is
c := newMockClient(mockZk.NewMockClient(ctrl))
// inject a fake regionserver client and fake region into cache
origlReg := region.NewInfo(
0,
nil,
[]byte("test1"),
[]byte("test1,,1434573235908.56f833d5569a27c7a43fbf547b4924a4."),
nil,
nil,
)
// pretend regionserver:1 has meta table
// "test1" is at the moment at regionserver:1
// marking unavailable to simulate error
origlReg.MarkUnavailable()
rc1 := c.clients.put("regionserver:1", origlReg, newRegionClientFn("regionserver:1"))
origlReg.SetClient(rc1)
c.regions.put(origlReg)
rc2 := c.clients.put("regionserver:1", c.metaRegionInfo, newRegionClientFn("regionserver:1"))
if rc1 != rc2 {
t.Fatal("expected to get the same region client")
}
c.metaRegionInfo.SetClient(rc2)
c.reestablishRegion(origlReg)
if len(c.clients.regions) != 1 {
t.Errorf("Expected 1 client in cache, got %d", len(c.clients.regions))
}
expRegs := map[string]struct{}{
"hbase:meta,,1": struct{}{},
"test1,,1480547738107.825c5c7e480c76b73d6d2bad5d3f7bb8.": struct{}{},
}
// make sure those are the right clients
for rc, rs := range c.clients.regions {
if rc.Addr() != "regionserver:1" {
t.Errorf("Got unexpected client %s in cache", rc.Addr())
break
}
// check that we have correct regions in the client
gotRegs := map[string]struct{}{}
for r := range rs {
gotRegs[string(r.Name())] = struct{}{}
// check that regions have correct client
if r.Client() != rc1 {
t.Errorf("Invalid bidirectional mapping: forward=%s, backward=%s",
r.Client().Addr(), rc1.Addr())
}
}
if !reflect.DeepEqual(expRegs, gotRegs) {
t.Errorf("expected %v, got %v", expRegs, gotRegs)
}
// check that we still have the same client that we injected
if rc != rc1 {
t.Errorf("Invalid bidirectional mapping: forward=%s, backward=%s",
rc.Addr(), rc1.Addr())
}
}
if c.regions.regions.Len() != 1 {
// expecting only one region because meta isn't in cache, it's hard-coded
t.Errorf("Expected 1 regions in cache, got %d", c.regions.regions.Len())
}
// check the we have correct region in regions cache
newRegIntf, ok := c.regions.regions.Get(
[]byte("test1,,1480547738107.825c5c7e480c76b73d6d2bad5d3f7bb8."))
if !ok {
t.Error("Expected region is not in the cache")
}
// check new region is available
newReg, ok := newRegIntf.(hrpc.RegionInfo)
if !ok {
t.Error("Expected hrpc.RegionInfo")
}
if newReg.IsUnavailable() {
t.Error("Expected new region to be available")
}
// check old region is available and it's client is empty since we
// need to release all the waiting callers
if origlReg.IsUnavailable() {
t.Error("Expected original region to be available")
}
if origlReg.Client() != nil {
t.Error("Expected original region to have no client")
}
}
func TestReestablishRegionNSRE(t *testing.T) {
c := newMockClient(nil)
origlReg := region.NewInfo(0, nil, []byte("nsre"),
[]byte("nsre,,1434573235908.56f833d5569a27c7a43fbf547b4924a4."), nil, nil)
// inject a fake regionserver client and fake region into cache
// pretend regionserver:1 has meta table
rc1 := c.clients.put("regionserver:1", c.metaRegionInfo, newRegionClientFn("regionserver:1"))
rc2 := c.clients.put("regionserver:1", origlReg, newRegionClientFn("regionserver:1"))
if rc1 != rc2 {
t.Fatal("expected region client to be the same")
}
// "nsre" is at the moment at regionserver:1
c.metaRegionInfo.SetClient(rc1)
origlReg.SetClient(rc1)
// marking unavailable to simulate error
origlReg.MarkUnavailable()
c.regions.put(origlReg)
c.reestablishRegion(origlReg)
if len(c.clients.regions) != 1 {
t.Errorf("Expected 1 client in cache, got %d", len(c.clients.regions))
}
if c.regions.regions.Len() != 1 {
// expecting only one region because meta isn't in cache, it's hard-coded
t.Errorf("Expected 1 regions in cache, got %d", c.regions.regions.Len())
}
// check the we have the region in regions cache
_, ok := c.regions.regions.Get(
[]byte("nsre,,1434573235908.56f833d5569a27c7a43fbf547b4924a4."))
if !ok {
t.Error("Expected region is not in the cache")
}
// check region is available and it's client is empty since we
// need to release all the waiting callers
if origlReg.IsUnavailable() {
t.Error("Expected original region to be available")
}
if origlReg.Client() != rc1 {
t.Error("Expected original region the same client")
}
}
func TestEstablishRegionDialFail(t *testing.T) {
ctrl := test.NewController(t)
defer ctrl.Finish()
c := newMockClient(nil)
rcFailDial := mockRegion.NewMockRegionClient(ctrl)
// return an error to make sure we lookup an new client
rcFailDial.EXPECT().Dial(gomock.Any()).Return(errors.New("ooops")).AnyTimes()
rcFailDial.EXPECT().Addr().Return("regionserver:1").AnyTimes()
rcFailDial.EXPECT().String().Return("regionserver:1").AnyTimes()
// second client returns that region has been dead
// this is a success case to make sure we ever obtain a new client and not
// just stuck looking up in cache
rcDialCancel := mockRegion.NewMockRegionClient(ctrl)
rcDialCancel.EXPECT().Dial(gomock.Any()).Return(context.Canceled)
rcDialCancel.EXPECT().Addr().Return("regionserver:1").AnyTimes()
rcDialCancel.EXPECT().String().Return("reginserver:1").AnyTimes()
newRegionClientFnCallCount := 0
c.newRegionClientFn = func(_ string, _ region.ClientType, _ int, _ time.Duration,
_ string, _ time.Duration, _ compression.Codec,
_ func(ctx context.Context, network, addr string) (net.Conn, error),
_ *slog.Logger) hrpc.RegionClient {
var rc hrpc.RegionClient
if newRegionClientFnCallCount == 0 {
rc = rcFailDial
} else {
// if there was a bug with cache updates, we would never get into this case
rc = rcDialCancel
}
newRegionClientFnCallCount++
return rc
}
reg := region.NewInfo(
0, nil, []byte("test1"), []byte("test1,,1434573235908.56f833d5569a27c7a43fbf547b4924a4."),
nil, nil)
reg.MarkUnavailable()
// inject a fake regionserver client and fake region into cache
// pretend regionserver:0 has meta table
rc1 := c.clients.put("regionserver:0", c.metaRegionInfo, newRegionClientFn("regionserver:0"))
c.metaRegionInfo.SetClient(rc1)
// should get stuck if the region is never established
c.establishRegion(reg, "regionserver:1")
if len(c.clients.regions) != 2 {
t.Errorf("Expected 2 clients in cache, got %d", len(c.clients.regions))
}
if reg.IsUnavailable() {
t.Error("Expected region to be available")
}
}
func TestEstablishClientConcurrent(t *testing.T) {
// test that the same client isn't added when establishing it concurrently
// if there's a race, this test will only fail sometimes
ctrl := test.NewController(t)
defer ctrl.Finish()
// we expect to ask zookeeper for where metaregion is
c := newMockClient(mockZk.NewMockClient(ctrl))
// pre-create fake regions to establish
numRegions := 1000
regions := make([]hrpc.RegionInfo, numRegions)
for i := range regions {
r := region.NewInfo(
0,
nil,
[]byte("test"),
[]byte(fmt.Sprintf("test,%d,1434573235908.yoloyoloyoloyoloyoloyoloyoloyolo.", i)),
nil, nil)
r.MarkUnavailable()
regions[i] = r
}
// all of the regions have the same region client
var wg sync.WaitGroup
for _, r := range regions {
r := r
wg.Add(1)
go func() {
c.establishRegion(r, "regionserver:1")
wg.Done()
}()
}
wg.Wait()
if len(c.clients.regions) != 1 {
t.Fatalf("Expected to have only 1 client in cache, got %d", len(c.clients.regions))
}
for rc, rs := range c.clients.regions {
if len(rs) != numRegions {
t.Errorf("Expected to have %d regions, got %d", numRegions, len(rs))
}
// check that all regions have the same client set and are available
for _, r := range regions {
if r.Client() != rc {
t.Errorf("Region %q has unexpected client %s", r.Name(), rc.Addr())
}
if r.IsUnavailable() {
t.Errorf("Expected region %s to be available", r.Name())
}
}
}
}
func TestEstablishServerErrorDuringProbe(t *testing.T) {
ctrl := test.NewController(t)
defer ctrl.Finish()
c := newMockClient(nil)
// pretend regionserver:0 has meta table
rc := c.clients.put("regionserver:0", c.metaRegionInfo, newRegionClientFn("regionserver:0"))
c.metaRegionInfo.SetClient(rc)
mockCall := mock.NewMockCall(ctrl)
mockCall.EXPECT().Context().Return(context.Background()).AnyTimes()
mockCall.EXPECT().Description().AnyTimes()
mockCall.EXPECT().Table().Return([]byte("down")).AnyTimes()
mockCall.EXPECT().Key().Return([]byte("yolo")).AnyTimes()
mockCall.EXPECT().SetRegion(gomock.Any()).AnyTimes()
result := make(chan hrpc.RPCResult, 1)
// pretend that response is successful
expMsg := &pb.GetResponse{}
result <- hrpc.RPCResult{Msg: expMsg}
mockCall.EXPECT().ResultChan().Return(result).Times(1)
msg, err := c.SendRPC(mockCall)
if err != nil {
t.Errorf("Unexpected error: %s", err)
}
if !proto.Equal(expMsg, msg) {
t.Errorf("expected %v, got %v", expMsg, msg)
}
if len(c.clients.regions) != 2 {
t.Errorf("expected to have 2 clients in cache, got %d", len(c.clients.regions))
}
}
// TestSendRPCToRegionClientDownDelayed check that the we don't replace a newly
// looked up client (by other goroutine) in clients cache if we are too slow
// at finding out that our old client died.
func TestSendRPCToRegionClientDownDelayed(t *testing.T) {
ctrl := test.NewController(t)
defer ctrl.Finish()
zkClient := mockZk.NewMockClient(ctrl)
zkClient.EXPECT().LocateResource(zk.Meta).Return("regionserver:1", nil).AnyTimes()
c := newMockClient(zkClient)
// create region with mock client
origlReg := region.NewInfo(
0, nil, []byte("test1"),
[]byte("test1,,1234567890042.56f833d5569a27c7a43fbf547b4924a4."),
nil, nil)
c.regions.put(origlReg)
rc := mockRegion.NewMockRegionClient(ctrl)
rc.EXPECT().String().Return("mock region client").AnyTimes()
c.clients.put("regionserver:1", origlReg, func() hrpc.RegionClient {
return rc
})
origlReg.SetClient(rc)
mockCall := mock.NewMockCall(ctrl)
mockCall.EXPECT().Region().Return(origlReg).Times(1)
result := make(chan hrpc.RPCResult, 1)
mockCall.EXPECT().ResultChan().Return(result).Times(1)
rc2 := newRegionClientFn("regionserver:1")()
rc.EXPECT().QueueRPC(mockCall).Times(1).Do(func(rpc hrpc.Call) {
// remove old client from clients cache
c.clients.clientDown(rc)
// replace client in region with new client
// this simulate other rpc toggling client reestablishment
c.regions.put(origlReg)
c.clients.put("regionserver:1", origlReg, func() hrpc.RegionClient { return rc2 })
origlReg.SetClient(rc2)
// return ServerError from QueueRPC, to emulate dead client
result <- hrpc.RPCResult{Error: region.ServerError{}}
})
_, err := c.sendRPCToRegionClient(context.Background(), mockCall, rc)
switch err.(type) {
case region.ServerError, region.NotServingRegionError:
default:
t.Errorf("Got unexpected error: %v", err)
}
// Wait for establishRegion to complete
ch := origlReg.AvailabilityChan()
if ch != nil {
<-ch
}
// check that we did not down new client
if len(c.clients.regions) != 1 {
t.Errorf("There are %d cached clients:", len(c.clients.regions))
for rc := range c.clients.regions {
t.Errorf("%s", rc.String())
}
}
_, ok := c.clients.regions[rc2]
if !ok {
t.Error("rc2 is not in clients cache")
}
}
func TestReestablishDeadRegion(t *testing.T) {
ctrl := test.NewController(t)
defer ctrl.Finish()
// setting zookeeper client to nil because we don't
// expect for it to be called
c := newMockClient(nil)
// here we assume that this region was removed from
// regions cache and thereby is considered dead
reg := region.NewInfo(
0,
nil,
[]byte("test"),
[]byte("test,,1434573235908.yoloyoloyoloyoloyoloyoloyoloyolo."),
nil, nil)
reg.MarkDead()
rc1 := c.clients.put("regionserver:0", c.metaRegionInfo, newRegionClientFn("regionserver:0"))
c.clients.put("regionserver:0", reg, newRegionClientFn("regionserver:0"))
// pretend regionserver:0 has meta table
c.metaRegionInfo.SetClient(rc1)
reg.MarkUnavailable()
// pretend that there's a race condition right after we removed region
// from regions cache a client dies that we haven't removed from
// clients cache yet
c.reestablishRegion(reg) // should exit TODO: check fast
// should not put anything in cache, we specifically get a region with new name
if c.regions.regions.Len() != 0 {
t.Errorf("Expected to have no region in cache, got %d", c.regions.regions.Len())
}
// should not establish any clients
if len(c.clients.regions) != 1 {
t.Errorf("Expected to have 1 client in cache, got %d", len(c.clients.regions))
}
if reg.Client() != nil {
t.Error("Expected to have no client established")
}
// should have reg as available
if reg.IsUnavailable() {
t.Error("Expected region to be available")
}
}
func TestFindRegion(t *testing.T) {
// TODO: check regions are deleted from client's cache
// when regions are replaced
tcases := []struct {
before []hrpc.RegionInfo
after []string
establish bool
regName string
err error
}{
{ // nothing in cache
before: nil,
after: []string{"test,,1434573235908.56f833d5569a27c7a43fbf547b4924a4."},
establish: true,
regName: "test,,1434573235908.56f833d5569a27c7a43fbf547b4924a4.",
},
{ // older region in cache
before: []hrpc.RegionInfo{
region.NewInfo(1, nil, []byte("test"),
[]byte("test,,1.yoloyoloyoloyoloyoloyoloyoloyolo."), nil, nil),
},
after: []string{"test,,1434573235908.56f833d5569a27c7a43fbf547b4924a4."},
establish: true,
regName: "test,,1434573235908.56f833d5569a27c7a43fbf547b4924a4.",
},
{ // younger region in cache
before: []hrpc.RegionInfo{
region.NewInfo(9999999999999, nil, []byte("test"),
[]byte("test,,9999999999999.yoloyoloyoloyoloyoloyoloyoloyolo."), nil, nil),
},
after: []string{"test,,9999999999999.yoloyoloyoloyoloyoloyoloyoloyolo."},
establish: false,
},
{ // overlapping younger region in cache, passed key is not in that region
before: []hrpc.RegionInfo{
region.NewInfo(9999999999999, nil, []byte("test"),
[]byte("test,,9999999999999.yoloyoloyoloyoloyoloyoloyoloyolo."),
nil, []byte("foo")),
},
after: []string{"test,,9999999999999.yoloyoloyoloyoloyoloyoloyoloyolo."},
establish: false,
},
}
ctrl := test.NewController(t)
defer ctrl.Finish()
// setting zookeeper client to nil because we don't
// expect for it to be called
c := newMockClient(nil)
// pretend regionserver:0 has meta table
rc := c.clients.put("regionserver:0", c.metaRegionInfo, newRegionClientFn("regionserver:0"))
c.metaRegionInfo.SetClient(rc)
ctx := context.Background()
testTable := []byte("test")
testKey := []byte("yolo")
for i, tcase := range tcases {
t.Run(strconv.Itoa(i), func(t *testing.T) {
c.regions.regions.Clear()
// set up initial cache
for _, region := range tcase.before {
c.regions.put(region)
}
reg, err := c.findRegion(ctx, testTable, testKey)
if err != tcase.err {
t.Fatalf("Expected error %v, got %v", tcase.err, err)
}
if len(tcase.regName) == 0 {
if reg != nil {
t.Errorf("Expected nil region, got %v", reg)
}
} else if string(reg.Name()) != tcase.regName {
t.Errorf("Expected region with name %q, got region %v",
tcase.regName, reg)
}
// check cache
if len(tcase.after) != c.regions.regions.Len() {
t.Errorf("Expected to have %d regions in cache, got %d",
len(tcase.after), c.regions.regions.Len())
}
for _, rn := range tcase.after {
if _, ok := c.regions.regions.Get([]byte(rn)); !ok {
t.Errorf("Expected region %q to be in regions cache", rn)
}
}
// check client was looked up
if tcase.establish {
if ch := reg.AvailabilityChan(); ch != nil {
// if still establishing, wait
<-ch
}
rc2 := reg.Client()
if rc2 == nil {
t.Errorf("Expected region %q to establish a client", reg.Name())
return
}
if rc2.Addr() != "regionserver:2" {
t.Errorf("Expected regionserver:2, got %q", rc2.Addr())
}
}
})
}
}
func TestErrCannotFindRegion(t *testing.T) {
c := newMockClient(nil)
// pretend regionserver:0 has meta table
rc := c.clients.put("regionserver:0", c.metaRegionInfo, newRegionClientFn("regionserver:0"))
c.metaRegionInfo.SetClient(rc)
// add young and small region to cache
origlReg := region.NewInfo(1434573235910, nil, []byte("test"),
[]byte("test,yolo,1434573235910.56f833d5569a27c7a43fbf547b4924a4."), []byte("yolo"), nil)
c.regions.put(origlReg)
rc = c.clients.put("regionserver:0", origlReg, newRegionClientFn("regionserver:0"))
origlReg.SetClient(rc)
// request a key not in the "yolo" region.
get, err := hrpc.NewGetStr(context.Background(), "test", "meow")
if err != nil {
t.Fatal(err)
}
// it should lookup a new older region (1434573235908) that overlaps with the one in cache.
// However, it shouldn't be put into cache, as it's older, resulting in a new lookup,
// evetually leading to ErrCannotFindRegion.
_, err = c.Get(get)
if err != ErrCannotFindRegion {
t.Errorf("Expected error %v, got error %v", ErrCannotFindRegion, err)
}
}
func TestMetaLookupTableNotFound(t *testing.T) {
c := newMockClient(nil)
// pretend regionserver:0 has meta table
rc := c.clients.put("regionserver:0", c.metaRegionInfo, newRegionClientFn("regionserver:0"))
c.metaRegionInfo.SetClient(rc)
_, _, err := c.metaLookup(context.Background(), []byte("tablenotfound"), []byte(t.Name()))
if err != TableNotFound {
t.Errorf("Expected error %v, got error %v", TableNotFound, err)
}
}
func TestMetaLookupCanceledContext(t *testing.T) {
c := newMockClient(nil)
// pretend regionserver:0 has meta table
rc := c.clients.put("regionserver:0", c.metaRegionInfo, newRegionClientFn("regionserver:0"))
c.metaRegionInfo.SetClient(rc)
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, _, err := c.metaLookup(ctx, []byte("tablenotfound"), []byte(t.Name()))
if err != context.Canceled {
t.Errorf("Expected error %v, got error %v", context.Canceled, err)
}
}
func TestMetaLookupAllRegionsCanceledContext(t *testing.T) {
c := newMockClient(nil)
// pretend regionserver:0 has meta table
rc := c.clients.put("regionserver:0", c.metaRegionInfo, newRegionClientFn("regionserver:0"))
c.metaRegionInfo.SetClient(rc)
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := c.metaLookupForTable(ctx, []byte("tablenotfound"))
if err != context.Canceled {
t.Errorf("Expected error %v, got error %v", context.Canceled, err)
}
}
func TestConcurrentRetryableError(t *testing.T) {
ctrl := test.NewController(t)
defer ctrl.Finish()
zkc := mockZk.NewMockClient(ctrl)
// keep failing on zookeeper lookup
zkc.EXPECT().LocateResource(gomock.Any()).Return("", errors.New("ooops")).AnyTimes()
c := newMockClient(zkc)
// create region with mock clien
origlReg := region.NewInfo(
0,
nil,
[]byte("test1"),
[]byte("test1,,1234567890042.56f833d5569a27c7a43fbf547b4924a4."),
nil,
nil,
)
rc := mockRegion.NewMockRegionClient(ctrl)
rc.EXPECT().String().Return("mock region client").AnyTimes()
rc.EXPECT().Addr().Return("host:1234").AnyTimes()
newRC := func() hrpc.RegionClient {
return rc
}
c.clients.put("host:1234", c.metaRegionInfo, newRC)
c.metaRegionInfo.SetClient(rc)
c.regions.put(origlReg)
c.clients.put("host:1234", origlReg, newRC)
origlReg.SetClient(rc)
numCalls := 100
rc.EXPECT().QueueRPC(gomock.Any()).MinTimes(1)
calls := make([]hrpc.Call, numCalls)
for i := range calls {
mockCall := mock.NewMockCall(ctrl)
mockCall.EXPECT().SetRegion(origlReg).AnyTimes()
mockCall.EXPECT().Region().Return(origlReg).AnyTimes()
result := make(chan hrpc.RPCResult, 1)
result <- hrpc.RPCResult{Error: region.NotServingRegionError{}}
mockCall.EXPECT().ResultChan().Return(result).AnyTimes()
calls[i] = mockCall
}
var wg sync.WaitGroup
for _, mockCall := range calls {
wg.Add(1)
go func(mockCall hrpc.Call) {
_, err := c.sendRPCToRegionClient(context.Background(), mockCall, rc)
if _, ok := err.(region.NotServingRegionError); !ok {
t.Errorf("Got unexpected error: %v", err)
}
wg.Done()
}(mockCall)
}
wg.Wait()
origlReg.MarkDead()
if ch := origlReg.AvailabilityChan(); ch != nil {
<-ch
}
}
func TestProbeKey(t *testing.T) {
regions := []hrpc.RegionInfo{
region.NewInfo(0, nil, nil, nil, nil, nil),
region.NewInfo(0, nil, nil, nil, nil, []byte("yolo")),
region.NewInfo(0, nil, nil, nil, []byte("swag"), nil),
region.NewInfo(0, nil, nil, nil, []byte("swag"), []byte("yolo")),
region.NewInfo(0, nil, nil, nil, []byte("aaaaaaaaaaaaaa"), []byte("bbbb")),
region.NewInfo(0, nil, nil, nil, []byte("aaaa"), []byte("bbbbbbb")),
region.NewInfo(0, nil, nil, nil, []byte("aaaa"), []byte("aab")),
region.NewInfo(0, nil, nil, nil, []byte("aaa"), []byte("aaaaaaaaaa")),
region.NewInfo(0, nil, nil, nil, []byte{255}, nil),
region.NewInfo(0, nil, nil, nil, []byte{255, 255}, nil),
}
for _, reg := range regions {
key := probeKey(reg)
isGreaterThanStartOfTable := len(reg.StartKey()) == 0 && len(key) > 0
isGreaterThanStartKey := bytes.Compare(reg.StartKey(), key) < 0
isLessThanEndOfTable := len(reg.StopKey()) == 0 &&
bytes.Compare(key, bytes.Repeat([]byte{255}, len(key))) < 0
isLessThanStopKey := bytes.Compare(key, reg.StopKey()) < 0
if (isGreaterThanStartOfTable || isGreaterThanStartKey) &&
(isLessThanEndOfTable || isLessThanStopKey) {
continue
}
t.Errorf("key %q is not within bounds of region %s: %v %v %v %v\n", key, reg,
isGreaterThanStartOfTable, isGreaterThanStartKey,
isLessThanEndOfTable, isLessThanStopKey)
}
}
var (
description = "GET"
result = "SUCCESS"
o prometheus.Observer
)
func BenchmarkPrometheusWithLabelValues(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
o = operationDurationSeconds.WithLabelValues(
description,
result,
)
}
}
func BenchmarkPrometheusWith(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
o = operationDurationSeconds.With(prometheus.Labels{
"operation": description,
"result": result,
})
}
}
func TestSendBatchBasic(t *testing.T) {
ctrl := test.NewController(t)
defer ctrl.Finish()
// we expect to ask zookeeper for where metaregion is
zkClient := mockZk.NewMockClient(ctrl)
zkClient.EXPECT().LocateResource(zk.Meta).Return("regionserver:1", nil).MinTimes(1)
c := newMockClient(zkClient)
call, err := hrpc.NewPutStr(context.Background(), "test", "theKey", nil)
if err != nil {
t.Fatal(err)
}
// pretend that response is successful
expMsg := &pb.MutateResponse{}
call.ResultChan() <- hrpc.RPCResult{Msg: expMsg}
msg, ok := c.SendBatch(context.Background(), []hrpc.Call{call})
if !ok {
t.Fatal(msg[0].Error)
}
if !proto.Equal(expMsg, msg[0].Msg) {
t.Errorf("expected %v, got %v", expMsg, msg)
}
if len(c.clients.regions) != 2 {
t.Errorf("Expected 2 clients in cache, got %d", len(c.clients.regions))
}
// addr -> region name
expClients := map[string]string{
"regionserver:1": "hbase:meta,,1",
"regionserver:2": "test,,1434573235908.56f833d5569a27c7a43fbf547b4924a4.",
}
// make sure those are the right clients
for c, rs := range c.clients.regions {
name, ok := expClients[c.Addr()]
if !ok {
t.Errorf("Got unexpected client %s in cache", c.Addr())
continue
}
if len(rs) != 1 {
t.Errorf("Expected to have only 1 region in cache for client %s", c.Addr())
continue
}
for r := range rs {
if string(r.Name()) != name {
t.Errorf("Unexpected name of region %q for client %s, expected %q",
r.Name(), c.Addr(), name)
}
// check bidirectional mapping, they have to be the same objects
rc := r.Client()
if c != rc {
t.Errorf("Invalid bidirectional mapping: forward=%s, backward=%s",
c.Addr(), rc.Addr())
}
}
}
if c.regions.regions.Len() != 1 {
// expecting only one region because meta isn't in cache, it's hard-coded
t.Errorf("Expected 1 regions in cache, got %d", c.regions.regions.Len())
}
}
func TestSendBatchBadInput(t *testing.T) {
ctrl := test.NewController(t)
defer ctrl.Finish()
zkc := mockZk.NewMockClient(ctrl)
zkc.EXPECT().LocateResource(zk.Meta).Return("regionserver:1", nil).AnyTimes()
c := newMockClient(zkc)
newRPC := func(table string, batchable bool) hrpc.Call {
if batchable {
rpc, err := hrpc.NewPutStr(context.Background(), table, "key",
map[string]map[string][]byte{"cf": {"foo": []byte("bar")}})
if err != nil {
t.Fatal(err)
}
return rpc
}
rpc, err := hrpc.NewScanStr(context.Background(), table)
if err != nil {
t.Fatal(err)
}
return rpc
}
rpc1 := newRPC("table", true)
rpc2 := newRPC("table", true)
for _, tc := range []struct {
name string
batch []hrpc.Call
expErr []string
}{{
name: "duplicate",
batch: []hrpc.Call{rpc1, rpc1},
expErr: []string{NotExecutedError.Error(), "duplicate call"},
}, {
name: "duplicate2",
batch: []hrpc.Call{rpc1, rpc2, rpc2, newRPC("table", true), rpc1},
expErr: []string{NotExecutedError.Error(), NotExecutedError.Error(),
"duplicate call", NotExecutedError.Error(), "duplicate call"},
}, {
name: "tables",
batch: []hrpc.Call{newRPC("table", true), newRPC("different_table", true)},
expErr: []string{NotExecutedError.Error(), "multiple tables"},
}, {
name: "batchable",
batch: []hrpc.Call{newRPC("table", false)},
expErr: []string{"non-batchable"},
}, {
name: "various errors",
batch: []hrpc.Call{rpc1,
newRPC("table", false),
rpc1,
newRPC("table2", true),
newRPC("table", true)},
expErr: []string{NotExecutedError.Error(),
"non-batchable",
"duplicate call",
"multiple tables",
NotExecutedError.Error()},
}} {
t.Run(tc.name, func(t *testing.T) {
if len(tc.batch) != len(tc.expErr) {
t.Fatalf("test case provides mismatched batch (%d) and expErr (%d) sizes",
len(tc.batch), len(tc.expErr))
}
results, ok := c.SendBatch(context.Background(), tc.batch)
if ok {
t.Errorf("expected !ok from SendBatch, got %t", ok)
}
if len(results) != len(tc.batch) {
t.Fatalf("result size (%d) does not match batch size (%d)",
len(results), len(tc.batch))
}
for i, res := range results {
if res.Error == nil {
t.Errorf("expected error in res[%d], but got nil for request %v",
i, tc.batch[i])
continue
}
if !strings.Contains(res.Error.Error(), tc.expErr[i]) {
t.Errorf("expected error to contain %q, but got %q", tc.expErr[i], res.Error)
}
}
})
}
}
// TestFindClient ensures findClients groups RPCs in a batch by region
// server and preserves the ordering of requests. And that each RPC