-
Notifications
You must be signed in to change notification settings - Fork 728
/
Copy pathregion.go
1267 lines (1126 loc) · 38.7 KB
/
region.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 TiKV Project Authors.
//
// 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,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package core
import (
"bytes"
"encoding/hex"
"fmt"
"reflect"
"sort"
"strings"
"unsafe"
"github.com/gogo/protobuf/proto"
"github.com/pingcap/errors"
"github.com/pingcap/kvproto/pkg/metapb"
"github.com/pingcap/kvproto/pkg/pdpb"
"github.com/pingcap/kvproto/pkg/replication_modepb"
"github.com/pingcap/log"
"github.com/tikv/pd/pkg/logutil"
"go.uber.org/zap"
)
// errRegionIsStale is error info for region is stale.
func errRegionIsStale(region *metapb.Region, origin *metapb.Region) error {
return errors.Errorf("region is stale: region %v origin %v", region, origin)
}
// RegionInfo records detail region info.
// Read-Only once created.
type RegionInfo struct {
term uint64
meta *metapb.Region
learners []*metapb.Peer
voters []*metapb.Peer
leader *metapb.Peer
downPeers []*pdpb.PeerStats
pendingPeers []*metapb.Peer
writtenBytes uint64
writtenKeys uint64
readBytes uint64
readKeys uint64
approximateSize int64
approximateKeys int64
interval *pdpb.TimeInterval
replicationStatus *replication_modepb.RegionReplicationStatus
QueryStats *pdpb.QueryStats
flowRoundDivisor uint64
}
// NewRegionInfo creates RegionInfo with region's meta and leader peer.
func NewRegionInfo(region *metapb.Region, leader *metapb.Peer, opts ...RegionCreateOption) *RegionInfo {
regionInfo := &RegionInfo{
meta: region,
leader: leader,
}
for _, opt := range opts {
opt(regionInfo)
}
classifyVoterAndLearner(regionInfo)
return regionInfo
}
// classifyVoterAndLearner sorts out voter and learner from peers into different slice.
func classifyVoterAndLearner(region *RegionInfo) {
learners := make([]*metapb.Peer, 0, 1)
voters := make([]*metapb.Peer, 0, len(region.meta.Peers))
for _, p := range region.meta.Peers {
if IsLearner(p) {
learners = append(learners, p)
} else {
voters = append(voters, p)
}
}
sort.Sort(peerSlice(learners))
sort.Sort(peerSlice(voters))
region.learners = learners
region.voters = voters
}
const (
// EmptyRegionApproximateSize is the region approximate size of an empty region
// (heartbeat size <= 1MB).
EmptyRegionApproximateSize = 1
// ImpossibleFlowSize is an impossible flow size (such as written_bytes, read_keys, etc.)
// It may be caused by overflow, refer to https://github.com/tikv/pd/issues/3379.
// They need to be filtered so as not to affect downstream.
// (flow size >= 1024TB)
ImpossibleFlowSize = 1 << 50
// Only statistics within this interval limit are valid.
statsReportMinInterval = 3 // 3s
statsReportMaxInterval = 5 * 60 // 5min
)
// RegionFromHeartbeat constructs a Region from region heartbeat.
func RegionFromHeartbeat(heartbeat *pdpb.RegionHeartbeatRequest, opts ...RegionCreateOption) *RegionInfo {
// Convert unit to MB.
// If region is empty or less than 1MB, use 1MB instead.
regionSize := heartbeat.GetApproximateSize() / (1 << 20)
if regionSize < EmptyRegionApproximateSize {
regionSize = EmptyRegionApproximateSize
}
region := &RegionInfo{
term: heartbeat.GetTerm(),
meta: heartbeat.GetRegion(),
leader: heartbeat.GetLeader(),
downPeers: heartbeat.GetDownPeers(),
pendingPeers: heartbeat.GetPendingPeers(),
writtenBytes: heartbeat.GetBytesWritten(),
writtenKeys: heartbeat.GetKeysWritten(),
readBytes: heartbeat.GetBytesRead(),
readKeys: heartbeat.GetKeysRead(),
approximateSize: int64(regionSize),
approximateKeys: int64(heartbeat.GetApproximateKeys()),
interval: heartbeat.GetInterval(),
replicationStatus: heartbeat.GetReplicationStatus(),
QueryStats: heartbeat.GetQueryStats(),
}
for _, opt := range opts {
opt(region)
}
if region.writtenKeys >= ImpossibleFlowSize || region.writtenBytes >= ImpossibleFlowSize {
region.writtenKeys = 0
region.writtenBytes = 0
}
if region.readKeys >= ImpossibleFlowSize || region.readBytes >= ImpossibleFlowSize {
region.readKeys = 0
region.readBytes = 0
}
sort.Sort(peerStatsSlice(region.downPeers))
sort.Sort(peerSlice(region.pendingPeers))
classifyVoterAndLearner(region)
return region
}
// Clone returns a copy of current regionInfo.
func (r *RegionInfo) Clone(opts ...RegionCreateOption) *RegionInfo {
downPeers := make([]*pdpb.PeerStats, 0, len(r.downPeers))
for _, peer := range r.downPeers {
downPeers = append(downPeers, proto.Clone(peer).(*pdpb.PeerStats))
}
pendingPeers := make([]*metapb.Peer, 0, len(r.pendingPeers))
for _, peer := range r.pendingPeers {
pendingPeers = append(pendingPeers, proto.Clone(peer).(*metapb.Peer))
}
region := &RegionInfo{
term: r.term,
meta: proto.Clone(r.meta).(*metapb.Region),
leader: proto.Clone(r.leader).(*metapb.Peer),
downPeers: downPeers,
pendingPeers: pendingPeers,
writtenBytes: r.writtenBytes,
writtenKeys: r.writtenKeys,
readBytes: r.readBytes,
readKeys: r.readKeys,
approximateSize: r.approximateSize,
approximateKeys: r.approximateKeys,
interval: proto.Clone(r.interval).(*pdpb.TimeInterval),
replicationStatus: r.replicationStatus,
}
for _, opt := range opts {
opt(region)
}
classifyVoterAndLearner(region)
return region
}
// GetTerm returns the current term of the region
func (r *RegionInfo) GetTerm() uint64 {
return r.term
}
// GetLearners returns the learners.
func (r *RegionInfo) GetLearners() []*metapb.Peer {
return r.learners
}
// GetVoters returns the voters.
func (r *RegionInfo) GetVoters() []*metapb.Peer {
return r.voters
}
// GetPeer returns the peer with specified peer id.
func (r *RegionInfo) GetPeer(peerID uint64) *metapb.Peer {
for _, peer := range r.meta.GetPeers() {
if peer.GetId() == peerID {
return peer
}
}
return nil
}
// GetDownPeer returns the down peer with specified peer id.
func (r *RegionInfo) GetDownPeer(peerID uint64) *metapb.Peer {
for _, down := range r.downPeers {
if down.GetPeer().GetId() == peerID {
return down.GetPeer()
}
}
return nil
}
// GetDownVoter returns the down voter with specified peer id.
func (r *RegionInfo) GetDownVoter(peerID uint64) *metapb.Peer {
for _, down := range r.downPeers {
if down.GetPeer().GetId() == peerID && !IsLearner(down.GetPeer()) {
return down.GetPeer()
}
}
return nil
}
// GetDownLearner returns the down learner with soecified peer id.
func (r *RegionInfo) GetDownLearner(peerID uint64) *metapb.Peer {
for _, down := range r.downPeers {
if down.GetPeer().GetId() == peerID && IsLearner(down.GetPeer()) {
return down.GetPeer()
}
}
return nil
}
// GetPendingPeer returns the pending peer with specified peer id.
func (r *RegionInfo) GetPendingPeer(peerID uint64) *metapb.Peer {
for _, peer := range r.pendingPeers {
if peer.GetId() == peerID {
return peer
}
}
return nil
}
// GetPendingVoter returns the pending voter with specified peer id.
func (r *RegionInfo) GetPendingVoter(peerID uint64) *metapb.Peer {
for _, peer := range r.pendingPeers {
if peer.GetId() == peerID && !IsLearner(peer) {
return peer
}
}
return nil
}
// GetPendingLearner returns the pending learner peer with specified peer id.
func (r *RegionInfo) GetPendingLearner(peerID uint64) *metapb.Peer {
for _, peer := range r.pendingPeers {
if peer.GetId() == peerID && IsLearner(peer) {
return peer
}
}
return nil
}
// GetStorePeer returns the peer in specified store.
func (r *RegionInfo) GetStorePeer(storeID uint64) *metapb.Peer {
for _, peer := range r.meta.GetPeers() {
if peer.GetStoreId() == storeID {
return peer
}
}
return nil
}
// GetStoreVoter returns the voter in specified store.
func (r *RegionInfo) GetStoreVoter(storeID uint64) *metapb.Peer {
for _, peer := range r.voters {
if peer.GetStoreId() == storeID {
return peer
}
}
return nil
}
// GetStoreLearner returns the learner peer in specified store.
func (r *RegionInfo) GetStoreLearner(storeID uint64) *metapb.Peer {
for _, peer := range r.learners {
if peer.GetStoreId() == storeID {
return peer
}
}
return nil
}
// GetStoreIds returns a map indicate the region distributed.
func (r *RegionInfo) GetStoreIds() map[uint64]struct{} {
peers := r.meta.GetPeers()
stores := make(map[uint64]struct{}, len(peers))
for _, peer := range peers {
stores[peer.GetStoreId()] = struct{}{}
}
return stores
}
// GetFollowers returns a map indicate the follow peers distributed.
func (r *RegionInfo) GetFollowers() map[uint64]*metapb.Peer {
peers := r.GetVoters()
followers := make(map[uint64]*metapb.Peer, len(peers))
for _, peer := range peers {
if r.leader == nil || r.leader.GetId() != peer.GetId() {
followers[peer.GetStoreId()] = peer
}
}
return followers
}
// GetFollower randomly returns a follow peer.
func (r *RegionInfo) GetFollower() *metapb.Peer {
for _, peer := range r.GetVoters() {
if r.leader == nil || r.leader.GetId() != peer.GetId() {
return peer
}
}
return nil
}
// GetDiffFollowers returns the followers which is not located in the same
// store as any other followers of the another specified region.
func (r *RegionInfo) GetDiffFollowers(other *RegionInfo) []*metapb.Peer {
res := make([]*metapb.Peer, 0, len(r.meta.Peers))
for _, p := range r.GetFollowers() {
diff := true
for _, o := range other.GetFollowers() {
if p.GetStoreId() == o.GetStoreId() {
diff = false
break
}
}
if diff {
res = append(res, p)
}
}
return res
}
// GetID returns the ID of the region.
func (r *RegionInfo) GetID() uint64 {
return r.meta.GetId()
}
// GetMeta returns the meta information of the region.
func (r *RegionInfo) GetMeta() *metapb.Region {
if r == nil {
return nil
}
return r.meta
}
// GetStat returns the statistics of the region.
func (r *RegionInfo) GetStat() *pdpb.RegionStat {
if r == nil {
return nil
}
return &pdpb.RegionStat{
BytesWritten: r.writtenBytes,
BytesRead: r.readBytes,
KeysWritten: r.writtenKeys,
KeysRead: r.readKeys,
}
}
// GetApproximateSize returns the approximate size of the region.
func (r *RegionInfo) GetApproximateSize() int64 {
return r.approximateSize
}
// GetApproximateKeys returns the approximate keys of the region.
func (r *RegionInfo) GetApproximateKeys() int64 {
return r.approximateKeys
}
// GetInterval returns the interval information of the region.
func (r *RegionInfo) GetInterval() *pdpb.TimeInterval {
return r.interval
}
// GetDownPeers returns the down peers of the region.
func (r *RegionInfo) GetDownPeers() []*pdpb.PeerStats {
return r.downPeers
}
// GetPendingPeers returns the pending peers of the region.
func (r *RegionInfo) GetPendingPeers() []*metapb.Peer {
return r.pendingPeers
}
// GetBytesRead returns the read bytes of the region.
func (r *RegionInfo) GetBytesRead() uint64 {
return r.readBytes
}
// GetRoundBytesRead returns the read bytes of the region.
func (r *RegionInfo) GetRoundBytesRead() uint64 {
if r.flowRoundDivisor == 0 {
return r.readBytes
}
return ((r.readBytes + r.flowRoundDivisor/2) / r.flowRoundDivisor) * r.flowRoundDivisor
}
// GetBytesWritten returns the written bytes of the region.
func (r *RegionInfo) GetBytesWritten() uint64 {
return r.writtenBytes
}
// GetRoundBytesWritten returns the written bytes of the region.
func (r *RegionInfo) GetRoundBytesWritten() uint64 {
if r.flowRoundDivisor == 0 {
return r.writtenBytes
}
return ((r.writtenBytes + r.flowRoundDivisor/2) / r.flowRoundDivisor) * r.flowRoundDivisor
}
// GetKeysWritten returns the written keys of the region.
func (r *RegionInfo) GetKeysWritten() uint64 {
return r.writtenKeys
}
// GetKeysRead returns the read keys of the region.
func (r *RegionInfo) GetKeysRead() uint64 {
return r.readKeys
}
// GetWriteRate returns the write rate of the region.
func (r *RegionInfo) GetWriteRate() (bytesRate, keysRate float64) {
reportInterval := r.GetInterval()
interval := reportInterval.GetEndTimestamp() - reportInterval.GetStartTimestamp()
if interval >= statsReportMinInterval && interval <= statsReportMaxInterval {
return float64(r.writtenBytes) / float64(interval), float64(r.writtenKeys) / float64(interval)
}
return 0, 0
}
// GetLeader returns the leader of the region.
func (r *RegionInfo) GetLeader() *metapb.Peer {
return r.leader
}
// GetStartKey returns the start key of the region.
func (r *RegionInfo) GetStartKey() []byte {
return r.meta.StartKey
}
// GetEndKey returns the end key of the region.
func (r *RegionInfo) GetEndKey() []byte {
return r.meta.EndKey
}
// GetPeers returns the peers of the region.
func (r *RegionInfo) GetPeers() []*metapb.Peer {
return r.meta.GetPeers()
}
// GetRegionEpoch returns the region epoch of the region.
func (r *RegionInfo) GetRegionEpoch() *metapb.RegionEpoch {
return r.meta.RegionEpoch
}
// GetReplicationStatus returns the region's replication status.
func (r *RegionInfo) GetReplicationStatus() *replication_modepb.RegionReplicationStatus {
return r.replicationStatus
}
// RegionGuideFunc is a function that determines which follow-up operations need to be performed based on the origin
// and new region information.
type RegionGuideFunc func(region, origin *RegionInfo) (isNew, saveKV, saveCache, needSync bool)
// GenerateRegionGuideFunc is used to generate a RegionGuideFunc. Control the log output by specifying the log function.
// nil means do not print the log.
func GenerateRegionGuideFunc(enableLog bool) RegionGuideFunc {
noLog := func(msg string, fields ...zap.Field) {}
debug, info := noLog, noLog
if enableLog {
debug = log.Debug
info = log.Info
}
// Save to storage if meta is updated.
// Save to cache if meta or leader is updated, or contains any down/pending peer.
// Mark isNew if the region in cache does not have leader.
return func(region, origin *RegionInfo) (isNew, saveKV, saveCache, needSync bool) {
if origin == nil {
debug("insert new region",
zap.Uint64("region-id", region.GetID()),
logutil.ZapRedactStringer("meta-region", RegionToHexMeta(region.GetMeta())))
saveKV, saveCache, isNew = true, true, true
} else {
r := region.GetRegionEpoch()
o := origin.GetRegionEpoch()
if r.GetVersion() > o.GetVersion() {
info("region Version changed",
zap.Uint64("region-id", region.GetID()),
logutil.ZapRedactString("detail", DiffRegionKeyInfo(origin, region)),
zap.Uint64("old-version", o.GetVersion()),
zap.Uint64("new-version", r.GetVersion()),
)
saveKV, saveCache = true, true
}
if r.GetConfVer() > o.GetConfVer() {
info("region ConfVer changed",
zap.Uint64("region-id", region.GetID()),
zap.String("detail", DiffRegionPeersInfo(origin, region)),
zap.Uint64("old-confver", o.GetConfVer()),
zap.Uint64("new-confver", r.GetConfVer()),
)
saveKV, saveCache = true, true
}
if region.GetLeader().GetId() != origin.GetLeader().GetId() {
if origin.GetLeader().GetId() == 0 {
isNew = true
} else {
info("leader changed",
zap.Uint64("region-id", region.GetID()),
zap.Uint64("from", origin.GetLeader().GetStoreId()),
zap.Uint64("to", region.GetLeader().GetStoreId()),
)
}
saveCache, needSync = true, true
}
if !SortedPeersStatsEqual(region.GetDownPeers(), origin.GetDownPeers()) {
debug("down-peers changed", zap.Uint64("region-id", region.GetID()))
saveCache, needSync = true, true
}
if !SortedPeersEqual(region.GetPendingPeers(), origin.GetPendingPeers()) {
debug("pending-peers changed", zap.Uint64("region-id", region.GetID()))
saveCache, needSync = true, true
}
if len(region.GetPeers()) != len(origin.GetPeers()) {
saveKV, saveCache = true, true
}
if region.GetApproximateSize() != origin.GetApproximateSize() ||
region.GetApproximateKeys() != origin.GetApproximateKeys() {
saveCache = true
}
// Once flow has changed, will update the cache.
// Because keys and bytes are strongly related, only bytes are judged.
if region.GetRoundBytesWritten() != origin.GetRoundBytesWritten() ||
region.GetRoundBytesRead() != origin.GetRoundBytesRead() {
saveCache, needSync = true, true
}
if region.GetReplicationStatus().GetState() != replication_modepb.RegionReplicationState_UNKNOWN &&
(region.GetReplicationStatus().GetState() != origin.GetReplicationStatus().GetState() ||
region.GetReplicationStatus().GetStateId() != origin.GetReplicationStatus().GetStateId()) {
saveCache = true
}
}
return
}
}
// regionMap wraps a map[uint64]*regionItem and supports randomly pick a region. They are the leaves of regionTree.
type regionMap map[uint64]*regionItem
func newRegionMap() regionMap {
return make(map[uint64]*regionItem)
}
func (rm regionMap) Len() int {
return len(rm)
}
func (rm regionMap) Get(id uint64) *regionItem {
return rm[id]
}
// AddNew uses RegionInfo to generate a new regionItem.
// If the regionItem already exists, it will be overwritten.
// Note: Do not use this function when you only need to update the RegionInfo and do not need a new regionItem.
func (rm regionMap) AddNew(region *RegionInfo) *regionItem {
item := ®ionItem{region: region}
rm[region.GetID()] = item
return item
}
func (rm regionMap) Delete(id uint64) {
delete(rm, id)
}
// RegionsInfo for export
type RegionsInfo struct {
tree *regionTree
regions regionMap // regionID -> regionInfo
leaders map[uint64]*regionTree // storeID -> sub regionTree
followers map[uint64]*regionTree // storeID -> sub regionTree
learners map[uint64]*regionTree // storeID -> sub regionTree
pendingPeers map[uint64]*regionTree // storeID -> sub regionTree
}
// NewRegionsInfo creates RegionsInfo with tree, regions, leaders and followers
func NewRegionsInfo() *RegionsInfo {
return &RegionsInfo{
tree: newRegionTree(),
regions: newRegionMap(),
leaders: make(map[uint64]*regionTree),
followers: make(map[uint64]*regionTree),
learners: make(map[uint64]*regionTree),
pendingPeers: make(map[uint64]*regionTree),
}
}
// GetRegion returns the RegionInfo with regionID
func (r *RegionsInfo) GetRegion(regionID uint64) *RegionInfo {
if item := r.regions.Get(regionID); item != nil {
return item.region
}
return nil
}
// SetRegion sets the RegionInfo to regionTree and regionMap, also update leaders and followers by region peers
// overlaps: Other regions that overlap with the specified region, excluding itself.
func (r *RegionsInfo) SetRegion(region *RegionInfo) (overlaps []*RegionInfo) {
var item *regionItem // Pointer to the *RegionInfo of this ID.
var origin *RegionInfo // This is the original region information of this ID.
var rangeChanged bool // This Region is new, or its range has changed.
var peersChanged bool // This Region is new, or its peers have changed, including leader-change/pending/down.
if item = r.regions.Get(region.GetID()); item != nil {
// If this ID already exists, use the existing regionItem and pick out the origin.
origin = item.region
rangeChanged = !bytes.Equal(origin.GetStartKey(), region.GetStartKey()) ||
!bytes.Equal(origin.GetEndKey(), region.GetEndKey())
if rangeChanged {
// Delete itself in regionTree so that overlaps will not contain itself.
// Because the regionItem is reused, there is no need to delete it in the regionMap.
r.tree.remove(origin)
// A change in the range is equivalent to a change in all peers.
peersChanged = true
} else {
peersChanged = r.shouldRemoveFromSubTree(region, origin)
}
// If the peers have changed, the sub regionTree needs to be cleaned up.
if peersChanged {
// TODO: Improve performance by deleting only the different peers.
r.removeRegionFromSubTree(origin)
}
// Update the RegionInfo in the regionItem.
item.region = region
} else {
// If this ID does not exist, generate a new regionItem and save it in the regionMap.
rangeChanged = true
peersChanged = true
item = r.regions.AddNew(region)
}
if !rangeChanged {
// If the range is not changed, only the statistical on the regionTree needs to be updated.
r.tree.updateStat(origin, region)
} else {
// It has been removed and all information needs to be updated again.
overlaps = r.tree.update(item)
for _, old := range overlaps {
r.RemoveRegion(r.GetRegion(old.GetID()))
}
}
if !peersChanged {
// If the peers are not changed, only the statistical on the sub regionTree needs to be updated.
r.updateSubTreeStat(origin, region)
} else {
// It has been removed and all information needs to be updated again.
// Add to leaders and followers.
for _, peer := range region.GetVoters() {
storeID := peer.GetStoreId()
if peer.GetId() == region.leader.GetId() {
// Add leader peer to leaders.
store, ok := r.leaders[storeID]
if !ok {
store = newRegionTree()
r.leaders[storeID] = store
}
store.update(item)
} else {
// Add follower peer to followers.
store, ok := r.followers[storeID]
if !ok {
store = newRegionTree()
r.followers[storeID] = store
}
store.update(item)
}
}
// Add to learners.
for _, peer := range region.GetLearners() {
storeID := peer.GetStoreId()
store, ok := r.learners[storeID]
if !ok {
store = newRegionTree()
r.learners[storeID] = store
}
store.update(item)
}
// Add to PendingPeers
for _, peer := range region.GetPendingPeers() {
storeID := peer.GetStoreId()
store, ok := r.pendingPeers[storeID]
if !ok {
store = newRegionTree()
r.pendingPeers[storeID] = store
}
store.update(item)
}
}
return
}
// Len returns the RegionsInfo length
func (r *RegionsInfo) Len() int {
return r.regions.Len()
}
// TreeLen returns the RegionsInfo tree length(now only used in test)
func (r *RegionsInfo) TreeLen() int {
return r.tree.length()
}
func (r *RegionsInfo) updateSubTreeStat(origin *RegionInfo, region *RegionInfo) {
for _, peer := range region.GetVoters() {
storeID := peer.GetStoreId()
if peer.GetId() == region.leader.GetId() {
if tree, ok := r.leaders[storeID]; ok {
tree.updateStat(origin, region)
}
} else {
if tree, ok := r.followers[storeID]; ok {
tree.updateStat(origin, region)
}
}
}
for _, peer := range region.GetLearners() {
if tree, ok := r.learners[peer.GetStoreId()]; ok {
tree.updateStat(origin, region)
}
}
for _, peer := range region.GetPendingPeers() {
if tree, ok := r.pendingPeers[peer.GetStoreId()]; ok {
tree.updateStat(origin, region)
}
}
}
// GetOverlaps returns the regions which are overlapped with the specified region range.
func (r *RegionsInfo) GetOverlaps(region *RegionInfo) []*RegionInfo {
return r.tree.getOverlaps(region)
}
// RemoveRegion removes RegionInfo from regionTree and regionMap
func (r *RegionsInfo) RemoveRegion(region *RegionInfo) {
// Remove from tree and regions.
r.tree.remove(region)
r.regions.Delete(region.GetID())
// Remove from leaders and followers.
r.removeRegionFromSubTree(region)
}
// removeRegionFromSubTree removes RegionInfo from regionSubTrees
func (r *RegionsInfo) removeRegionFromSubTree(region *RegionInfo) {
// Remove from leaders and followers.
for _, peer := range region.meta.GetPeers() {
storeID := peer.GetStoreId()
r.leaders[storeID].remove(region)
r.followers[storeID].remove(region)
r.learners[storeID].remove(region)
r.pendingPeers[storeID].remove(region)
}
}
type peerSlice []*metapb.Peer
func (s peerSlice) Len() int {
return len(s)
}
func (s peerSlice) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s peerSlice) Less(i, j int) bool {
return s[i].GetId() < s[j].GetId()
}
// SortedPeersEqual judges whether two sorted `peerSlice` are equal
func SortedPeersEqual(peersA, peersB []*metapb.Peer) bool {
if len(peersA) != len(peersB) {
return false
}
for i, peerA := range peersA {
peerB := peersB[i]
if peerA.GetStoreId() != peerB.GetStoreId() || peerA.GetId() != peerB.GetId() {
return false
}
}
return true
}
type peerStatsSlice []*pdpb.PeerStats
func (s peerStatsSlice) Len() int {
return len(s)
}
func (s peerStatsSlice) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s peerStatsSlice) Less(i, j int) bool {
return s[i].GetPeer().GetId() < s[j].GetPeer().GetId()
}
// SortedPeersStatsEqual judges whether two sorted `peerStatsSlice` are equal
func SortedPeersStatsEqual(peersA, peersB []*pdpb.PeerStats) bool {
if len(peersA) != len(peersB) {
return false
}
for i, peerStatsA := range peersA {
peerA := peerStatsA.GetPeer()
peerB := peersB[i].GetPeer()
if peerA.GetStoreId() != peerB.GetStoreId() || peerA.GetId() != peerB.GetId() {
return false
}
}
return true
}
// shouldRemoveFromSubTree return true when the region leader changed, peer transferred,
// new peer was created, learners changed, pendingPeers changed, and so on.
func (r *RegionsInfo) shouldRemoveFromSubTree(region *RegionInfo, origin *RegionInfo) bool {
return origin.leader.GetId() != region.leader.GetId() ||
!SortedPeersEqual(origin.GetVoters(), region.GetVoters()) ||
!SortedPeersEqual(origin.GetLearners(), region.GetLearners()) ||
!SortedPeersEqual(origin.GetPendingPeers(), region.GetPendingPeers())
}
// SearchRegion searches RegionInfo from regionTree
func (r *RegionsInfo) SearchRegion(regionKey []byte) *RegionInfo {
region := r.tree.search(regionKey)
if region == nil {
return nil
}
return r.GetRegion(region.GetID())
}
// SearchPrevRegion searches previous RegionInfo from regionTree
func (r *RegionsInfo) SearchPrevRegion(regionKey []byte) *RegionInfo {
region := r.tree.searchPrev(regionKey)
if region == nil {
return nil
}
return r.GetRegion(region.GetID())
}
// GetRegions gets all RegionInfo from regionMap
func (r *RegionsInfo) GetRegions() []*RegionInfo {
regions := make([]*RegionInfo, 0, r.regions.Len())
for _, item := range r.regions {
regions = append(regions, item.region)
}
return regions
}
// GetStoreRegions gets all RegionInfo with a given storeID
func (r *RegionsInfo) GetStoreRegions(storeID uint64) []*RegionInfo {
regions := make([]*RegionInfo, 0, r.GetStoreRegionCount(storeID))
if leaders, ok := r.leaders[storeID]; ok {
regions = append(regions, leaders.scanRanges()...)
}
if followers, ok := r.followers[storeID]; ok {
regions = append(regions, followers.scanRanges()...)
}
if learners, ok := r.learners[storeID]; ok {
regions = append(regions, learners.scanRanges()...)
}
return regions
}
// GetStoreLeaderRegionSize get total size of store's leader regions
func (r *RegionsInfo) GetStoreLeaderRegionSize(storeID uint64) int64 {
return r.leaders[storeID].TotalSize()
}
// GetStoreFollowerRegionSize get total size of store's follower regions
func (r *RegionsInfo) GetStoreFollowerRegionSize(storeID uint64) int64 {
return r.followers[storeID].TotalSize()
}
// GetStoreLearnerRegionSize get total size of store's learner regions
func (r *RegionsInfo) GetStoreLearnerRegionSize(storeID uint64) int64 {
return r.learners[storeID].TotalSize()
}
// GetStoreRegionSize get total size of store's regions
func (r *RegionsInfo) GetStoreRegionSize(storeID uint64) int64 {
return r.GetStoreLeaderRegionSize(storeID) + r.GetStoreFollowerRegionSize(storeID) + r.GetStoreLearnerRegionSize(storeID)
}
// GetStoreLeaderWriteRate get total write rate of store's leaders
func (r *RegionsInfo) GetStoreLeaderWriteRate(storeID uint64) (bytesRate, keysRate float64) {
return r.leaders[storeID].TotalWriteRate()
}
// GetStoreWriteRate get total write rate of store's regions
func (r *RegionsInfo) GetStoreWriteRate(storeID uint64) (bytesRate, keysRate float64) {
storeBytesRate, storeKeysRate := r.leaders[storeID].TotalWriteRate()
bytesRate += storeBytesRate
keysRate += storeKeysRate
storeBytesRate, storeKeysRate = r.followers[storeID].TotalWriteRate()
bytesRate += storeBytesRate
keysRate += storeKeysRate
storeBytesRate, storeKeysRate = r.learners[storeID].TotalWriteRate()
bytesRate += storeBytesRate
keysRate += storeKeysRate
return
}
// GetMetaRegions gets a set of metapb.Region from regionMap
func (r *RegionsInfo) GetMetaRegions() []*metapb.Region {
regions := make([]*metapb.Region, 0, r.regions.Len())
for _, item := range r.regions {
regions = append(regions, proto.Clone(item.region.meta).(*metapb.Region))
}
return regions
}
// GetRegionCount gets the total count of RegionInfo of regionMap
func (r *RegionsInfo) GetRegionCount() int {
return r.regions.Len()
}
// GetStoreRegionCount gets the total count of a store's leader, follower and learner RegionInfo by storeID
func (r *RegionsInfo) GetStoreRegionCount(storeID uint64) int {
return r.GetStoreLeaderCount(storeID) + r.GetStoreFollowerCount(storeID) + r.GetStoreLearnerCount(storeID)
}
// GetStorePendingPeerCount gets the total count of a store's region that includes pending peer
func (r *RegionsInfo) GetStorePendingPeerCount(storeID uint64) int {
return r.pendingPeers[storeID].length()
}
// GetStoreLeaderCount get the total count of a store's leader RegionInfo
func (r *RegionsInfo) GetStoreLeaderCount(storeID uint64) int {
return r.leaders[storeID].length()
}
// GetStoreFollowerCount get the total count of a store's follower RegionInfo
func (r *RegionsInfo) GetStoreFollowerCount(storeID uint64) int {
return r.followers[storeID].length()
}
// GetStoreLearnerCount get the total count of a store's learner RegionInfo
func (r *RegionsInfo) GetStoreLearnerCount(storeID uint64) int {
return r.learners[storeID].length()
}
// RandPendingRegion randomly gets a store's region with a pending peer.
func (r *RegionsInfo) RandPendingRegion(storeID uint64, ranges []KeyRange) *RegionInfo {
return r.pendingPeers[storeID].RandomRegion(ranges)
}
// RandPendingRegions randomly gets a store's n regions with a pending peer.
func (r *RegionsInfo) RandPendingRegions(storeID uint64, ranges []KeyRange, n int) []*RegionInfo {
return r.pendingPeers[storeID].RandomRegions(n, ranges)
}
// RandLeaderRegion randomly gets a store's leader region.
func (r *RegionsInfo) RandLeaderRegion(storeID uint64, ranges []KeyRange) *RegionInfo {
return r.leaders[storeID].RandomRegion(ranges)
}
// RandLeaderRegions randomly gets a store's n leader regions.
func (r *RegionsInfo) RandLeaderRegions(storeID uint64, ranges []KeyRange, n int) []*RegionInfo {
return r.leaders[storeID].RandomRegions(n, ranges)
}
// RandFollowerRegion randomly gets a store's follower region.
func (r *RegionsInfo) RandFollowerRegion(storeID uint64, ranges []KeyRange) *RegionInfo {
return r.followers[storeID].RandomRegion(ranges)
}
// RandFollowerRegions randomly gets a store's n follower regions.
func (r *RegionsInfo) RandFollowerRegions(storeID uint64, ranges []KeyRange, n int) []*RegionInfo {
return r.followers[storeID].RandomRegions(n, ranges)
}
// RandLearnerRegion randomly gets a store's learner region.
func (r *RegionsInfo) RandLearnerRegion(storeID uint64, ranges []KeyRange) *RegionInfo {
return r.learners[storeID].RandomRegion(ranges)