You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

random.go 2.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package strategy
  2. import (
  3. "github.com/pkg/errors"
  4. "math/rand"
  5. )
  6. type RandomStrategy struct {
  7. clusterIds []string
  8. replicas int32
  9. }
  10. func NewRandomStrategy(clusterIds []string, replicas int32) *RandomStrategy {
  11. return &RandomStrategy{clusterIds: clusterIds,
  12. replicas: replicas,
  13. }
  14. }
  15. func (s *RandomStrategy) Schedule() ([]*AssignedCluster, error) {
  16. var results []*AssignedCluster
  17. if s.replicas < 1 {
  18. return nil, errors.New("replicas must be greater than 0")
  19. }
  20. if len(s.clusterIds) < 1 {
  21. return nil, errors.New("cluster must be greater than 0")
  22. }
  23. if len(s.clusterIds) == 0 || s.clusterIds == nil {
  24. return nil, errors.New("weight must be set")
  25. }
  26. if s.replicas == 1 {
  27. // 创建一个切片来保存每个部分的数量
  28. parts := make([]int32, len(s.clusterIds))
  29. // 剩余要分配的副本数
  30. remaining := s.replicas
  31. // 随机分配剩余的副本
  32. for remaining > 0 {
  33. // 随机选择一个部分(索引从0到numParts-1)
  34. partIndex := rand.Intn(len(s.clusterIds))
  35. // 如果该部分加上一个副本后不会超过总数,则分配一个副本
  36. //if parts[partIndex]+1 <= s.replicas {
  37. parts[partIndex]++
  38. remaining--
  39. //}
  40. }
  41. if len(s.clusterIds) == len(parts) {
  42. for i, key := range s.clusterIds {
  43. cluster := &AssignedCluster{ClusterId: key, Replicas: parts[i]}
  44. results = append(results, cluster)
  45. }
  46. }
  47. } else {
  48. // 创建一个切片来保存每个部分的数量
  49. parts := make([]int32, len(s.clusterIds))
  50. // 首先将每个部分都分配至少一个副本
  51. for i := range parts {
  52. parts[i] = 1
  53. s.replicas--
  54. }
  55. // 剩余要分配的副本数
  56. remaining := s.replicas
  57. // 随机分配剩余的副本
  58. for remaining > 0 {
  59. // 随机选择一个部分(索引从0到numParts-1)
  60. partIndex := rand.Intn(len(s.clusterIds))
  61. // 如果该部分加上一个副本后不会超过总数,则分配一个副本
  62. //if parts[partIndex]+1 <= s.replicas {
  63. parts[partIndex]++
  64. remaining--
  65. //}
  66. }
  67. if len(s.clusterIds) == len(parts) {
  68. for i, key := range s.clusterIds {
  69. cluster := &AssignedCluster{ClusterId: key, Replicas: parts[i]}
  70. results = append(results, cluster)
  71. }
  72. }
  73. }
  74. return results, nil
  75. }

PCM is positioned as Software stack over Cloud, aiming to build the standards and ecology of heterogeneous cloud collaboration for JCC in a non intrusive and autonomous peer-to-peer manner.