Merge pull request 'static weight algorithm' (#15) from JoYang/pcm-coordinator:master into master
Former-commit-id: 40d527663f2d944da898002620d6b8183fe206d7
This commit is contained in:
commit
6949d513df
|
@ -11,3 +11,9 @@ type Participant struct {
|
|||
Name string
|
||||
Participant_id int64
|
||||
}
|
||||
|
||||
type WeightP struct {
|
||||
Participant_id int64
|
||||
Weight int32
|
||||
Name string
|
||||
}
|
||||
|
|
|
@ -1,10 +1,69 @@
|
|||
package strategy
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"gitlink.org.cn/jcce-pcm/pcm-coordinator/api/internal/scheduler/entity"
|
||||
)
|
||||
|
||||
type StaticWeightStrategy struct {
|
||||
// TODO: add fields
|
||||
|
||||
//每个
|
||||
num int32
|
||||
weights []entity.WeightP
|
||||
}
|
||||
|
||||
func (ps *StaticWeightStrategy) Schedule() ([]*AssignedCluster, error) {
|
||||
// TODO: implement the scheduling logic return nil, nil
|
||||
return nil, nil
|
||||
|
||||
if ps.num < 1 {
|
||||
return nil, errors.New("numbers must be greater than 0")
|
||||
}
|
||||
|
||||
if ps.weights == nil {
|
||||
return nil, errors.New("weight must be set")
|
||||
}
|
||||
|
||||
var weightSum int32
|
||||
weightSum = 0
|
||||
for _, w := range ps.weights {
|
||||
weightSum += w.Weight
|
||||
}
|
||||
|
||||
weightRatio := make([]float64, len(ps.weights))
|
||||
for i, w := range ps.weights {
|
||||
weightRatio[i] = float64(w.Weight) / float64(weightSum)
|
||||
}
|
||||
|
||||
var rest = ps.num
|
||||
var results []*AssignedCluster
|
||||
|
||||
for i := 0; i < len(ps.weights); i++ {
|
||||
|
||||
var n = int(float64(ps.num) * weightRatio[i])
|
||||
rest -= int32(n)
|
||||
|
||||
cluster := &AssignedCluster{ParticipantId: ps.weights[i].Participant_id, Name: ps.weights[i].Name, Replicas: int32(n)}
|
||||
results = append(results, cluster)
|
||||
}
|
||||
|
||||
if rest != 0 {
|
||||
if rest < 0 { // 如果差值小于0,需要增加某些元素的值
|
||||
for i := len(ps.weights) - 1; rest < 0 && i >= 0; i-- {
|
||||
if results[i].Replicas < ps.weights[i].Weight {
|
||||
results[i].Replicas++
|
||||
rest++
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for i := len(ps.weights) - 1; rest > 0 && i >= 0; i-- {
|
||||
if results[i].Replicas < ps.weights[i].Weight {
|
||||
results[i].Replicas--
|
||||
rest--
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return results, nil
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue