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

245 lines
7.0 KiB

  1. package shell
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "io"
  7. "math"
  8. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  9. "github.com/chrislusf/seaweedfs/weed/storage/erasure_coding"
  10. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  11. )
  12. func init() {
  13. commands = append(commands, &commandEcBalance{})
  14. }
  15. type commandEcBalance struct {
  16. }
  17. func (c *commandEcBalance) Name() string {
  18. return "ec.balance"
  19. }
  20. func (c *commandEcBalance) Help() string {
  21. return `balance all ec shards among volume servers
  22. ec.balance [-c ALL|EACH_COLLECTION|<collection_name>] [-f]
  23. Algorithm:
  24. For each type of volume server (different max volume count limit){
  25. for each collection {
  26. balanceEcVolumes()
  27. }
  28. }
  29. func balanceEcVolumes(){
  30. idealWritableVolumes = totalWritableVolumes / numVolumeServers
  31. for {
  32. sort all volume servers ordered by the number of local writable volumes
  33. pick the volume server A with the lowest number of writable volumes x
  34. pick the volume server B with the highest number of writable volumes y
  35. if y > idealWritableVolumes and x +1 <= idealWritableVolumes {
  36. if B has a writable volume id v that A does not have {
  37. move writable volume v from A to B
  38. }
  39. }
  40. }
  41. }
  42. `
  43. }
  44. func (c *commandEcBalance) Do(args []string, commandEnv *commandEnv, writer io.Writer) (err error) {
  45. balanceCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
  46. collection := balanceCommand.String("c", "EACH_COLLECTION", "collection name, or use \"ALL_COLLECTIONS\" across collections, \"EACH_COLLECTION\" for each collection")
  47. dc := balanceCommand.String("dataCenter", "", "only apply the balancing for this dataCenter")
  48. applyBalancing := balanceCommand.Bool("f", false, "apply the balancing plan.")
  49. if err = balanceCommand.Parse(args); err != nil {
  50. return nil
  51. }
  52. var resp *master_pb.VolumeListResponse
  53. ctx := context.Background()
  54. err = commandEnv.masterClient.WithClient(ctx, func(client master_pb.SeaweedClient) error {
  55. resp, err = client.VolumeList(ctx, &master_pb.VolumeListRequest{})
  56. return err
  57. })
  58. if err != nil {
  59. return err
  60. }
  61. typeToNodes := collectVolumeServersByType(resp.TopologyInfo, *dc)
  62. for _, volumeServers := range typeToNodes {
  63. fmt.Printf("balanceEcVolumes servers %d\n", len(volumeServers))
  64. if len(volumeServers) < 2 {
  65. continue
  66. }
  67. if *collection == "EACH_COLLECTION" {
  68. collections, err := ListCollectionNames(commandEnv, false, true)
  69. if err != nil {
  70. return err
  71. }
  72. fmt.Printf("balanceEcVolumes collections %+v\n", len(collections))
  73. for _, c := range collections {
  74. fmt.Printf("balanceEcVolumes collection %+v\n", c)
  75. if err = balanceEcVolumes(commandEnv, c, *applyBalancing); err != nil {
  76. return err
  77. }
  78. }
  79. } else if *collection == "ALL" {
  80. if err = balanceEcVolumes(commandEnv, "ALL", *applyBalancing); err != nil {
  81. return err
  82. }
  83. } else {
  84. if err = balanceEcVolumes(commandEnv, *collection, *applyBalancing); err != nil {
  85. return err
  86. }
  87. }
  88. }
  89. return nil
  90. }
  91. func balanceEcVolumes(commandEnv *commandEnv, collection string, applyBalancing bool) error {
  92. ctx := context.Background()
  93. fmt.Printf("balanceEcVolumes %s\n", collection)
  94. // collect all ec nodes
  95. allEcNodes, totalFreeEcSlots, err := collectEcNodes(ctx, commandEnv)
  96. if err != nil {
  97. return err
  98. }
  99. if totalFreeEcSlots < 1 {
  100. return fmt.Errorf("no free ec shard slots. only %d left", totalFreeEcSlots)
  101. }
  102. // vid => []ecNode
  103. vidLocations := make(map[needle.VolumeId][]*EcNode)
  104. for _, ecNode := range allEcNodes {
  105. for _, shardInfo := range ecNode.info.EcShardInfos {
  106. vidLocations[needle.VolumeId(shardInfo.Id)] = append(vidLocations[needle.VolumeId(shardInfo.Id)], ecNode)
  107. }
  108. }
  109. for vid, locations := range vidLocations {
  110. // collect all ec nodes with at least one free slot
  111. var possibleDestinationEcNodes []*EcNode
  112. for _, ecNode := range allEcNodes {
  113. if ecNode.freeEcSlot > 0 {
  114. possibleDestinationEcNodes = append(possibleDestinationEcNodes, ecNode)
  115. }
  116. }
  117. // calculate average number of shards an ec node should have for one volume
  118. averageShardsPerEcNode := int(math.Ceil(float64(erasure_coding.TotalShardsCount) / float64(len(possibleDestinationEcNodes))))
  119. fmt.Printf("vid %d averageShardsPerEcNode %+v\n", vid, averageShardsPerEcNode)
  120. // check whether this volume has ecNodes that are over average
  121. isOverLimit := false
  122. for _, ecNode := range locations {
  123. shardBits := findEcVolumeShards(ecNode, vid)
  124. if shardBits.ShardIdCount() > averageShardsPerEcNode {
  125. isOverLimit = true
  126. fmt.Printf("vid %d %s has %d shards, isOverLimit %+v\n", vid, ecNode.info.Id, shardBits.ShardIdCount(), isOverLimit)
  127. break
  128. }
  129. }
  130. if isOverLimit {
  131. if err := spreadShardsIntoMoreDataNodes(ctx, commandEnv, averageShardsPerEcNode, vid, locations, possibleDestinationEcNodes, applyBalancing); err != nil {
  132. return err
  133. }
  134. }
  135. }
  136. return nil
  137. }
  138. func spreadShardsIntoMoreDataNodes(ctx context.Context, commandEnv *commandEnv, averageShardsPerEcNode int, vid needle.VolumeId, existingLocations, possibleDestinationEcNodes []*EcNode, applyBalancing bool) error {
  139. for _, ecNode := range existingLocations {
  140. shardBits := findEcVolumeShards(ecNode, vid)
  141. overLimitCount := shardBits.ShardIdCount() - averageShardsPerEcNode
  142. for _, shardId := range shardBits.ShardIds() {
  143. if overLimitCount <= 0 {
  144. break
  145. }
  146. fmt.Printf("%s has %d overlimit, moving ec shard %d.%d\n", ecNode.info.Id, overLimitCount, vid, shardId)
  147. err := pickOneEcNodeAndMoveOneShard(ctx, commandEnv, averageShardsPerEcNode, ecNode, vid, shardId, possibleDestinationEcNodes, applyBalancing)
  148. if err != nil {
  149. return err
  150. }
  151. overLimitCount--
  152. }
  153. }
  154. return nil
  155. }
  156. func pickOneEcNodeAndMoveOneShard(ctx context.Context, commandEnv *commandEnv, averageShardsPerEcNode int, existingLocation *EcNode, vid needle.VolumeId, shardId erasure_coding.ShardId, possibleDestinationEcNodes []*EcNode, applyBalancing bool) error {
  157. sortEcNodes(possibleDestinationEcNodes)
  158. for _, destEcNode := range possibleDestinationEcNodes {
  159. if destEcNode.info.Id == existingLocation.info.Id {
  160. continue
  161. }
  162. if destEcNode.freeEcSlot <= 0 {
  163. continue
  164. }
  165. if findEcVolumeShards(destEcNode, vid).ShardIdCount() >= averageShardsPerEcNode {
  166. continue
  167. }
  168. fmt.Printf("%s moves ec shard %d.%d to %s\n", existingLocation.info.Id, vid, shardId, destEcNode.info.Id)
  169. err := moveOneShardToEcNode(ctx, commandEnv, existingLocation, vid, shardId, destEcNode, applyBalancing)
  170. if err != nil {
  171. return err
  172. }
  173. destEcNode.freeEcSlot--
  174. return nil
  175. }
  176. return nil
  177. }
  178. func moveOneShardToEcNode(ctx context.Context, commandEnv *commandEnv, existingLocation *EcNode, vid needle.VolumeId, shardId erasure_coding.ShardId, destinationEcNode *EcNode, applyBalancing bool) error {
  179. fmt.Printf("moved ec shard %d.%d %s => %s\n", vid, shardId, existingLocation.info.Id, destinationEcNode.info.Id)
  180. return nil
  181. }
  182. func findEcVolumeShards(ecNode *EcNode, vid needle.VolumeId) erasure_coding.ShardBits {
  183. for _, shardInfo := range ecNode.info.EcShardInfos {
  184. if needle.VolumeId(shardInfo.Id) == vid {
  185. return erasure_coding.ShardBits(shardInfo.EcIndexBits)
  186. }
  187. }
  188. return 0
  189. }