From 4cf1e23cf96aca1b53c6d471f2b7c1a20e4929f7 Mon Sep 17 00:00:00 2001 From: Jo Yang Date: Mon, 29 Jan 2024 08:54:43 +0800 Subject: [PATCH] static weight algorithm Former-commit-id: 2c1e37f6fb9226e9069ee1e1d4ec77c3cf91c11c --- api/internal/scheduler/entity/entity.go | 6 ++ .../scheduler/strategy/staticWeight.go | 61 ++++++++++++++++++- 2 files changed, 66 insertions(+), 1 deletion(-) diff --git a/api/internal/scheduler/entity/entity.go b/api/internal/scheduler/entity/entity.go index 33e48dba..7f5f6951 100644 --- a/api/internal/scheduler/entity/entity.go +++ b/api/internal/scheduler/entity/entity.go @@ -11,3 +11,9 @@ type Participant struct { Name string Participant_id int64 } + +type WeightP struct { + Participant_id int64 + Weight int32 + Name string +} diff --git a/api/internal/scheduler/strategy/staticWeight.go b/api/internal/scheduler/strategy/staticWeight.go index 3aa5d769..b028baaa 100644 --- a/api/internal/scheduler/strategy/staticWeight.go +++ b/api/internal/scheduler/strategy/staticWeight.go @@ -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 }