/
balancer.go
64 lines (56 loc) · 1.94 KB
/
balancer.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
// 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 server
import (
"math"
"github.com/montanaflynn/stats"
"github.com/pingcap/pd/server/core"
)
// TODO: remove this file.
const (
bootstrapBalanceCount = 10
bootstrapBalanceDiff = 2
)
// minBalanceDiff returns the minimal diff to do balance. The formula is based
// on experience to let the diff increase alone with the count slowly.
func minBalanceDiff(count uint64) float64 {
if count < bootstrapBalanceCount {
return bootstrapBalanceDiff
}
return math.Sqrt(float64(count))
}
// shouldBalance returns true if we should balance the source and target store.
// The min balance diff provides a buffer to make the cluster stable, so that we
// don't need to schedule very frequently.
func shouldBalance(source, target *core.StoreInfo, kind core.ResourceKind) bool {
sourceCount := source.ResourceCount(kind)
sourceScore := source.ResourceScore(kind)
targetScore := target.ResourceScore(kind)
if targetScore >= sourceScore {
return false
}
diffRatio := 1 - targetScore/sourceScore
diffCount := diffRatio * float64(sourceCount)
return diffCount >= minBalanceDiff(sourceCount)
}
func adjustBalanceLimit(cluster *clusterInfo, kind core.ResourceKind) uint64 {
stores := cluster.GetStores()
counts := make([]float64, 0, len(stores))
for _, s := range stores {
if s.IsUp() {
counts = append(counts, float64(s.ResourceCount(kind)))
}
}
limit, _ := stats.StandardDeviation(stats.Float64Data(counts))
return maxUint64(1, uint64(limit))
}