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.

300 lines
9.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 EACH_COLLECTION|<collection_name>] [-force] [-dataCenter <data_center>]
  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("collection", "EACH_COLLECTION", "collection name, or \"EACH_COLLECTION\" for each collection")
  47. dc := balanceCommand.String("dataCenter", "", "only apply the balancing for this dataCenter")
  48. applyBalancing := balanceCommand.Bool("force", 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 {
  80. if err = balanceEcVolumes(commandEnv, *collection, *applyBalancing); err != nil {
  81. return err
  82. }
  83. }
  84. }
  85. return nil
  86. }
  87. func balanceEcVolumes(commandEnv *CommandEnv, collection string, applyBalancing bool) error {
  88. ctx := context.Background()
  89. fmt.Printf("balanceEcVolumes %s\n", collection)
  90. // collect all ec nodes
  91. allEcNodes, totalFreeEcSlots, err := collectEcNodes(ctx, commandEnv)
  92. if err != nil {
  93. return err
  94. }
  95. if totalFreeEcSlots < 1 {
  96. return fmt.Errorf("no free ec shard slots. only %d left", totalFreeEcSlots)
  97. }
  98. // vid => []ecNode
  99. vidLocations := make(map[needle.VolumeId][]*EcNode)
  100. for _, ecNode := range allEcNodes {
  101. for _, shardInfo := range ecNode.info.EcShardInfos {
  102. vidLocations[needle.VolumeId(shardInfo.Id)] = append(vidLocations[needle.VolumeId(shardInfo.Id)], ecNode)
  103. }
  104. }
  105. for vid, locations := range vidLocations {
  106. if err := doDeduplicateEcShards(ctx, commandEnv, collection, vid, locations, applyBalancing); err != nil {
  107. return err
  108. }
  109. if err := doBalanceEcShards(ctx, commandEnv, collection, vid, locations, allEcNodes, applyBalancing); err != nil {
  110. return err
  111. }
  112. }
  113. return nil
  114. }
  115. func doBalanceEcShards(ctx context.Context, commandEnv *CommandEnv, collection string, vid needle.VolumeId, locations []*EcNode, allEcNodes []*EcNode, applyBalancing bool) error {
  116. // collect all ec nodes with at least one free slot
  117. var possibleDestinationEcNodes []*EcNode
  118. for _, ecNode := range allEcNodes {
  119. if ecNode.freeEcSlot > 0 {
  120. possibleDestinationEcNodes = append(possibleDestinationEcNodes, ecNode)
  121. }
  122. }
  123. // calculate average number of shards an ec node should have for one volume
  124. averageShardsPerEcNode := int(math.Ceil(float64(erasure_coding.TotalShardsCount) / float64(len(possibleDestinationEcNodes))))
  125. fmt.Printf("vid %d averageShardsPerEcNode %+v\n", vid, averageShardsPerEcNode)
  126. // check whether this volume has ecNodes that are over average
  127. isOverLimit := false
  128. for _, ecNode := range locations {
  129. shardBits := findEcVolumeShards(ecNode, vid)
  130. if shardBits.ShardIdCount() > averageShardsPerEcNode {
  131. isOverLimit = true
  132. fmt.Printf("vid %d %s has %d shards, isOverLimit %+v\n", vid, ecNode.info.Id, shardBits.ShardIdCount(), isOverLimit)
  133. break
  134. }
  135. }
  136. if isOverLimit {
  137. if err := spreadShardsIntoMoreDataNodes(ctx, commandEnv, averageShardsPerEcNode, collection, vid, locations, possibleDestinationEcNodes, applyBalancing); err != nil {
  138. return err
  139. }
  140. }
  141. return nil
  142. }
  143. func doDeduplicateEcShards(ctx context.Context, commandEnv *CommandEnv, collection string, vid needle.VolumeId, locations []*EcNode, applyBalancing bool) error {
  144. // check whether this volume has ecNodes that are over average
  145. shardToLocations := make([][]*EcNode, erasure_coding.TotalShardsCount)
  146. for _, ecNode := range locations {
  147. shardBits := findEcVolumeShards(ecNode, vid)
  148. for _, shardId := range shardBits.ShardIds() {
  149. shardToLocations[shardId] = append(shardToLocations[shardId], ecNode)
  150. }
  151. }
  152. for shardId, ecNodes := range shardToLocations {
  153. if len(ecNodes) <= 1 {
  154. continue
  155. }
  156. sortEcNodes(ecNodes)
  157. fmt.Printf("ec shard %d.%d has %d copies, keeping %v\n", vid, shardId, len(ecNodes), ecNodes[0].info.Id)
  158. if !applyBalancing {
  159. continue
  160. }
  161. duplicatedShardIds := []uint32{uint32(shardId)}
  162. for _, ecNode := range ecNodes[1:] {
  163. if err := unmountEcShards(ctx, commandEnv.option.GrpcDialOption, vid, ecNode.info.Id, duplicatedShardIds); err != nil {
  164. return err
  165. }
  166. if err := sourceServerDeleteEcShards(ctx, commandEnv.option.GrpcDialOption, collection, vid, ecNode.info.Id, duplicatedShardIds); err != nil {
  167. return err
  168. }
  169. deleteEcVolumeShards(ecNode, vid, duplicatedShardIds)
  170. ecNode.freeEcSlot++
  171. }
  172. }
  173. return nil
  174. }
  175. func spreadShardsIntoMoreDataNodes(ctx context.Context, commandEnv *CommandEnv, averageShardsPerEcNode int, collection string, vid needle.VolumeId, existingLocations, possibleDestinationEcNodes []*EcNode, applyBalancing bool) error {
  176. for _, ecNode := range existingLocations {
  177. shardBits := findEcVolumeShards(ecNode, vid)
  178. overLimitCount := shardBits.ShardIdCount() - averageShardsPerEcNode
  179. for _, shardId := range shardBits.ShardIds() {
  180. if overLimitCount <= 0 {
  181. break
  182. }
  183. fmt.Printf("%s has %d overlimit, moving ec shard %d.%d\n", ecNode.info.Id, overLimitCount, vid, shardId)
  184. err := pickOneEcNodeAndMoveOneShard(ctx, commandEnv, averageShardsPerEcNode, ecNode, collection, vid, shardId, possibleDestinationEcNodes, applyBalancing)
  185. if err != nil {
  186. return err
  187. }
  188. overLimitCount--
  189. }
  190. }
  191. return nil
  192. }
  193. func pickOneEcNodeAndMoveOneShard(ctx context.Context, commandEnv *CommandEnv, averageShardsPerEcNode int, existingLocation *EcNode, collection string, vid needle.VolumeId, shardId erasure_coding.ShardId, possibleDestinationEcNodes []*EcNode, applyBalancing bool) error {
  194. sortEcNodes(possibleDestinationEcNodes)
  195. for _, destEcNode := range possibleDestinationEcNodes {
  196. if destEcNode.info.Id == existingLocation.info.Id {
  197. continue
  198. }
  199. if destEcNode.freeEcSlot <= 0 {
  200. continue
  201. }
  202. if findEcVolumeShards(destEcNode, vid).ShardIdCount() >= averageShardsPerEcNode {
  203. continue
  204. }
  205. fmt.Printf("%s moves ec shard %d.%d to %s\n", existingLocation.info.Id, vid, shardId, destEcNode.info.Id)
  206. err := moveMountedShardToEcNode(ctx, commandEnv, existingLocation, collection, vid, shardId, destEcNode, applyBalancing)
  207. if err != nil {
  208. return err
  209. }
  210. destEcNode.freeEcSlot--
  211. existingLocation.freeEcSlot++
  212. return nil
  213. }
  214. return nil
  215. }
  216. func findEcVolumeShards(ecNode *EcNode, vid needle.VolumeId) erasure_coding.ShardBits {
  217. for _, shardInfo := range ecNode.info.EcShardInfos {
  218. if needle.VolumeId(shardInfo.Id) == vid {
  219. return erasure_coding.ShardBits(shardInfo.EcIndexBits)
  220. }
  221. }
  222. return 0
  223. }
  224. func addEcVolumeShards(ecNode *EcNode, vid needle.VolumeId, shardIds []uint32){
  225. for _, shardInfo := range ecNode.info.EcShardInfos {
  226. if needle.VolumeId(shardInfo.Id) == vid {
  227. for _, shardId := range shardIds{
  228. shardInfo.EcIndexBits = uint32(erasure_coding.ShardBits(shardInfo.EcIndexBits).AddShardId(erasure_coding.ShardId(shardId)))
  229. }
  230. }
  231. }
  232. }
  233. func deleteEcVolumeShards(ecNode *EcNode, vid needle.VolumeId, shardIds []uint32){
  234. for _, shardInfo := range ecNode.info.EcShardInfos {
  235. if needle.VolumeId(shardInfo.Id) == vid {
  236. for _, shardId := range shardIds{
  237. shardInfo.EcIndexBits = uint32(erasure_coding.ShardBits(shardInfo.EcIndexBits).RemoveShardId(erasure_coding.ShardId(shardId)))
  238. }
  239. }
  240. }
  241. }