2023-03-23 15:58:12 +08:00
|
|
|
|
package balance
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"hpds_control_center/model"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// WeightRoundRobinBalance 加权轮询负载
|
|
|
|
|
type WeightRoundRobinBalance struct {
|
|
|
|
|
curIndex int
|
|
|
|
|
rss []*WeightNode
|
2023-04-24 15:14:04 +08:00
|
|
|
|
rsw []*model.NodeLastStateItem
|
2023-03-23 15:58:12 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type WeightNode struct {
|
2023-04-24 15:14:04 +08:00
|
|
|
|
node *model.NodeLastStateItem
|
2023-03-23 15:58:12 +08:00
|
|
|
|
Weight int //初始化时对节点约定的权重
|
|
|
|
|
currentWeight int //节点临时权重,每轮都会变化
|
|
|
|
|
effectiveWeight int //有效权重, 默认与weight相同 , totalWeight = sum(effectiveWeight) //出现故障就-1
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//1, currentWeight = currentWeight + effectiveWeight
|
|
|
|
|
//2, 选中最大的currentWeight节点为选中节点
|
|
|
|
|
//3, currentWeight = currentWeight - totalWeight
|
|
|
|
|
|
|
|
|
|
func (r *WeightRoundRobinBalance) Add(params model.NodeLastStateItem) error {
|
|
|
|
|
weightCpu := params.CpuUsed
|
|
|
|
|
weightMem := float64(params.MemUsed*100) / float64(params.MemUsed)
|
|
|
|
|
weightSwap := float64(params.SwapTotal*100) / float64(params.SwapTotal)
|
|
|
|
|
weightTask := 0.0
|
|
|
|
|
if len(params.ExecTask) > 0 {
|
|
|
|
|
weightTask = 0
|
|
|
|
|
} else {
|
|
|
|
|
weightTask = 100
|
|
|
|
|
}
|
|
|
|
|
node := &WeightNode{
|
2023-04-24 15:14:04 +08:00
|
|
|
|
node: ¶ms,
|
2023-03-23 15:58:12 +08:00
|
|
|
|
Weight: int(400 - weightCpu - weightMem - weightSwap - weightTask),
|
|
|
|
|
}
|
|
|
|
|
node.effectiveWeight = node.Weight
|
|
|
|
|
r.rss = append(r.rss, node)
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2023-04-24 15:14:04 +08:00
|
|
|
|
func (r *WeightRoundRobinBalance) Next() *model.NodeLastStateItem {
|
2023-03-23 15:58:12 +08:00
|
|
|
|
var best *WeightNode
|
|
|
|
|
total := 0
|
|
|
|
|
for i := 0; i < len(r.rss); i++ {
|
|
|
|
|
w := r.rss[i]
|
|
|
|
|
//1 计算所有有效权重
|
|
|
|
|
total += w.effectiveWeight
|
|
|
|
|
//2 修改当前节点临时权重
|
|
|
|
|
w.currentWeight += w.effectiveWeight
|
|
|
|
|
//3 有效权重默认与权重相同,通讯异常时-1, 通讯成功+1,直到恢复到weight大小
|
|
|
|
|
if w.effectiveWeight < w.Weight {
|
|
|
|
|
w.effectiveWeight++
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//4 选中最大临时权重节点
|
|
|
|
|
if best == nil || w.currentWeight > best.currentWeight {
|
|
|
|
|
best = w
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if best == nil {
|
2023-04-24 15:14:04 +08:00
|
|
|
|
return nil
|
2023-03-23 15:58:12 +08:00
|
|
|
|
}
|
|
|
|
|
//5 变更临时权重为 临时权重-有效权重之和
|
|
|
|
|
best.currentWeight -= total
|
2023-04-24 15:14:04 +08:00
|
|
|
|
return best.node
|
2023-03-23 15:58:12 +08:00
|
|
|
|
}
|
|
|
|
|
|
2023-04-24 15:14:04 +08:00
|
|
|
|
func (r *WeightRoundRobinBalance) Get(int64) (*model.NodeLastStateItem, error) {
|
2023-03-23 15:58:12 +08:00
|
|
|
|
return r.Next(), nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (r *WeightRoundRobinBalance) Update() {
|
|
|
|
|
|
|
|
|
|
}
|