forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathregion_cache.go
1445 lines (1316 loc) · 41.2 KB
/
region_cache.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 2016 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package tikv
import (
"bytes"
"context"
"fmt"
"sync"
"sync/atomic"
"time"
"unsafe"
"github.com/gogo/protobuf/proto"
"github.com/google/btree"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/kvproto/pkg/metapb"
pd "github.com/pingcap/pd/v4/client"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/metrics"
"github.com/pingcap/tidb/util/logutil"
atomic2 "go.uber.org/atomic"
"go.uber.org/zap"
)
const (
btreeDegree = 32
invalidatedLastAccessTime = -1
defaultRegionsPerBatch = 128
)
// RegionCacheTTLSec is the max idle time for regions in the region cache.
var RegionCacheTTLSec int64 = 600
var (
tikvRegionCacheCounterWithInvalidateRegionFromCacheOK = metrics.TiKVRegionCacheCounter.WithLabelValues("invalidate_region_from_cache", "ok")
tikvRegionCacheCounterWithSendFail = metrics.TiKVRegionCacheCounter.WithLabelValues("send_fail", "ok")
tikvRegionCacheCounterWithGetRegionByIDOK = metrics.TiKVRegionCacheCounter.WithLabelValues("get_region_by_id", "ok")
tikvRegionCacheCounterWithGetRegionByIDError = metrics.TiKVRegionCacheCounter.WithLabelValues("get_region_by_id", "err")
tikvRegionCacheCounterWithGetRegionOK = metrics.TiKVRegionCacheCounter.WithLabelValues("get_region", "ok")
tikvRegionCacheCounterWithGetRegionError = metrics.TiKVRegionCacheCounter.WithLabelValues("get_region", "err")
tikvRegionCacheCounterWithScanRegionsOK = metrics.TiKVRegionCacheCounter.WithLabelValues("scan_regions", "ok")
tikvRegionCacheCounterWithScanRegionsError = metrics.TiKVRegionCacheCounter.WithLabelValues("scan_regions", "err")
tikvRegionCacheCounterWithGetStoreOK = metrics.TiKVRegionCacheCounter.WithLabelValues("get_store", "ok")
tikvRegionCacheCounterWithGetStoreError = metrics.TiKVRegionCacheCounter.WithLabelValues("get_store", "err")
tikvRegionCacheCounterWithInvalidateStoreRegionsOK = metrics.TiKVRegionCacheCounter.WithLabelValues("invalidate_store_regions", "ok")
)
const (
updated int32 = iota // region is updated and no need to reload.
needSync // need sync new region info.
)
// Region presents kv region
type Region struct {
meta *metapb.Region // raw region meta from PD immutable after init
store unsafe.Pointer // point to region store info, see RegionStore
syncFlag int32 // region need be sync in next turn
lastAccess int64 // last region access time, see checkRegionCacheTTL
}
// RegionStore represents region stores info
// it will be store as unsafe.Pointer and be load at once
type RegionStore struct {
workTiKVIdx int32 // point to current work peer in meta.Peers and work store in stores(same idx) for tikv peer
workTiFlashIdx int32 // point to current work peer in meta.Peers and work store in stores(same idx) for tiflash peer
stores []*Store // stores in this region
storeFails []uint32 // snapshots of store's fail, need reload when `storeFails[curr] != stores[cur].fail`
}
// clone clones region store struct.
func (r *RegionStore) clone() *RegionStore {
storeFails := make([]uint32, len(r.stores))
copy(storeFails, r.storeFails)
return &RegionStore{
workTiFlashIdx: r.workTiFlashIdx,
workTiKVIdx: r.workTiKVIdx,
stores: r.stores,
storeFails: storeFails,
}
}
// return next follower store's index
func (r *RegionStore) follower(seed uint32) int32 {
l := uint32(len(r.stores))
if l <= 1 {
return r.workTiKVIdx
}
for retry := l - 1; retry > 0; retry-- {
followerIdx := int32(seed % (l - 1))
if followerIdx >= r.workTiKVIdx {
followerIdx++
}
if r.stores[followerIdx].storeType != kv.TiKV {
continue
}
if r.storeFails[followerIdx] == atomic.LoadUint32(&r.stores[followerIdx].fail) {
return followerIdx
}
seed++
}
return r.workTiKVIdx
}
// return next leader or follower store's index
func (r *RegionStore) peer(seed uint32) int32 {
candidates := make([]int32, 0, len(r.stores))
for i := 0; i < len(r.stores); i++ {
if r.stores[i].storeType != kv.TiKV {
continue
}
if r.storeFails[i] != atomic.LoadUint32(&r.stores[i].fail) {
continue
}
candidates = append(candidates, int32(i))
}
if len(candidates) == 0 {
return r.workTiKVIdx
}
return candidates[int32(seed)%int32(len(candidates))]
}
// init initializes region after constructed.
func (r *Region) init(c *RegionCache) {
// region store pull used store from global store map
// to avoid acquire storeMu in later access.
rs := &RegionStore{
workTiKVIdx: 0,
workTiFlashIdx: 0,
stores: make([]*Store, 0, len(r.meta.Peers)),
storeFails: make([]uint32, 0, len(r.meta.Peers)),
}
for _, p := range r.meta.Peers {
c.storeMu.RLock()
store, exists := c.storeMu.stores[p.StoreId]
c.storeMu.RUnlock()
if !exists {
store = c.getStoreByStoreID(p.StoreId)
}
rs.stores = append(rs.stores, store)
rs.storeFails = append(rs.storeFails, atomic.LoadUint32(&store.fail))
}
atomic.StorePointer(&r.store, unsafe.Pointer(rs))
// mark region has been init accessed.
r.lastAccess = time.Now().Unix()
}
func (r *Region) getStore() (store *RegionStore) {
store = (*RegionStore)(atomic.LoadPointer(&r.store))
return
}
func (r *Region) compareAndSwapStore(oldStore, newStore *RegionStore) bool {
return atomic.CompareAndSwapPointer(&r.store, unsafe.Pointer(oldStore), unsafe.Pointer(newStore))
}
func (r *Region) checkRegionCacheTTL(ts int64) bool {
for {
lastAccess := atomic.LoadInt64(&r.lastAccess)
if ts-lastAccess > RegionCacheTTLSec {
return false
}
if atomic.CompareAndSwapInt64(&r.lastAccess, lastAccess, ts) {
return true
}
}
}
// invalidate invalidates a region, next time it will got null result.
func (r *Region) invalidate() {
tikvRegionCacheCounterWithInvalidateRegionFromCacheOK.Inc()
atomic.StoreInt64(&r.lastAccess, invalidatedLastAccessTime)
}
// scheduleReload schedules reload region request in next LocateKey.
func (r *Region) scheduleReload() {
oldValue := atomic.LoadInt32(&r.syncFlag)
if oldValue != updated {
return
}
atomic.CompareAndSwapInt32(&r.syncFlag, oldValue, needSync)
}
// needReload checks whether region need reload.
func (r *Region) needReload() bool {
oldValue := atomic.LoadInt32(&r.syncFlag)
if oldValue == updated {
return false
}
return atomic.CompareAndSwapInt32(&r.syncFlag, oldValue, updated)
}
// RegionCache caches Regions loaded from PD.
type RegionCache struct {
pdClient pd.Client
mu struct {
sync.RWMutex // mutex protect cached region
regions map[RegionVerID]*Region // cached regions be organized as regionVerID to region ref mapping
sorted *btree.BTree // cache regions be organized as sorted key to region ref mapping
}
storeMu struct {
sync.RWMutex
stores map[uint64]*Store
}
notifyDieCh chan []string
notifyCheckCh chan struct{}
closeCh chan struct{}
}
// NewRegionCache creates a RegionCache.
func NewRegionCache(pdClient pd.Client) *RegionCache {
c := &RegionCache{
pdClient: pdClient,
}
c.mu.regions = make(map[RegionVerID]*Region)
c.mu.sorted = btree.New(btreeDegree)
c.storeMu.stores = make(map[uint64]*Store)
c.notifyCheckCh = make(chan struct{}, 1)
c.notifyDieCh = make(chan []string, 1)
c.closeCh = make(chan struct{})
go c.asyncCheckAndResolveLoop()
return c
}
// Close releases region cache's resource.
func (c *RegionCache) Close() {
close(c.closeCh)
}
// asyncCheckAndResolveLoop with
func (c *RegionCache) asyncCheckAndResolveLoop() {
var needCheckStores []*Store
for {
select {
case <-c.closeCh:
return
case <-c.notifyCheckCh:
needCheckStores = needCheckStores[:0]
c.checkAndResolve(needCheckStores)
case addrs := <-c.notifyDieCh:
c.invalidStore(addrs)
}
}
}
// checkAndResolve checks and resolve addr of failed stores.
// this method isn't thread-safe and only be used by one goroutine.
func (c *RegionCache) checkAndResolve(needCheckStores []*Store) {
defer func() {
r := recover()
if r != nil {
logutil.BgLogger().Error("panic in the checkAndResolve goroutine",
zap.Reflect("r", r),
zap.Stack("stack trace"))
}
}()
c.storeMu.RLock()
for _, store := range c.storeMu.stores {
state := store.getResolveState()
if state == needCheck {
needCheckStores = append(needCheckStores, store)
}
}
c.storeMu.RUnlock()
for _, store := range needCheckStores {
store.reResolve(c)
}
}
func (c *RegionCache) invalidStore(sAddrs []string) {
c.storeMu.RLock()
for _, store := range c.storeMu.stores {
for _, sAddr := range sAddrs {
if store.addr == sAddr {
atomic.AddUint32(&store.fail, 1)
}
}
}
c.storeMu.RUnlock()
}
// RPCContext contains data that is needed to send RPC to a region.
type RPCContext struct {
Region RegionVerID
Meta *metapb.Region
Peer *metapb.Peer
PeerIdx int
Store *Store
Addr string
}
// GetStoreID returns StoreID.
func (c *RPCContext) GetStoreID() uint64 {
if c.Store != nil {
return c.Store.storeID
}
return 0
}
func (c *RPCContext) String() string {
return fmt.Sprintf("region ID: %d, meta: %s, peer: %s, addr: %s, idx: %d",
c.Region.GetID(), c.Meta, c.Peer, c.Addr, c.PeerIdx)
}
// GetTiKVRPCContext returns RPCContext for a region. If it returns nil, the region
// must be out of date and already dropped from cache.
func (c *RegionCache) GetTiKVRPCContext(bo *Backoffer, id RegionVerID, replicaRead kv.ReplicaReadType, followerStoreSeed uint32) (*RPCContext, error) {
ts := time.Now().Unix()
cachedRegion := c.getCachedRegionWithRLock(id)
if cachedRegion == nil {
return nil, nil
}
if !cachedRegion.checkRegionCacheTTL(ts) {
return nil, nil
}
regionStore := cachedRegion.getStore()
var store *Store
var peer *metapb.Peer
var storeIdx int
switch replicaRead {
case kv.ReplicaReadFollower:
store, peer, storeIdx = cachedRegion.FollowerStorePeer(regionStore, followerStoreSeed)
case kv.ReplicaReadMixed:
store, peer, storeIdx = cachedRegion.AnyStorePeer(regionStore, followerStoreSeed)
default:
store, peer, storeIdx = cachedRegion.WorkStorePeer(regionStore)
}
addr, err := c.getStoreAddr(bo, cachedRegion, store, storeIdx)
if err != nil {
return nil, err
}
// enable by `curl -XPUT -d '1*return("[some-addr]")->return("")' http://host:port/github.com/pingcap/tidb/store/tikv/injectWrongStoreAddr`
failpoint.Inject("injectWrongStoreAddr", func(val failpoint.Value) {
if a, ok := val.(string); ok && len(a) > 0 {
addr = a
}
})
if store == nil || len(addr) == 0 {
// Store not found, region must be out of date.
cachedRegion.invalidate()
return nil, nil
}
storeFailEpoch := atomic.LoadUint32(&store.fail)
if storeFailEpoch != regionStore.storeFails[storeIdx] {
cachedRegion.invalidate()
logutil.BgLogger().Info("invalidate current region, because others failed on same store",
zap.Uint64("region", id.GetID()),
zap.String("store", store.addr))
return nil, nil
}
return &RPCContext{
Region: id,
Meta: cachedRegion.meta,
Peer: peer,
PeerIdx: storeIdx,
Store: store,
Addr: addr,
}, nil
}
// GetTiFlashRPCContext returns RPCContext for a region must access flash store. If it returns nil, the region
// must be out of date and already dropped from cache or not flash store found.
func (c *RegionCache) GetTiFlashRPCContext(bo *Backoffer, id RegionVerID) (*RPCContext, error) {
ts := time.Now().Unix()
cachedRegion := c.getCachedRegionWithRLock(id)
if cachedRegion == nil {
return nil, nil
}
if !cachedRegion.checkRegionCacheTTL(ts) {
return nil, nil
}
regionStore := cachedRegion.getStore()
// sIdx is for load balance of TiFlash store.
sIdx := int(atomic.AddInt32(®ionStore.workTiFlashIdx, 1))
for i := range regionStore.stores {
storeIdx := (sIdx + i) % len(regionStore.stores)
store := regionStore.stores[storeIdx]
addr, err := c.getStoreAddr(bo, cachedRegion, store, storeIdx)
if err != nil {
return nil, err
}
if len(addr) == 0 {
cachedRegion.invalidate()
return nil, nil
}
if store.getResolveState() == needCheck {
store.reResolve(c)
}
if store.storeType != kv.TiFlash {
continue
}
atomic.StoreInt32(®ionStore.workTiFlashIdx, int32(storeIdx))
peer := cachedRegion.meta.Peers[storeIdx]
storeFailEpoch := atomic.LoadUint32(&store.fail)
if storeFailEpoch != regionStore.storeFails[storeIdx] {
cachedRegion.invalidate()
logutil.BgLogger().Info("invalidate current region, because others failed on same store",
zap.Uint64("region", id.GetID()),
zap.String("store", store.addr))
return nil, nil
}
return &RPCContext{
Region: id,
Meta: cachedRegion.meta,
Peer: peer,
PeerIdx: storeIdx,
Store: store,
Addr: addr,
}, nil
}
cachedRegion.invalidate()
return nil, nil
}
// KeyLocation is the region and range that a key is located.
type KeyLocation struct {
Region RegionVerID
StartKey kv.Key
EndKey kv.Key
}
// Contains checks if key is in [StartKey, EndKey).
func (l *KeyLocation) Contains(key []byte) bool {
return bytes.Compare(l.StartKey, key) <= 0 &&
(bytes.Compare(key, l.EndKey) < 0 || len(l.EndKey) == 0)
}
// LocateKey searches for the region and range that the key is located.
func (c *RegionCache) LocateKey(bo *Backoffer, key []byte) (*KeyLocation, error) {
r, err := c.findRegionByKey(bo, key, false)
if err != nil {
return nil, err
}
return &KeyLocation{
Region: r.VerID(),
StartKey: r.StartKey(),
EndKey: r.EndKey(),
}, nil
}
func (c *RegionCache) loadAndInsertRegion(bo *Backoffer, key []byte) (*Region, error) {
r, err := c.loadRegion(bo, key, false)
if err != nil {
return nil, err
}
c.mu.Lock()
c.insertRegionToCache(r)
c.mu.Unlock()
return r, nil
}
// LocateEndKey searches for the region and range that the key is located.
// Unlike LocateKey, start key of a region is exclusive and end key is inclusive.
func (c *RegionCache) LocateEndKey(bo *Backoffer, key []byte) (*KeyLocation, error) {
r, err := c.findRegionByKey(bo, key, true)
if err != nil {
return nil, err
}
return &KeyLocation{
Region: r.VerID(),
StartKey: r.StartKey(),
EndKey: r.EndKey(),
}, nil
}
func (c *RegionCache) findRegionByKey(bo *Backoffer, key []byte, isEndKey bool) (r *Region, err error) {
r = c.searchCachedRegion(key, isEndKey)
if r == nil {
// load region when it is not exists or expired.
lr, err := c.loadRegion(bo, key, isEndKey)
if err != nil {
// no region data, return error if failure.
return nil, err
}
logutil.Eventf(bo.ctx, "load region %d from pd, due to cache-miss", lr.GetID())
r = lr
c.mu.Lock()
c.insertRegionToCache(r)
c.mu.Unlock()
} else if r.needReload() {
// load region when it be marked as need reload.
lr, err := c.loadRegion(bo, key, isEndKey)
if err != nil {
// ignore error and use old region info.
logutil.Logger(bo.ctx).Error("load region failure",
zap.ByteString("key", key), zap.Error(err))
} else {
logutil.Eventf(bo.ctx, "load region %d from pd, due to need-reload", lr.GetID())
r = lr
c.mu.Lock()
c.insertRegionToCache(r)
c.mu.Unlock()
}
}
return r, nil
}
// OnSendFail handles send request fail logic.
func (c *RegionCache) OnSendFail(bo *Backoffer, ctx *RPCContext, scheduleReload bool, err error) {
tikvRegionCacheCounterWithSendFail.Inc()
r := c.getCachedRegionWithRLock(ctx.Region)
if r != nil {
if ctx.Store.storeType == kv.TiKV {
c.switchNextPeer(r, ctx.PeerIdx, err)
} else {
c.switchNextFlashPeer(r, ctx.PeerIdx, err)
}
if scheduleReload {
r.scheduleReload()
}
logutil.Logger(bo.ctx).Info("switch region peer to next due to send request fail",
zap.Stringer("current", ctx),
zap.Bool("needReload", scheduleReload),
zap.Error(err))
}
}
// LocateRegionByID searches for the region with ID.
func (c *RegionCache) LocateRegionByID(bo *Backoffer, regionID uint64) (*KeyLocation, error) {
c.mu.RLock()
r := c.getRegionByIDFromCache(regionID)
c.mu.RUnlock()
if r != nil {
if r.needReload() {
lr, err := c.loadRegionByID(bo, regionID)
if err != nil {
// ignore error and use old region info.
logutil.Logger(bo.ctx).Error("load region failure",
zap.Uint64("regionID", regionID), zap.Error(err))
} else {
r = lr
c.mu.Lock()
c.insertRegionToCache(r)
c.mu.Unlock()
}
}
loc := &KeyLocation{
Region: r.VerID(),
StartKey: r.StartKey(),
EndKey: r.EndKey(),
}
return loc, nil
}
r, err := c.loadRegionByID(bo, regionID)
if err != nil {
return nil, errors.Trace(err)
}
c.mu.Lock()
c.insertRegionToCache(r)
c.mu.Unlock()
return &KeyLocation{
Region: r.VerID(),
StartKey: r.StartKey(),
EndKey: r.EndKey(),
}, nil
}
// GroupKeysByRegion separates keys into groups by their belonging Regions.
// Specially it also returns the first key's region which may be used as the
// 'PrimaryLockKey' and should be committed ahead of others.
// filter is used to filter some unwanted keys.
func (c *RegionCache) GroupKeysByRegion(bo *Backoffer, keys [][]byte, filter func(key, regionStartKey []byte) bool) (map[RegionVerID][][]byte, RegionVerID, error) {
groups := make(map[RegionVerID][][]byte)
var first RegionVerID
var lastLoc *KeyLocation
for i, k := range keys {
if lastLoc == nil || !lastLoc.Contains(k) {
var err error
lastLoc, err = c.LocateKey(bo, k)
if err != nil {
return nil, first, errors.Trace(err)
}
if filter != nil && filter(k, lastLoc.StartKey) {
continue
}
}
id := lastLoc.Region
if i == 0 {
first = id
}
groups[id] = append(groups[id], k)
}
return groups, first, nil
}
type groupedMutations struct {
region RegionVerID
mutations committerMutations
}
// GroupSortedMutationsByRegion separates keys into groups by their belonging Regions.
func (c *RegionCache) GroupSortedMutationsByRegion(bo *Backoffer, m committerMutations) ([]groupedMutations, error) {
var (
groups []groupedMutations
lastLoc *KeyLocation
)
lastUpperBound := 0
for i := range m.keys {
if lastLoc == nil || !lastLoc.Contains(m.keys[i]) {
if lastLoc != nil {
groups = append(groups, groupedMutations{
region: lastLoc.Region,
mutations: m.subRange(lastUpperBound, i),
})
lastUpperBound = i
}
var err error
lastLoc, err = c.LocateKey(bo, m.keys[i])
if err != nil {
return nil, errors.Trace(err)
}
}
}
if lastLoc != nil {
groups = append(groups, groupedMutations{
region: lastLoc.Region,
mutations: m.subRange(lastUpperBound, m.len()),
})
}
return groups, nil
}
// ListRegionIDsInKeyRange lists ids of regions in [start_key,end_key].
func (c *RegionCache) ListRegionIDsInKeyRange(bo *Backoffer, startKey, endKey []byte) (regionIDs []uint64, err error) {
for {
curRegion, err := c.LocateKey(bo, startKey)
if err != nil {
return nil, errors.Trace(err)
}
regionIDs = append(regionIDs, curRegion.Region.id)
if curRegion.Contains(endKey) {
break
}
startKey = curRegion.EndKey
}
return regionIDs, nil
}
// LoadRegionsInKeyRange lists regions in [start_key,end_key].
func (c *RegionCache) LoadRegionsInKeyRange(bo *Backoffer, startKey, endKey []byte) (regions []*Region, err error) {
var batchRegions []*Region
for {
batchRegions, err = c.BatchLoadRegionsWithKeyRange(bo, startKey, endKey, defaultRegionsPerBatch)
if err != nil {
return nil, errors.Trace(err)
}
if len(batchRegions) == 0 {
// should never happen
break
}
regions = append(regions, batchRegions...)
endRegion := batchRegions[len(batchRegions)-1]
if endRegion.Contains(endKey) {
break
}
startKey = endRegion.EndKey()
}
return
}
// BatchLoadRegionsWithKeyRange loads at most given numbers of regions to the RegionCache,
// within the given key range from the startKey to endKey. Returns the loaded regions.
func (c *RegionCache) BatchLoadRegionsWithKeyRange(bo *Backoffer, startKey []byte, endKey []byte, count int) (regions []*Region, err error) {
regions, err = c.scanRegions(bo, startKey, endKey, count)
if err != nil {
return
}
if len(regions) == 0 {
err = errors.New("PD returned no region")
return
}
c.mu.Lock()
defer c.mu.Unlock()
for _, region := range regions {
c.insertRegionToCache(region)
}
return
}
// BatchLoadRegionsFromKey loads at most given numbers of regions to the RegionCache, from the given startKey. Returns
// the endKey of the last loaded region. If some of the regions has no leader, their entries in RegionCache will not be
// updated.
func (c *RegionCache) BatchLoadRegionsFromKey(bo *Backoffer, startKey []byte, count int) ([]byte, error) {
regions, err := c.BatchLoadRegionsWithKeyRange(bo, startKey, nil, count)
if err != nil {
return nil, errors.Trace(err)
}
return regions[len(regions)-1].EndKey(), nil
}
// InvalidateCachedRegion removes a cached Region.
func (c *RegionCache) InvalidateCachedRegion(id RegionVerID) {
cachedRegion := c.getCachedRegionWithRLock(id)
if cachedRegion == nil {
return
}
cachedRegion.invalidate()
}
// UpdateLeader update some region cache with newer leader info.
func (c *RegionCache) UpdateLeader(regionID RegionVerID, leaderStoreID uint64, currentPeerIdx int) {
r := c.getCachedRegionWithRLock(regionID)
if r == nil {
logutil.BgLogger().Debug("regionCache: cannot find region when updating leader",
zap.Uint64("regionID", regionID.GetID()),
zap.Uint64("leaderStoreID", leaderStoreID))
return
}
if leaderStoreID == 0 {
c.switchNextPeer(r, currentPeerIdx, nil)
logutil.BgLogger().Info("switch region peer to next due to NotLeader with NULL leader",
zap.Int("currIdx", currentPeerIdx),
zap.Uint64("regionID", regionID.GetID()))
return
}
if !c.switchToPeer(r, leaderStoreID) {
logutil.BgLogger().Info("invalidate region cache due to cannot find peer when updating leader",
zap.Uint64("regionID", regionID.GetID()),
zap.Int("currIdx", currentPeerIdx),
zap.Uint64("leaderStoreID", leaderStoreID))
r.invalidate()
} else {
logutil.BgLogger().Info("switch region leader to specific leader due to kv return NotLeader",
zap.Uint64("regionID", regionID.GetID()),
zap.Int("currIdx", currentPeerIdx),
zap.Uint64("leaderStoreID", leaderStoreID))
}
}
// insertRegionToCache tries to insert the Region to cache.
func (c *RegionCache) insertRegionToCache(cachedRegion *Region) {
old := c.mu.sorted.ReplaceOrInsert(newBtreeItem(cachedRegion))
if old != nil {
// Don't refresh TiFlash work idx for region. Otherwise, it will always goto a invalid store which
// is under transferring regions.
cachedRegion.getStore().workTiFlashIdx = old.(*btreeItem).cachedRegion.getStore().workTiFlashIdx
delete(c.mu.regions, old.(*btreeItem).cachedRegion.VerID())
}
c.mu.regions[cachedRegion.VerID()] = cachedRegion
}
// searchCachedRegion finds a region from cache by key. Like `getCachedRegion`,
// it should be called with c.mu.RLock(), and the returned Region should not be
// used after c.mu is RUnlock().
// If the given key is the end key of the region that you want, you may set the second argument to true. This is useful
// when processing in reverse order.
func (c *RegionCache) searchCachedRegion(key []byte, isEndKey bool) *Region {
ts := time.Now().Unix()
var r *Region
c.mu.RLock()
c.mu.sorted.DescendLessOrEqual(newBtreeSearchItem(key), func(item btree.Item) bool {
r = item.(*btreeItem).cachedRegion
if isEndKey && bytes.Equal(r.StartKey(), key) {
r = nil // clear result
return true // iterate next item
}
if !r.checkRegionCacheTTL(ts) {
r = nil
return true
}
return false
})
c.mu.RUnlock()
if r != nil && (!isEndKey && r.Contains(key) || isEndKey && r.ContainsByEnd(key)) {
return r
}
return nil
}
// getRegionByIDFromCache tries to get region by regionID from cache. Like
// `getCachedRegion`, it should be called with c.mu.RLock(), and the returned
// Region should not be used after c.mu is RUnlock().
func (c *RegionCache) getRegionByIDFromCache(regionID uint64) *Region {
for v, r := range c.mu.regions {
if v.id == regionID {
return r
}
}
return nil
}
// loadRegion loads region from pd client, and picks the first peer as leader.
// If the given key is the end key of the region that you want, you may set the second argument to true. This is useful
// when processing in reverse order.
func (c *RegionCache) loadRegion(bo *Backoffer, key []byte, isEndKey bool) (*Region, error) {
var backoffErr error
searchPrev := false
for {
if backoffErr != nil {
err := bo.Backoff(BoPDRPC, backoffErr)
if err != nil {
return nil, errors.Trace(err)
}
}
var meta *metapb.Region
var leader *metapb.Peer
var err error
if searchPrev {
meta, leader, err = c.pdClient.GetPrevRegion(bo.ctx, key)
} else {
meta, leader, err = c.pdClient.GetRegion(bo.ctx, key)
}
if err != nil {
tikvRegionCacheCounterWithGetRegionError.Inc()
} else {
tikvRegionCacheCounterWithGetRegionOK.Inc()
}
if err != nil {
backoffErr = errors.Errorf("loadRegion from PD failed, key: %q, err: %v", key, err)
continue
}
if meta == nil {
backoffErr = errors.Errorf("region not found for key %q", key)
continue
}
if len(meta.Peers) == 0 {
return nil, errors.New("receive Region with no peer")
}
if isEndKey && !searchPrev && bytes.Equal(meta.StartKey, key) && len(meta.StartKey) != 0 {
searchPrev = true
continue
}
region := &Region{meta: meta}
region.init(c)
if leader != nil {
c.switchToPeer(region, leader.StoreId)
}
return region, nil
}
}
// loadRegionByID loads region from pd client, and picks the first peer as leader.
func (c *RegionCache) loadRegionByID(bo *Backoffer, regionID uint64) (*Region, error) {
var backoffErr error
for {
if backoffErr != nil {
err := bo.Backoff(BoPDRPC, backoffErr)
if err != nil {
return nil, errors.Trace(err)
}
}
meta, leader, err := c.pdClient.GetRegionByID(bo.ctx, regionID)
if err != nil {
tikvRegionCacheCounterWithGetRegionByIDError.Inc()
} else {
tikvRegionCacheCounterWithGetRegionByIDOK.Inc()
}
if err != nil {
backoffErr = errors.Errorf("loadRegion from PD failed, regionID: %v, err: %v", regionID, err)
continue
}
if meta == nil {
return nil, errors.Errorf("region not found for regionID %d", regionID)
}
if len(meta.Peers) == 0 {
return nil, errors.New("receive Region with no peer")
}
region := &Region{meta: meta}
region.init(c)
if leader != nil {
c.switchToPeer(region, leader.GetStoreId())
}
return region, nil
}
}
// scanRegions scans at most `limit` regions from PD, starts from the region containing `startKey` and in key order.
// Regions with no leader will not be returned.
func (c *RegionCache) scanRegions(bo *Backoffer, startKey, endKey []byte, limit int) ([]*Region, error) {
if limit == 0 {
return nil, nil
}
var backoffErr error
for {
if backoffErr != nil {
err := bo.Backoff(BoPDRPC, backoffErr)
if err != nil {
return nil, errors.Trace(err)
}
}
metas, leaders, err := c.pdClient.ScanRegions(bo.ctx, startKey, endKey, limit)
if err != nil {
tikvRegionCacheCounterWithScanRegionsError.Inc()
backoffErr = errors.Errorf(
"scanRegion from PD failed, startKey: %q, limit: %q, err: %v",
startKey,
limit,
err)
continue
}
tikvRegionCacheCounterWithScanRegionsOK.Inc()
if len(metas) == 0 {
return nil, errors.New("PD returned no region")
}
if len(metas) != len(leaders) {
return nil, errors.New("PD returned mismatching region metas and leaders")
}
regions := make([]*Region, 0, len(metas))
for i, meta := range metas {
region := &Region{meta: meta}
region.init(c)
leader := leaders[i]
// Leader id = 0 indicates no leader.
if leader.GetId() != 0 {
c.switchToPeer(region, leader.GetStoreId())
regions = append(regions, region)
}
}
if len(regions) == 0 {
return nil, errors.New("receive Regions with no peer")
}
if len(regions) < len(metas) {
logutil.Logger(context.Background()).Debug(
"regionCache: scanRegion finished but some regions has no leader.")
}
return regions, nil
}
}
func (c *RegionCache) getCachedRegionWithRLock(regionID RegionVerID) (r *Region) {
c.mu.RLock()
r = c.mu.regions[regionID]
c.mu.RUnlock()
return
}
func (c *RegionCache) getStoreAddr(bo *Backoffer, region *Region, store *Store, storeIdx int) (addr string, err error) {
state := store.getResolveState()
switch state {
case resolved, needCheck:
addr = store.addr
return
case unresolved:
addr, err = store.initResolve(bo, c)
return
case deleted:
addr = c.changeToActiveStore(region, store, storeIdx)
return
default:
panic("unsupported resolve state")
}
}
func (c *RegionCache) changeToActiveStore(region *Region, store *Store, storeIdx int) (addr string) {
c.storeMu.RLock()
store = c.storeMu.stores[store.storeID]
c.storeMu.RUnlock()
for {
oldRegionStore := region.getStore()
newRegionStore := oldRegionStore.clone()
newRegionStore.stores = make([]*Store, 0, len(oldRegionStore.stores))
for i, s := range oldRegionStore.stores {
if i == storeIdx {
newRegionStore.stores = append(newRegionStore.stores, store)
} else {
newRegionStore.stores = append(newRegionStore.stores, s)
}
}
if region.compareAndSwapStore(oldRegionStore, newRegionStore) {
break
}
}