balance_brokers.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package pub_balancer
  2. import (
  3. cmap "github.com/orcaman/concurrent-map/v2"
  4. "github.com/seaweedfs/seaweedfs/weed/mq/topic"
  5. "math/rand"
  6. )
  7. func BalanceTopicPartitionOnBrokers(brokers cmap.ConcurrentMap[string, *BrokerStats]) BalanceAction {
  8. // 1. calculate the average number of partitions per broker
  9. var totalPartitionCount int32
  10. var totalBrokerCount int32
  11. for brokerStats := range brokers.IterBuffered() {
  12. totalBrokerCount++
  13. totalPartitionCount += brokerStats.Val.TopicPartitionCount
  14. }
  15. averagePartitionCountPerBroker := totalPartitionCount / totalBrokerCount
  16. minPartitionCountPerBroker := averagePartitionCountPerBroker
  17. maxPartitionCountPerBroker := averagePartitionCountPerBroker
  18. var sourceBroker, targetBroker string
  19. var candidatePartition *topic.TopicPartition
  20. for brokerStats := range brokers.IterBuffered() {
  21. if minPartitionCountPerBroker > brokerStats.Val.TopicPartitionCount {
  22. minPartitionCountPerBroker = brokerStats.Val.TopicPartitionCount
  23. targetBroker = brokerStats.Key
  24. }
  25. if maxPartitionCountPerBroker < brokerStats.Val.TopicPartitionCount {
  26. maxPartitionCountPerBroker = brokerStats.Val.TopicPartitionCount
  27. sourceBroker = brokerStats.Key
  28. // select a random partition from the source broker
  29. randomePartitionIndex := rand.Intn(int(brokerStats.Val.TopicPartitionCount))
  30. index := 0
  31. for topicPartitionStats := range brokerStats.Val.TopicPartitionStats.IterBuffered() {
  32. if index == randomePartitionIndex {
  33. candidatePartition = &topicPartitionStats.Val.TopicPartition
  34. break
  35. } else {
  36. index++
  37. }
  38. }
  39. }
  40. }
  41. if minPartitionCountPerBroker >= maxPartitionCountPerBroker-1 {
  42. return nil
  43. }
  44. // 2. move the partitions from the source broker to the target broker
  45. return &BalanceActionMove{
  46. TopicPartition: *candidatePartition,
  47. SourceBroker: sourceBroker,
  48. TargetBroker: targetBroker,
  49. }
  50. }