-
Notifications
You must be signed in to change notification settings - Fork 714
/
hot_region.go
1972 lines (1801 loc) · 69.7 KB
/
hot_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 2017 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 schedulers
import (
"fmt"
"math"
"math/rand"
"net/http"
"sort"
"strconv"
"time"
"github.com/pingcap/kvproto/pkg/metapb"
"github.com/pingcap/kvproto/pkg/pdpb"
"github.com/pingcap/log"
"github.com/prometheus/client_golang/prometheus"
"github.com/tikv/pd/pkg/core"
"github.com/tikv/pd/pkg/core/constant"
"github.com/tikv/pd/pkg/errs"
sche "github.com/tikv/pd/pkg/schedule/core"
"github.com/tikv/pd/pkg/schedule/filter"
"github.com/tikv/pd/pkg/schedule/operator"
"github.com/tikv/pd/pkg/schedule/plan"
"github.com/tikv/pd/pkg/slice"
"github.com/tikv/pd/pkg/statistics"
"github.com/tikv/pd/pkg/statistics/buckets"
"github.com/tikv/pd/pkg/statistics/utils"
"github.com/tikv/pd/pkg/utils/keyutil"
"github.com/tikv/pd/pkg/utils/syncutil"
"go.uber.org/zap"
)
const (
// HotRegionName is balance hot region scheduler name.
HotRegionName = "balance-hot-region-scheduler"
// HotRegionType is balance hot region scheduler type.
HotRegionType = "hot-region"
splitHotReadBuckets = "split-hot-read-region"
splitHotWriteBuckets = "split-hot-write-region"
splitProgressiveRank = int64(-5)
minHotScheduleInterval = time.Second
maxHotScheduleInterval = 20 * time.Second
defaultPendingAmpFactor = 2.0
defaultStddevThreshold = 0.1
defaultTopnPosition = 10
)
var (
// pendingAmpFactor will amplify the impact of pending influence, making scheduling slower or even serial when two stores are close together
pendingAmpFactor = defaultPendingAmpFactor
// If the distribution of a dimension is below the corresponding stddev threshold, then scheduling will no longer be based on this dimension,
// as it implies that this dimension is sufficiently uniform.
stddevThreshold = defaultStddevThreshold
// topnPosition is the position of the topn peer in the hot peer list.
// We use it to judge whether to schedule the hot peer in some cases.
topnPosition = defaultTopnPosition
// statisticsInterval is the interval to update statistics information.
statisticsInterval = time.Second
)
var (
// WithLabelValues is a heavy operation, define variable to avoid call it every time.
hotSchedulerCounter = schedulerCounter.WithLabelValues(HotRegionName, "schedule")
hotSchedulerSkipCounter = schedulerCounter.WithLabelValues(HotRegionName, "skip")
hotSchedulerSearchRevertRegionsCounter = schedulerCounter.WithLabelValues(HotRegionName, "search_revert_regions")
hotSchedulerNotSameEngineCounter = schedulerCounter.WithLabelValues(HotRegionName, "not_same_engine")
hotSchedulerNoRegionCounter = schedulerCounter.WithLabelValues(HotRegionName, "no_region")
hotSchedulerUnhealthyReplicaCounter = schedulerCounter.WithLabelValues(HotRegionName, "unhealthy_replica")
hotSchedulerAbnormalReplicaCounter = schedulerCounter.WithLabelValues(HotRegionName, "abnormal_replica")
hotSchedulerCreateOperatorFailedCounter = schedulerCounter.WithLabelValues(HotRegionName, "create_operator_failed")
hotSchedulerNewOperatorCounter = schedulerCounter.WithLabelValues(HotRegionName, "new_operator")
hotSchedulerSnapshotSenderLimitCounter = schedulerCounter.WithLabelValues(HotRegionName, "snapshot_sender_limit")
// counter related with the split region
hotSchedulerNotFoundSplitKeysCounter = schedulerCounter.WithLabelValues(HotRegionName, "not_found_split_keys")
hotSchedulerRegionBucketsNotHotCounter = schedulerCounter.WithLabelValues(HotRegionName, "region_buckets_not_hot")
hotSchedulerOnlyOneBucketsHotCounter = schedulerCounter.WithLabelValues(HotRegionName, "only_one_buckets_hot")
hotSchedulerHotBucketNotValidCounter = schedulerCounter.WithLabelValues(HotRegionName, "hot_buckets_not_valid")
hotSchedulerRegionBucketsSingleHotSpotCounter = schedulerCounter.WithLabelValues(HotRegionName, "region_buckets_single_hot_spot")
hotSchedulerSplitSuccessCounter = schedulerCounter.WithLabelValues(HotRegionName, "split_success")
hotSchedulerNeedSplitBeforeScheduleCounter = schedulerCounter.WithLabelValues(HotRegionName, "need_split_before_move_peer")
hotSchedulerRegionTooHotNeedSplitCounter = schedulerCounter.WithLabelValues(HotRegionName, "region_is_too_hot_need_split")
hotSchedulerMoveLeaderCounter = schedulerCounter.WithLabelValues(HotRegionName, moveLeader.String())
hotSchedulerMovePeerCounter = schedulerCounter.WithLabelValues(HotRegionName, movePeer.String())
hotSchedulerTransferLeaderCounter = schedulerCounter.WithLabelValues(HotRegionName, transferLeader.String())
readSkipAllDimUniformStoreCounter = schedulerCounter.WithLabelValues(HotRegionName, "read-skip-all-dim-uniform-store")
writeSkipAllDimUniformStoreCounter = schedulerCounter.WithLabelValues(HotRegionName, "write-skip-all-dim-uniform-store")
readSkipByteDimUniformStoreCounter = schedulerCounter.WithLabelValues(HotRegionName, "read-skip-byte-uniform-store")
writeSkipByteDimUniformStoreCounter = schedulerCounter.WithLabelValues(HotRegionName, "write-skip-byte-uniform-store")
readSkipKeyDimUniformStoreCounter = schedulerCounter.WithLabelValues(HotRegionName, "read-skip-key-uniform-store")
writeSkipKeyDimUniformStoreCounter = schedulerCounter.WithLabelValues(HotRegionName, "write-skip-key-uniform-store")
readSkipQueryDimUniformStoreCounter = schedulerCounter.WithLabelValues(HotRegionName, "read-skip-query-uniform-store")
writeSkipQueryDimUniformStoreCounter = schedulerCounter.WithLabelValues(HotRegionName, "write-skip-query-uniform-store")
pendingOpFailsStoreCounter = schedulerCounter.WithLabelValues(HotRegionName, "pending-op-fails")
)
type baseHotScheduler struct {
*BaseScheduler
// stLoadInfos contain store statistics information by resource type.
// stLoadInfos is temporary states but exported to API or metrics.
// Every time `Schedule()` will recalculate it.
stLoadInfos [resourceTypeLen]map[uint64]*statistics.StoreLoadDetail
// stHistoryLoads stores the history `stLoadInfos`
// Every time `Schedule()` will rolling update it.
stHistoryLoads *statistics.StoreHistoryLoads
// regionPendings stores regionID -> pendingInfluence,
// this records regionID which have pending Operator by operation type. During filterHotPeers, the hot peers won't
// be selected if its owner region is tracked in this attribute.
regionPendings map[uint64]*pendingInfluence
// types is the resource types that the scheduler considers.
types []resourceType
r *rand.Rand
updateReadTime time.Time
updateWriteTime time.Time
}
func newBaseHotScheduler(opController *operator.Controller, sampleDuration time.Duration, sampleInterval time.Duration) *baseHotScheduler {
base := NewBaseScheduler(opController)
ret := &baseHotScheduler{
BaseScheduler: base,
regionPendings: make(map[uint64]*pendingInfluence),
stHistoryLoads: statistics.NewStoreHistoryLoads(utils.DimLen, sampleDuration, sampleInterval),
r: rand.New(rand.NewSource(time.Now().UnixNano())),
}
for ty := resourceType(0); ty < resourceTypeLen; ty++ {
ret.types = append(ret.types, ty)
ret.stLoadInfos[ty] = map[uint64]*statistics.StoreLoadDetail{}
}
return ret
}
// prepareForBalance calculate the summary of pending Influence for each store and prepare the load detail for
// each store, only update read or write load detail
func (h *baseHotScheduler) prepareForBalance(typ resourceType, cluster sche.SchedulerCluster) {
storeInfos := statistics.SummaryStoreInfos(cluster.GetStores())
h.summaryPendingInfluence(storeInfos)
storesLoads := cluster.GetStoresLoads()
isTraceRegionFlow := cluster.GetSchedulerConfig().IsTraceRegionFlow()
prepare := func(regionStats map[uint64][]*statistics.HotPeerStat, rw utils.RWType, resource constant.ResourceKind) {
ty := buildResourceType(rw, resource)
h.stLoadInfos[ty] = statistics.SummaryStoresLoad(
storeInfos,
storesLoads,
h.stHistoryLoads,
regionStats,
isTraceRegionFlow,
rw, resource)
}
switch typ {
case readLeader, readPeer:
// update read statistics
if time.Since(h.updateReadTime) >= statisticsInterval {
regionRead := cluster.RegionReadStats()
prepare(regionRead, utils.Read, constant.LeaderKind)
prepare(regionRead, utils.Read, constant.RegionKind)
h.updateReadTime = time.Now()
}
case writeLeader, writePeer:
// update write statistics
if time.Since(h.updateWriteTime) >= statisticsInterval {
regionWrite := cluster.RegionWriteStats()
prepare(regionWrite, utils.Write, constant.LeaderKind)
prepare(regionWrite, utils.Write, constant.RegionKind)
h.updateWriteTime = time.Now()
}
default:
log.Error("invalid resource type", zap.String("type", typ.String()))
}
}
func (h *baseHotScheduler) updateHistoryLoadConfig(sampleDuration, sampleInterval time.Duration) {
h.stHistoryLoads = h.stHistoryLoads.UpdateConfig(sampleDuration, sampleInterval)
}
// summaryPendingInfluence calculate the summary of pending Influence for each store
// and clean the region from regionInfluence if they have ended operator.
// It makes each dim rate or count become `weight` times to the origin value.
func (h *baseHotScheduler) summaryPendingInfluence(storeInfos map[uint64]*statistics.StoreSummaryInfo) {
for id, p := range h.regionPendings {
for _, from := range p.froms {
from := storeInfos[from]
to := storeInfos[p.to]
maxZombieDur := p.maxZombieDuration
weight, needGC := calcPendingInfluence(p.op, maxZombieDur)
if needGC {
delete(h.regionPendings, id)
continue
}
if from != nil && weight > 0 {
from.AddInfluence(&p.origin, -weight)
}
if to != nil && weight > 0 {
to.AddInfluence(&p.origin, weight)
}
}
}
for storeID, info := range storeInfos {
storeLabel := strconv.FormatUint(storeID, 10)
if infl := info.PendingSum; infl != nil && len(infl.Loads) != 0 {
utils.ForeachRegionStats(func(rwTy utils.RWType, dim int, kind utils.RegionStatKind) {
setHotPendingInfluenceMetrics(storeLabel, rwTy.String(), utils.DimToString(dim), infl.Loads[kind])
})
}
}
}
// setHotPendingInfluenceMetrics sets pending influence in hot scheduler.
func setHotPendingInfluenceMetrics(storeLabel, rwTy, dim string, load float64) {
HotPendingSum.WithLabelValues(storeLabel, rwTy, dim).Set(load)
}
func (h *baseHotScheduler) randomType() resourceType {
return h.types[h.r.Int()%len(h.types)]
}
type hotScheduler struct {
name string
*baseHotScheduler
syncutil.RWMutex
// config of hot scheduler
conf *hotRegionSchedulerConfig
searchRevertRegions [resourceTypeLen]bool // Whether to search revert regions.
}
func newHotScheduler(opController *operator.Controller, conf *hotRegionSchedulerConfig) *hotScheduler {
base := newBaseHotScheduler(opController,
conf.GetHistorySampleDuration(), conf.GetHistorySampleInterval())
ret := &hotScheduler{
name: HotRegionName,
baseHotScheduler: base,
conf: conf,
}
for ty := resourceType(0); ty < resourceTypeLen; ty++ {
ret.searchRevertRegions[ty] = false
}
return ret
}
func (h *hotScheduler) GetName() string {
return h.name
}
func (*hotScheduler) GetType() string {
return HotRegionType
}
func (h *hotScheduler) EncodeConfig() ([]byte, error) {
return h.conf.EncodeConfig()
}
func (h *hotScheduler) ReloadConfig() error {
h.conf.Lock()
defer h.conf.Unlock()
cfgData, err := h.conf.storage.LoadSchedulerConfig(h.GetName())
if err != nil {
return err
}
if len(cfgData) == 0 {
return nil
}
newCfg := &hotRegionSchedulerConfig{}
if err := DecodeConfig([]byte(cfgData), newCfg); err != nil {
return err
}
h.conf.MinHotByteRate = newCfg.MinHotByteRate
h.conf.MinHotKeyRate = newCfg.MinHotKeyRate
h.conf.MinHotQueryRate = newCfg.MinHotQueryRate
h.conf.MaxZombieRounds = newCfg.MaxZombieRounds
h.conf.MaxPeerNum = newCfg.MaxPeerNum
h.conf.ByteRateRankStepRatio = newCfg.ByteRateRankStepRatio
h.conf.KeyRateRankStepRatio = newCfg.KeyRateRankStepRatio
h.conf.QueryRateRankStepRatio = newCfg.QueryRateRankStepRatio
h.conf.CountRankStepRatio = newCfg.CountRankStepRatio
h.conf.GreatDecRatio = newCfg.GreatDecRatio
h.conf.MinorDecRatio = newCfg.MinorDecRatio
h.conf.SrcToleranceRatio = newCfg.SrcToleranceRatio
h.conf.DstToleranceRatio = newCfg.DstToleranceRatio
h.conf.WriteLeaderPriorities = newCfg.WriteLeaderPriorities
h.conf.WritePeerPriorities = newCfg.WritePeerPriorities
h.conf.ReadPriorities = newCfg.ReadPriorities
h.conf.StrictPickingStore = newCfg.StrictPickingStore
h.conf.EnableForTiFlash = newCfg.EnableForTiFlash
h.conf.RankFormulaVersion = newCfg.RankFormulaVersion
h.conf.ForbidRWType = newCfg.ForbidRWType
h.conf.SplitThresholds = newCfg.SplitThresholds
h.conf.HistorySampleDuration = newCfg.HistorySampleDuration
h.conf.HistorySampleInterval = newCfg.HistorySampleInterval
return nil
}
func (h *hotScheduler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.conf.ServeHTTP(w, r)
}
func (*hotScheduler) GetMinInterval() time.Duration {
return minHotScheduleInterval
}
func (h *hotScheduler) GetNextInterval(time.Duration) time.Duration {
return intervalGrow(h.GetMinInterval(), maxHotScheduleInterval, exponentialGrowth)
}
func (h *hotScheduler) IsScheduleAllowed(cluster sche.SchedulerCluster) bool {
allowed := h.OpController.OperatorCount(operator.OpHotRegion) < cluster.GetSchedulerConfig().GetHotRegionScheduleLimit()
if !allowed {
operator.OperatorLimitCounter.WithLabelValues(h.GetType(), operator.OpHotRegion.String()).Inc()
}
return allowed
}
func (h *hotScheduler) Schedule(cluster sche.SchedulerCluster, _ bool) ([]*operator.Operator, []plan.Plan) {
hotSchedulerCounter.Inc()
typ := h.randomType()
return h.dispatch(typ, cluster), nil
}
func (h *hotScheduler) dispatch(typ resourceType, cluster sche.SchedulerCluster) []*operator.Operator {
h.Lock()
defer h.Unlock()
h.updateHistoryLoadConfig(h.conf.GetHistorySampleDuration(), h.conf.GetHistorySampleInterval())
h.prepareForBalance(typ, cluster)
// IsForbidRWType can not be move earlier to support to use api and metrics.
switch typ {
case readLeader, readPeer:
if h.conf.IsForbidRWType(utils.Read) {
return nil
}
return h.balanceHotReadRegions(cluster)
case writePeer:
if h.conf.IsForbidRWType(utils.Write) {
return nil
}
return h.balanceHotWritePeers(cluster)
case writeLeader:
if h.conf.IsForbidRWType(utils.Write) {
return nil
}
return h.balanceHotWriteLeaders(cluster)
}
return nil
}
func (h *hotScheduler) tryAddPendingInfluence(op *operator.Operator, srcStore []uint64, dstStore uint64, infl statistics.Influence, maxZombieDur time.Duration) bool {
regionID := op.RegionID()
_, ok := h.regionPendings[regionID]
if ok {
pendingOpFailsStoreCounter.Inc()
return false
}
influence := newPendingInfluence(op, srcStore, dstStore, infl, maxZombieDur)
h.regionPendings[regionID] = influence
utils.ForeachRegionStats(func(rwTy utils.RWType, dim int, kind utils.RegionStatKind) {
hotPeerHist.WithLabelValues(h.GetName(), rwTy.String(), utils.DimToString(dim)).Observe(infl.Loads[kind])
})
return true
}
func (h *hotScheduler) balanceHotReadRegions(cluster sche.SchedulerCluster) []*operator.Operator {
leaderSolver := newBalanceSolver(h, cluster, utils.Read, transferLeader)
leaderOps := leaderSolver.solve()
peerSolver := newBalanceSolver(h, cluster, utils.Read, movePeer)
peerOps := peerSolver.solve()
if len(leaderOps) == 0 && len(peerOps) == 0 {
hotSchedulerSkipCounter.Inc()
return nil
}
if len(leaderOps) == 0 {
if peerSolver.tryAddPendingInfluence() {
return peerOps
}
hotSchedulerSkipCounter.Inc()
return nil
}
if len(peerOps) == 0 {
if leaderSolver.tryAddPendingInfluence() {
return leaderOps
}
hotSchedulerSkipCounter.Inc()
return nil
}
leaderSolver.cur = leaderSolver.best
if leaderSolver.betterThan(peerSolver.best) {
if leaderSolver.tryAddPendingInfluence() {
return leaderOps
}
if peerSolver.tryAddPendingInfluence() {
return peerOps
}
} else {
if peerSolver.tryAddPendingInfluence() {
return peerOps
}
if leaderSolver.tryAddPendingInfluence() {
return leaderOps
}
}
hotSchedulerSkipCounter.Inc()
return nil
}
func (h *hotScheduler) balanceHotWritePeers(cluster sche.SchedulerCluster) []*operator.Operator {
peerSolver := newBalanceSolver(h, cluster, utils.Write, movePeer)
ops := peerSolver.solve()
if len(ops) > 0 && peerSolver.tryAddPendingInfluence() {
return ops
}
return nil
}
func (h *hotScheduler) balanceHotWriteLeaders(cluster sche.SchedulerCluster) []*operator.Operator {
leaderSolver := newBalanceSolver(h, cluster, utils.Write, transferLeader)
ops := leaderSolver.solve()
if len(ops) > 0 && leaderSolver.tryAddPendingInfluence() {
return ops
}
hotSchedulerSkipCounter.Inc()
return nil
}
type solution struct {
srcStore *statistics.StoreLoadDetail
region *core.RegionInfo // The region of the main balance effect. Relate mainPeerStat. srcStore -> dstStore
mainPeerStat *statistics.HotPeerStat
dstStore *statistics.StoreLoadDetail
revertRegion *core.RegionInfo // The regions to hedge back effects. Relate revertPeerStat. dstStore -> srcStore
revertPeerStat *statistics.HotPeerStat
cachedPeersRate []float64
// progressiveRank measures the contribution for balance.
// The smaller the rank, the better this solution is.
// If progressiveRank <= 0, this solution makes thing better.
// 0 indicates that this is a solution that cannot be used directly, but can be optimized.
// 1 indicates that this is a non-optimizable solution.
// See `calcProgressiveRank` for more about progressive rank.
progressiveRank int64
// only for rank v2
firstScore int
secondScore int
}
// getExtremeLoad returns the closest load in the selected src and dst statistics.
// in other word, the min load of the src store and the max load of the dst store.
// If peersRate is negative, the direction is reversed.
func (s *solution) getExtremeLoad(dim int) (src float64, dst float64) {
if s.getPeersRateFromCache(dim) >= 0 {
return s.srcStore.LoadPred.Min().Loads[dim], s.dstStore.LoadPred.Max().Loads[dim]
}
return s.srcStore.LoadPred.Max().Loads[dim], s.dstStore.LoadPred.Min().Loads[dim]
}
// getCurrentLoad returns the current load of the src store and the dst store.
func (s *solution) getCurrentLoad(dim int) (src float64, dst float64) {
return s.srcStore.LoadPred.Current.Loads[dim], s.dstStore.LoadPred.Current.Loads[dim]
}
// getPendingLoad returns the pending load of the src store and the dst store.
func (s *solution) getPendingLoad(dim int) (src float64, dst float64) {
return s.srcStore.LoadPred.Pending().Loads[dim], s.dstStore.LoadPred.Pending().Loads[dim]
}
// calcPeersRate precomputes the peer rate and stores it in cachedPeersRate.
func (s *solution) calcPeersRate(dims ...int) {
s.cachedPeersRate = make([]float64, utils.DimLen)
for _, dim := range dims {
peersRate := s.mainPeerStat.GetLoad(dim)
if s.revertPeerStat != nil {
peersRate -= s.revertPeerStat.GetLoad(dim)
}
s.cachedPeersRate[dim] = peersRate
}
}
// getPeersRateFromCache returns the load of the peer. Need to calcPeersRate first.
func (s *solution) getPeersRateFromCache(dim int) float64 {
return s.cachedPeersRate[dim]
}
// isAvailable returns the solution is available.
// The solution should have no revertRegion and progressiveRank < 0.
func isAvailableV1(s *solution) bool {
return s.progressiveRank < 0
}
type balanceSolver struct {
sche.SchedulerCluster
sche *hotScheduler
stLoadDetail map[uint64]*statistics.StoreLoadDetail
filteredHotPeers map[uint64][]*statistics.HotPeerStat // storeID -> hotPeers(filtered)
nthHotPeer map[uint64][]*statistics.HotPeerStat // storeID -> [dimLen]hotPeers
rwTy utils.RWType
opTy opType
resourceTy resourceType
cur *solution
best *solution
ops []*operator.Operator
maxSrc *statistics.StoreLoad
minDst *statistics.StoreLoad
rankStep *statistics.StoreLoad
// firstPriority and secondPriority indicate priority of hot schedule
// they may be byte(0), key(1), query(2), and always less than dimLen
firstPriority int
secondPriority int
greatDecRatio float64
minorDecRatio float64
maxPeerNum int
minHotDegree int
firstPriorityV2Ratios *rankV2Ratios
secondPriorityV2Ratios *rankV2Ratios
// The rank correlation function used according to the version
isAvailable func(*solution) bool
filterUniformStore func() (string, bool)
needSearchRevertRegions func() bool
setSearchRevertRegions func()
calcProgressiveRank func()
betterThan func(*solution) bool
rankToDimString func() string
checkByPriorityAndTolerance func(loads []float64, f func(int) bool) bool
checkHistoryLoadsByPriority func(loads [][]float64, f func(int) bool) bool
}
func (bs *balanceSolver) init() {
// Load the configuration items of the scheduler.
bs.resourceTy = toResourceType(bs.rwTy, bs.opTy)
bs.maxPeerNum = bs.sche.conf.GetMaxPeerNumber()
bs.minHotDegree = bs.GetSchedulerConfig().GetHotRegionCacheHitsThreshold()
bs.firstPriority, bs.secondPriority = prioritiesToDim(bs.getPriorities())
bs.greatDecRatio, bs.minorDecRatio = bs.sche.conf.GetGreatDecRatio(), bs.sche.conf.GetMinorDecRatio()
switch bs.sche.conf.GetRankFormulaVersion() {
case "v1":
bs.initRankV1()
default:
bs.initRankV2()
}
// Init store load detail according to the type.
bs.stLoadDetail = bs.sche.stLoadInfos[bs.resourceTy]
bs.maxSrc = &statistics.StoreLoad{Loads: make([]float64, utils.DimLen)}
bs.minDst = &statistics.StoreLoad{
Loads: make([]float64, utils.DimLen),
Count: math.MaxFloat64,
}
for i := range bs.minDst.Loads {
bs.minDst.Loads[i] = math.MaxFloat64
}
maxCur := &statistics.StoreLoad{Loads: make([]float64, utils.DimLen)}
bs.filteredHotPeers = make(map[uint64][]*statistics.HotPeerStat)
bs.nthHotPeer = make(map[uint64][]*statistics.HotPeerStat)
for _, detail := range bs.stLoadDetail {
bs.maxSrc = statistics.MaxLoad(bs.maxSrc, detail.LoadPred.Min())
bs.minDst = statistics.MinLoad(bs.minDst, detail.LoadPred.Max())
maxCur = statistics.MaxLoad(maxCur, &detail.LoadPred.Current)
bs.nthHotPeer[detail.GetID()] = make([]*statistics.HotPeerStat, utils.DimLen)
bs.filteredHotPeers[detail.GetID()] = bs.filterHotPeers(detail)
}
rankStepRatios := []float64{
utils.ByteDim: bs.sche.conf.GetByteRankStepRatio(),
utils.KeyDim: bs.sche.conf.GetKeyRankStepRatio(),
utils.QueryDim: bs.sche.conf.GetQueryRateRankStepRatio()}
stepLoads := make([]float64, utils.DimLen)
for i := range stepLoads {
stepLoads[i] = maxCur.Loads[i] * rankStepRatios[i]
}
bs.rankStep = &statistics.StoreLoad{
Loads: stepLoads,
Count: maxCur.Count * bs.sche.conf.GetCountRankStepRatio(),
}
}
func (bs *balanceSolver) initRankV1() {
bs.isAvailable = isAvailableV1
bs.filterUniformStore = bs.filterUniformStoreV1
bs.needSearchRevertRegions = func() bool { return false }
bs.setSearchRevertRegions = func() {}
bs.calcProgressiveRank = bs.calcProgressiveRankV1
bs.betterThan = bs.betterThanV1
bs.rankToDimString = bs.rankToDimStringV1
bs.pickCheckPolicyV1()
}
func (bs *balanceSolver) pickCheckPolicyV1() {
switch {
case bs.resourceTy == writeLeader:
bs.checkByPriorityAndTolerance = bs.checkByPriorityAndToleranceFirstOnly
bs.checkHistoryLoadsByPriority = bs.checkHistoryLoadsByPriorityAndToleranceFirstOnly
case bs.sche.conf.IsStrictPickingStoreEnabled():
bs.checkByPriorityAndTolerance = bs.checkByPriorityAndToleranceAllOf
bs.checkHistoryLoadsByPriority = bs.checkHistoryLoadsByPriorityAndToleranceAllOf
default:
bs.checkByPriorityAndTolerance = bs.checkByPriorityAndToleranceFirstOnly
bs.checkHistoryLoadsByPriority = bs.checkHistoryLoadsByPriorityAndToleranceFirstOnly
}
}
func (bs *balanceSolver) isSelectedDim(dim int) bool {
return dim == bs.firstPriority || dim == bs.secondPriority
}
func (bs *balanceSolver) getPriorities() []string {
querySupport := bs.sche.conf.checkQuerySupport(bs.SchedulerCluster)
// For read, transfer-leader and move-peer have the same priority config
// For write, they are different
switch bs.resourceTy {
case readLeader, readPeer:
return adjustPrioritiesConfig(querySupport, bs.sche.conf.GetReadPriorities(), getReadPriorities)
case writeLeader:
return adjustPrioritiesConfig(querySupport, bs.sche.conf.GetWriteLeaderPriorities(), getWriteLeaderPriorities)
case writePeer:
return adjustPrioritiesConfig(querySupport, bs.sche.conf.GetWritePeerPriorities(), getWritePeerPriorities)
}
log.Error("illegal type or illegal operator while getting the priority", zap.String("type", bs.rwTy.String()), zap.String("operator", bs.opTy.String()))
return []string{}
}
func newBalanceSolver(sche *hotScheduler, cluster sche.SchedulerCluster, rwTy utils.RWType, opTy opType) *balanceSolver {
bs := &balanceSolver{
SchedulerCluster: cluster,
sche: sche,
rwTy: rwTy,
opTy: opTy,
}
bs.init()
return bs
}
func (bs *balanceSolver) isValid() bool {
if bs.SchedulerCluster == nil || bs.sche == nil || bs.stLoadDetail == nil {
return false
}
return true
}
func (bs *balanceSolver) filterUniformStoreV1() (string, bool) {
if !bs.enableExpectation() {
return "", false
}
// Because region is available for src and dst, so stddev is the same for both, only need to calculate one.
isUniformFirstPriority, isUniformSecondPriority := bs.isUniformFirstPriority(bs.cur.srcStore), bs.isUniformSecondPriority(bs.cur.srcStore)
if isUniformFirstPriority && isUniformSecondPriority {
// If both dims are enough uniform, any schedule is unnecessary.
return "all-dim", true
}
if isUniformFirstPriority && (bs.cur.progressiveRank == -1 || bs.cur.progressiveRank == -3) {
// If first priority dim is enough uniform, -1 is unnecessary and maybe lead to worse balance for second priority dim
return dimToString(bs.firstPriority), true
}
if isUniformSecondPriority && bs.cur.progressiveRank == -2 {
// If second priority dim is enough uniform, -2 is unnecessary and maybe lead to worse balance for first priority dim
return dimToString(bs.secondPriority), true
}
return "", false
}
// solve travels all the src stores, hot peers, dst stores and select each one of them to make a best scheduling solution.
// The comparing between solutions is based on calcProgressiveRank.
func (bs *balanceSolver) solve() []*operator.Operator {
if !bs.isValid() {
return nil
}
bs.cur = &solution{}
tryUpdateBestSolution := func() {
if label, ok := bs.filterUniformStore(); ok {
bs.skipCounter(label).Inc()
return
}
if bs.isAvailable(bs.cur) && bs.betterThan(bs.best) {
if newOps := bs.buildOperators(); len(newOps) > 0 {
bs.ops = newOps
clone := *bs.cur
bs.best = &clone
}
}
}
// Whether to allow move region peer from dstStore to srcStore
var allowRevertRegion func(region *core.RegionInfo, srcStoreID uint64) bool
if bs.opTy == transferLeader {
allowRevertRegion = func(region *core.RegionInfo, srcStoreID uint64) bool {
return region.GetStorePeer(srcStoreID) != nil
}
} else {
allowRevertRegion = func(region *core.RegionInfo, srcStoreID uint64) bool {
return region.GetStorePeer(srcStoreID) == nil
}
}
snapshotFilter := filter.NewSnapshotSendFilter(bs.GetStores(), constant.Medium)
splitThresholds := bs.sche.conf.getSplitThresholds()
for _, srcStore := range bs.filterSrcStores() {
bs.cur.srcStore = srcStore
srcStoreID := srcStore.GetID()
for _, mainPeerStat := range bs.filteredHotPeers[srcStoreID] {
if bs.cur.region = bs.getRegion(mainPeerStat, srcStoreID); bs.cur.region == nil {
continue
} else if bs.opTy == movePeer {
if !snapshotFilter.Select(bs.cur.region).IsOK() {
hotSchedulerSnapshotSenderLimitCounter.Inc()
continue
}
}
bs.cur.mainPeerStat = mainPeerStat
if bs.GetStoreConfig().IsEnableRegionBucket() && bs.tooHotNeedSplit(srcStore, mainPeerStat, splitThresholds) {
hotSchedulerRegionTooHotNeedSplitCounter.Inc()
ops := bs.createSplitOperator([]*core.RegionInfo{bs.cur.region}, byLoad)
if len(ops) > 0 {
bs.ops = ops
bs.cur.calcPeersRate(bs.firstPriority, bs.secondPriority)
bs.best = bs.cur
return ops
}
}
for _, dstStore := range bs.filterDstStores() {
bs.cur.dstStore = dstStore
bs.calcProgressiveRank()
tryUpdateBestSolution()
if bs.needSearchRevertRegions() {
hotSchedulerSearchRevertRegionsCounter.Inc()
dstStoreID := dstStore.GetID()
for _, revertPeerStat := range bs.filteredHotPeers[dstStoreID] {
revertRegion := bs.getRegion(revertPeerStat, dstStoreID)
if revertRegion == nil || revertRegion.GetID() == bs.cur.region.GetID() ||
!allowRevertRegion(revertRegion, srcStoreID) {
continue
}
bs.cur.revertPeerStat = revertPeerStat
bs.cur.revertRegion = revertRegion
bs.calcProgressiveRank()
tryUpdateBestSolution()
}
bs.cur.revertPeerStat = nil
bs.cur.revertRegion = nil
}
}
}
}
bs.setSearchRevertRegions()
return bs.ops
}
func (bs *balanceSolver) skipCounter(label string) prometheus.Counter {
if bs.rwTy == utils.Read {
switch label {
case "byte":
return readSkipByteDimUniformStoreCounter
case "key":
return readSkipKeyDimUniformStoreCounter
case "query":
return readSkipQueryDimUniformStoreCounter
default:
return readSkipAllDimUniformStoreCounter
}
}
switch label {
case "byte":
return writeSkipByteDimUniformStoreCounter
case "key":
return writeSkipKeyDimUniformStoreCounter
case "query":
return writeSkipQueryDimUniformStoreCounter
default:
return writeSkipAllDimUniformStoreCounter
}
}
func (bs *balanceSolver) tryAddPendingInfluence() bool {
if bs.best == nil || len(bs.ops) == 0 {
return false
}
isSplit := bs.ops[0].Kind() == operator.OpSplit
if !isSplit && bs.best.srcStore.IsTiFlash() != bs.best.dstStore.IsTiFlash() {
hotSchedulerNotSameEngineCounter.Inc()
return false
}
maxZombieDur := bs.calcMaxZombieDur()
// TODO: Process operators atomically.
// main peer
srcStoreIDs := make([]uint64, 0)
dstStoreID := uint64(0)
if isSplit {
region := bs.GetRegion(bs.ops[0].RegionID())
if region == nil {
return false
}
for id := range region.GetStoreIDs() {
srcStoreIDs = append(srcStoreIDs, id)
}
} else {
srcStoreIDs = append(srcStoreIDs, bs.best.srcStore.GetID())
dstStoreID = bs.best.dstStore.GetID()
}
infl := bs.collectPendingInfluence(bs.best.mainPeerStat)
if !bs.sche.tryAddPendingInfluence(bs.ops[0], srcStoreIDs, dstStoreID, infl, maxZombieDur) {
return false
}
if isSplit {
return true
}
// revert peers
if bs.best.revertPeerStat != nil && len(bs.ops) > 1 {
infl := bs.collectPendingInfluence(bs.best.revertPeerStat)
if !bs.sche.tryAddPendingInfluence(bs.ops[1], srcStoreIDs, dstStoreID, infl, maxZombieDur) {
return false
}
}
bs.logBestSolution()
return true
}
func (bs *balanceSolver) collectPendingInfluence(peer *statistics.HotPeerStat) statistics.Influence {
infl := statistics.Influence{Loads: make([]float64, utils.RegionStatCount), Count: 1}
bs.rwTy.SetFullLoadRates(infl.Loads, peer.GetLoads())
inverse := bs.rwTy.Inverse()
another := bs.GetHotPeerStat(inverse, peer.RegionID, peer.StoreID)
if another != nil {
inverse.SetFullLoadRates(infl.Loads, another.GetLoads())
}
return infl
}
// Depending on the source of the statistics used, a different ZombieDuration will be used.
// If the statistics are from the sum of Regions, there will be a longer ZombieDuration.
func (bs *balanceSolver) calcMaxZombieDur() time.Duration {
switch bs.resourceTy {
case writeLeader:
if bs.firstPriority == utils.QueryDim {
// We use store query info rather than total of hot write leader to guide hot write leader scheduler
// when its first priority is `QueryDim`, because `Write-peer` does not have `QueryDim`.
// The reason is the same with `tikvCollector.GetLoads`.
return bs.sche.conf.GetStoreStatZombieDuration()
}
return bs.sche.conf.GetRegionsStatZombieDuration()
case writePeer:
if bs.best.srcStore.IsTiFlash() {
return bs.sche.conf.GetRegionsStatZombieDuration()
}
return bs.sche.conf.GetStoreStatZombieDuration()
default:
return bs.sche.conf.GetStoreStatZombieDuration()
}
}
// filterSrcStores compare the min rate and the ratio * expectation rate, if two dim rate is greater than
// its expectation * ratio, the store would be selected as hot source store
func (bs *balanceSolver) filterSrcStores() map[uint64]*statistics.StoreLoadDetail {
ret := make(map[uint64]*statistics.StoreLoadDetail)
confSrcToleranceRatio := bs.sche.conf.GetSrcToleranceRatio()
confEnableForTiFlash := bs.sche.conf.GetEnableForTiFlash()
for id, detail := range bs.stLoadDetail {
srcToleranceRatio := confSrcToleranceRatio
if detail.IsTiFlash() {
if !confEnableForTiFlash {
continue
}
if bs.rwTy != utils.Write || bs.opTy != movePeer {
continue
}
srcToleranceRatio += tiflashToleranceRatioCorrection
}
if len(detail.HotPeers) == 0 {
continue
}
if !bs.checkSrcByPriorityAndTolerance(detail.LoadPred.Min(), &detail.LoadPred.Expect, srcToleranceRatio) {
hotSchedulerResultCounter.WithLabelValues("src-store-failed-"+bs.resourceTy.String(), strconv.FormatUint(id, 10)).Inc()
continue
}
if !bs.checkSrcHistoryLoadsByPriorityAndTolerance(&detail.LoadPred.Current, &detail.LoadPred.Expect, srcToleranceRatio) {
hotSchedulerResultCounter.WithLabelValues("src-store-history-loads-failed-"+bs.resourceTy.String(), strconv.FormatUint(id, 10)).Inc()
continue
}
ret[id] = detail
hotSchedulerResultCounter.WithLabelValues("src-store-succ-"+bs.resourceTy.String(), strconv.FormatUint(id, 10)).Inc()
}
return ret
}
func (bs *balanceSolver) checkSrcByPriorityAndTolerance(minLoad, expectLoad *statistics.StoreLoad, toleranceRatio float64) bool {
return bs.checkByPriorityAndTolerance(minLoad.Loads, func(i int) bool {
return minLoad.Loads[i] > toleranceRatio*expectLoad.Loads[i]
})
}
func (bs *balanceSolver) checkSrcHistoryLoadsByPriorityAndTolerance(current, expectLoad *statistics.StoreLoad, toleranceRatio float64) bool {
if len(current.HistoryLoads) == 0 {
return true
}
return bs.checkHistoryLoadsByPriority(current.HistoryLoads, func(i int) bool {
return slice.AllOf(current.HistoryLoads[i], func(j int) bool {
return current.HistoryLoads[i][j] > toleranceRatio*expectLoad.HistoryLoads[i][j]
})
})
}
// filterHotPeers filtered hot peers from statistics.HotPeerStat and deleted the peer if its region is in pending status.
// The returned hotPeer count in controlled by `max-peer-number`.
func (bs *balanceSolver) filterHotPeers(storeLoad *statistics.StoreLoadDetail) []*statistics.HotPeerStat {
hotPeers := storeLoad.HotPeers
ret := make([]*statistics.HotPeerStat, 0, len(hotPeers))
appendItem := func(item *statistics.HotPeerStat) {
if _, ok := bs.sche.regionPendings[item.ID()]; !ok && !item.IsNeedCoolDownTransferLeader(bs.minHotDegree, bs.rwTy) {
// no in pending operator and no need cool down after transfer leader
ret = append(ret, item)
}
}
var firstSort, secondSort []*statistics.HotPeerStat
if len(hotPeers) >= topnPosition || len(hotPeers) > bs.maxPeerNum {
firstSort = make([]*statistics.HotPeerStat, len(hotPeers))
copy(firstSort, hotPeers)
sort.Slice(firstSort, func(i, j int) bool {
return firstSort[i].GetLoad(bs.firstPriority) > firstSort[j].GetLoad(bs.firstPriority)
})
secondSort = make([]*statistics.HotPeerStat, len(hotPeers))
copy(secondSort, hotPeers)
sort.Slice(secondSort, func(i, j int) bool {
return secondSort[i].GetLoad(bs.secondPriority) > secondSort[j].GetLoad(bs.secondPriority)
})
}
if len(hotPeers) >= topnPosition {
storeID := storeLoad.GetID()
bs.nthHotPeer[storeID][bs.firstPriority] = firstSort[topnPosition-1]
bs.nthHotPeer[storeID][bs.secondPriority] = secondSort[topnPosition-1]
}
if len(hotPeers) > bs.maxPeerNum {
union := bs.sortHotPeers(firstSort, secondSort)
ret = make([]*statistics.HotPeerStat, 0, len(union))
for peer := range union {
appendItem(peer)
}
return ret
}
for _, peer := range hotPeers {
appendItem(peer)
}
return ret
}
func (bs *balanceSolver) sortHotPeers(firstSort, secondSort []*statistics.HotPeerStat) map[*statistics.HotPeerStat]struct{} {
union := make(map[*statistics.HotPeerStat]struct{}, bs.maxPeerNum)
// At most MaxPeerNum peers, to prevent balanceSolver.solve() too slow.
for len(union) < bs.maxPeerNum {
for len(firstSort) > 0 {
peer := firstSort[0]
firstSort = firstSort[1:]
if _, ok := union[peer]; !ok {
union[peer] = struct{}{}
break
}
}
for len(union) < bs.maxPeerNum && len(secondSort) > 0 {
peer := secondSort[0]
secondSort = secondSort[1:]
if _, ok := union[peer]; !ok {
union[peer] = struct{}{}
break
}
}
}
return union
}
// isRegionAvailable checks whether the given region is not available to schedule.
func (bs *balanceSolver) isRegionAvailable(region *core.RegionInfo) bool {