/
hot_region.go
385 lines (337 loc) · 11.4 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
// Copyright 2017 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 schedulers
import (
"math"
"math/rand"
"sync"
"time"
log "github.com/Sirupsen/logrus"
"github.com/pingcap/kvproto/pkg/metapb"
"github.com/pingcap/pd/server/core"
"github.com/pingcap/pd/server/schedule"
)
func init() {
schedule.RegisterScheduler("hotRegion", func(opt schedule.Options, args []string) (schedule.Scheduler, error) {
return newBalanceHotRegionScheduler(opt), nil
})
}
const (
hotRegionLimitFactor = 0.75
storeHotRegionsDefaultLen = 100
hotRegionScheduleFactor = 0.9
)
// BalanceType : the perspective of balance
type BalanceType int
const (
byPeer BalanceType = iota
byLeader
)
type balanceHotRegionScheduler struct {
sync.RWMutex
opt schedule.Options
limit uint64
// store id -> hot regions statistics as the role of replica
statisticsAsPeer map[uint64]*core.HotRegionsStat
// store id -> hot regions statistics as the role of leader
statisticsAsLeader map[uint64]*core.HotRegionsStat
r *rand.Rand
}
// newBalanceHotRegionScheduler creates a scheduler that keeps hot regions on
// each stores balanced.
func newBalanceHotRegionScheduler(opt schedule.Options) schedule.Scheduler {
return &balanceHotRegionScheduler{
opt: opt,
limit: 1,
statisticsAsPeer: make(map[uint64]*core.HotRegionsStat),
statisticsAsLeader: make(map[uint64]*core.HotRegionsStat),
r: rand.New(rand.NewSource(time.Now().UnixNano())),
}
}
func (h *balanceHotRegionScheduler) GetName() string {
return "balance-hot-region-scheduler"
}
func (h *balanceHotRegionScheduler) GetResourceKind() core.ResourceKind {
return core.PriorityKind
}
func (h *balanceHotRegionScheduler) GetResourceLimit() uint64 {
return h.limit
}
func (h *balanceHotRegionScheduler) Prepare(cluster schedule.Cluster) error { return nil }
func (h *balanceHotRegionScheduler) Cleanup(cluster schedule.Cluster) {}
func (h *balanceHotRegionScheduler) Schedule(cluster schedule.Cluster) *schedule.Operator {
schedulerCounter.WithLabelValues(h.GetName(), "schedule").Inc()
h.calcScore(cluster)
// balance by peer
srcRegion, srcPeer, destPeer := h.balanceByPeer(cluster)
if srcRegion != nil {
schedulerCounter.WithLabelValues(h.GetName(), "move_peer").Inc()
return schedule.CreateMovePeerOperator("moveHotRegion", srcRegion, core.PriorityKind, srcPeer.GetStoreId(), destPeer.GetStoreId(), destPeer.GetId())
}
// balance by leader
srcRegion, newLeader := h.balanceByLeader(cluster)
if srcRegion != nil {
schedulerCounter.WithLabelValues(h.GetName(), "move_leader").Inc()
step := schedule.TransferLeader{FromStore: srcRegion.Leader.GetStoreId(), ToStore: newLeader.GetStoreId()}
return schedule.NewOperator("transferHotLeader", srcRegion.GetId(), core.PriorityKind, step)
}
schedulerCounter.WithLabelValues(h.GetName(), "skip").Inc()
return nil
}
func (h *balanceHotRegionScheduler) calcScore(cluster schedule.Cluster) {
h.Lock()
defer h.Unlock()
h.statisticsAsPeer = make(map[uint64]*core.HotRegionsStat)
h.statisticsAsLeader = make(map[uint64]*core.HotRegionsStat)
items := cluster.RegionWriteStats()
for _, r := range items {
if r.HotDegree < h.opt.GetHotRegionLowThreshold() {
continue
}
regionInfo := cluster.GetRegion(r.RegionID)
leaderStoreID := regionInfo.Leader.GetStoreId()
storeIDs := regionInfo.GetStoreIds()
for storeID := range storeIDs {
peerStat, ok := h.statisticsAsPeer[storeID]
if !ok {
peerStat = &core.HotRegionsStat{
RegionsStat: make(core.RegionsStat, 0, storeHotRegionsDefaultLen),
}
h.statisticsAsPeer[storeID] = peerStat
}
leaderStat, ok := h.statisticsAsLeader[storeID]
if !ok {
leaderStat = &core.HotRegionsStat{
RegionsStat: make(core.RegionsStat, 0, storeHotRegionsDefaultLen),
}
h.statisticsAsLeader[storeID] = leaderStat
}
stat := core.RegionStat{
RegionID: r.RegionID,
WrittenBytes: r.WrittenBytes,
HotDegree: r.HotDegree,
LastUpdateTime: r.LastUpdateTime,
StoreID: storeID,
AntiCount: r.AntiCount,
Version: r.Version,
}
peerStat.WrittenBytes += r.WrittenBytes
peerStat.RegionsCount++
peerStat.RegionsStat = append(peerStat.RegionsStat, stat)
if storeID == leaderStoreID {
leaderStat.WrittenBytes += r.WrittenBytes
leaderStat.RegionsCount++
leaderStat.RegionsStat = append(leaderStat.RegionsStat, stat)
}
}
}
}
func (h *balanceHotRegionScheduler) balanceByPeer(cluster schedule.Cluster) (*core.RegionInfo, *metapb.Peer, *metapb.Peer) {
var (
maxWrittenBytes uint64
srcStoreID uint64
maxHotStoreRegionCount int
)
// get the srcStoreId
for storeID, statistics := range h.statisticsAsPeer {
count, writtenBytes := statistics.RegionsStat.Len(), statistics.WrittenBytes
if count >= 2 && (count > maxHotStoreRegionCount || (count == maxHotStoreRegionCount && writtenBytes > maxWrittenBytes)) {
maxHotStoreRegionCount = count
maxWrittenBytes = writtenBytes
srcStoreID = storeID
}
}
if srcStoreID == 0 {
return nil, nil, nil
}
stores := cluster.GetStores()
var destStoreID uint64
for _, i := range h.r.Perm(h.statisticsAsPeer[srcStoreID].RegionsStat.Len()) {
rs := h.statisticsAsPeer[srcStoreID].RegionsStat[i]
srcRegion := cluster.GetRegion(rs.RegionID)
if len(srcRegion.DownPeers) != 0 || len(srcRegion.PendingPeers) != 0 {
continue
}
filters := []schedule.Filter{
schedule.NewExcludedFilter(srcRegion.GetStoreIds(), srcRegion.GetStoreIds()),
schedule.NewDistinctScoreFilter(h.opt.GetLocationLabels(), stores, cluster.GetLeaderStore(srcRegion)),
schedule.NewStateFilter(h.opt),
schedule.NewStorageThresholdFilter(h.opt),
}
destStoreIDs := make([]uint64, 0, len(stores))
for _, store := range stores {
if schedule.FilterTarget(store, filters) {
continue
}
destStoreIDs = append(destStoreIDs, store.GetId())
}
destStoreID = h.selectDestStoreByPeer(destStoreIDs, srcRegion, srcStoreID)
if destStoreID != 0 {
srcRegion.WrittenBytes = rs.WrittenBytes
h.adjustBalanceLimit(srcStoreID, byPeer)
var srcPeer *metapb.Peer
for _, peer := range srcRegion.GetPeers() {
if peer.GetStoreId() == srcStoreID {
srcPeer = peer
break
}
}
if srcPeer == nil {
return nil, nil, nil
}
destPeer, err := cluster.AllocPeer(destStoreID)
if err != nil {
log.Errorf("failed to allocate peer: %v", err)
return nil, nil, nil
}
return srcRegion, srcPeer, destPeer
}
}
return nil, nil, nil
}
func (h *balanceHotRegionScheduler) selectDestStoreByPeer(candidateStoreIDs []uint64, srcRegion *core.RegionInfo, srcStoreID uint64) uint64 {
sr := h.statisticsAsPeer[srcStoreID]
srcWrittenBytes := sr.WrittenBytes
srcHotRegionsCount := sr.RegionsStat.Len()
var (
destStoreID uint64
minWrittenBytes uint64 = math.MaxUint64
)
minRegionsCount := int(math.MaxInt32)
for _, storeID := range candidateStoreIDs {
if s, ok := h.statisticsAsPeer[storeID]; ok {
if srcHotRegionsCount-s.RegionsStat.Len() > 1 && minRegionsCount > s.RegionsStat.Len() {
destStoreID = storeID
minWrittenBytes = s.WrittenBytes
minRegionsCount = s.RegionsStat.Len()
continue
}
if minRegionsCount == s.RegionsStat.Len() && minWrittenBytes > s.WrittenBytes &&
uint64(float64(srcWrittenBytes)*hotRegionScheduleFactor) > s.WrittenBytes+2*srcRegion.WrittenBytes {
minWrittenBytes = s.WrittenBytes
destStoreID = storeID
}
} else {
destStoreID = storeID
break
}
}
return destStoreID
}
func (h *balanceHotRegionScheduler) adjustBalanceLimit(storeID uint64, t BalanceType) {
var srcStatistics *core.HotRegionsStat
var allStatistics map[uint64]*core.HotRegionsStat
switch t {
case byPeer:
srcStatistics = h.statisticsAsPeer[storeID]
allStatistics = h.statisticsAsPeer
case byLeader:
srcStatistics = h.statisticsAsLeader[storeID]
allStatistics = h.statisticsAsLeader
}
var hotRegionTotalCount float64
for _, m := range allStatistics {
hotRegionTotalCount += float64(m.RegionsStat.Len())
}
avgRegionCount := hotRegionTotalCount / float64(len(allStatistics))
// Multiplied by hotRegionLimitFactor to avoid transfer back and forth
limit := uint64((float64(srcStatistics.RegionsStat.Len()) - avgRegionCount) * hotRegionLimitFactor)
h.limit = maxUint64(1, limit)
}
func (h *balanceHotRegionScheduler) balanceByLeader(cluster schedule.Cluster) (*core.RegionInfo, *metapb.Peer) {
var (
maxWrittenBytes uint64
srcStoreID uint64
maxHotStoreRegionCount int
)
// select srcStoreId by leader
for storeID, statistics := range h.statisticsAsLeader {
if statistics.RegionsStat.Len() < 2 {
continue
}
if maxHotStoreRegionCount < statistics.RegionsStat.Len() {
maxHotStoreRegionCount = statistics.RegionsStat.Len()
maxWrittenBytes = statistics.WrittenBytes
srcStoreID = storeID
continue
}
if maxHotStoreRegionCount == statistics.RegionsStat.Len() && maxWrittenBytes < statistics.WrittenBytes {
maxWrittenBytes = statistics.WrittenBytes
srcStoreID = storeID
}
}
if srcStoreID == 0 {
return nil, nil
}
// select destPeer
for _, i := range h.r.Perm(h.statisticsAsLeader[srcStoreID].RegionsStat.Len()) {
rs := h.statisticsAsLeader[srcStoreID].RegionsStat[i]
srcRegion := cluster.GetRegion(rs.RegionID)
if len(srcRegion.DownPeers) != 0 || len(srcRegion.PendingPeers) != 0 {
continue
}
destPeer := h.selectDestStoreByLeader(srcRegion)
if destPeer != nil {
h.adjustBalanceLimit(srcStoreID, byLeader)
return srcRegion, destPeer
}
}
return nil, nil
}
func (h *balanceHotRegionScheduler) selectDestStoreByLeader(srcRegion *core.RegionInfo) *metapb.Peer {
sr := h.statisticsAsLeader[srcRegion.Leader.GetStoreId()]
srcWrittenBytes := sr.WrittenBytes
srcHotRegionsCount := sr.RegionsStat.Len()
var (
destPeer *metapb.Peer
minWrittenBytes uint64 = math.MaxUint64
)
minRegionsCount := int(math.MaxInt32)
for storeID, peer := range srcRegion.GetFollowers() {
if s, ok := h.statisticsAsLeader[storeID]; ok {
if srcHotRegionsCount-s.RegionsStat.Len() > 1 && minRegionsCount > s.RegionsStat.Len() {
destPeer = peer
minWrittenBytes = s.WrittenBytes
minRegionsCount = s.RegionsStat.Len()
continue
}
if minRegionsCount == s.RegionsStat.Len() && minWrittenBytes > s.WrittenBytes &&
uint64(float64(srcWrittenBytes)*hotRegionScheduleFactor) > s.WrittenBytes+2*srcRegion.WrittenBytes {
minWrittenBytes = s.WrittenBytes
destPeer = peer
}
} else {
destPeer = peer
break
}
}
return destPeer
}
func (h *balanceHotRegionScheduler) GetStatus() *core.StoreHotRegionInfos {
h.RLock()
defer h.RUnlock()
asPeer := make(map[uint64]*core.HotRegionsStat, len(h.statisticsAsPeer))
for id, stat := range h.statisticsAsPeer {
clone := *stat
asPeer[id] = &clone
}
asLeader := make(map[uint64]*core.HotRegionsStat, len(h.statisticsAsLeader))
for id, stat := range h.statisticsAsLeader {
clone := *stat
asLeader[id] = &clone
}
return &core.StoreHotRegionInfos{
AsPeer: asPeer,
AsLeader: asLeader,
}
}