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.

255 lines
7.5 KiB

  1. package shell
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "io"
  7. "os"
  8. "sort"
  9. "time"
  10. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  11. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  12. )
  13. func init() {
  14. Commands = append(Commands, &commandVolumeBalance{})
  15. }
  16. type commandVolumeBalance struct {
  17. }
  18. func (c *commandVolumeBalance) Name() string {
  19. return "volume.balance"
  20. }
  21. func (c *commandVolumeBalance) Help() string {
  22. return `balance all volumes among volume servers
  23. volume.balance [-collection ALL|EACH_COLLECTION|<collection_name>] [-force] [-dataCenter=<data_center_name>]
  24. Algorithm:
  25. For each type of volume server (different max volume count limit){
  26. for each collection {
  27. balanceWritableVolumes()
  28. balanceReadOnlyVolumes()
  29. }
  30. }
  31. func balanceWritableVolumes(){
  32. idealWritableVolumes = totalWritableVolumes / numVolumeServers
  33. for hasMovedOneVolume {
  34. sort all volume servers ordered by the number of local writable volumes
  35. pick the volume server A with the lowest number of writable volumes x
  36. pick the volume server B with the highest number of writable volumes y
  37. if y > idealWritableVolumes and x +1 <= idealWritableVolumes {
  38. if B has a writable volume id v that A does not have {
  39. move writable volume v from A to B
  40. }
  41. }
  42. }
  43. }
  44. func balanceReadOnlyVolumes(){
  45. //similar to balanceWritableVolumes
  46. }
  47. `
  48. }
  49. func (c *commandVolumeBalance) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  50. balanceCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
  51. collection := balanceCommand.String("collection", "EACH_COLLECTION", "collection name, or use \"ALL_COLLECTIONS\" across collections, \"EACH_COLLECTION\" for each collection")
  52. dc := balanceCommand.String("dataCenter", "", "only apply the balancing for this dataCenter")
  53. applyBalancing := balanceCommand.Bool("force", false, "apply the balancing plan.")
  54. if err = balanceCommand.Parse(args); err != nil {
  55. return nil
  56. }
  57. var resp *master_pb.VolumeListResponse
  58. ctx := context.Background()
  59. err = commandEnv.MasterClient.WithClient(ctx, func(client master_pb.SeaweedClient) error {
  60. resp, err = client.VolumeList(ctx, &master_pb.VolumeListRequest{})
  61. return err
  62. })
  63. if err != nil {
  64. return err
  65. }
  66. typeToNodes := collectVolumeServersByType(resp.TopologyInfo, *dc)
  67. for maxVolumeCount, volumeServers := range typeToNodes {
  68. if len(volumeServers) < 2 {
  69. fmt.Printf("only 1 node is configured max %d volumes, skipping balancing\n", maxVolumeCount)
  70. continue
  71. }
  72. if *collection == "EACH_COLLECTION" {
  73. collections, err := ListCollectionNames(commandEnv, true, false)
  74. if err != nil {
  75. return err
  76. }
  77. for _, c := range collections {
  78. if err = balanceVolumeServers(commandEnv, volumeServers, resp.VolumeSizeLimitMb*1024*1024, c, *applyBalancing); err != nil {
  79. return err
  80. }
  81. }
  82. } else if *collection == "ALL_COLLECTIONS" {
  83. if err = balanceVolumeServers(commandEnv, volumeServers, resp.VolumeSizeLimitMb*1024*1024, "ALL_COLLECTIONS", *applyBalancing); err != nil {
  84. return err
  85. }
  86. } else {
  87. if err = balanceVolumeServers(commandEnv, volumeServers, resp.VolumeSizeLimitMb*1024*1024, *collection, *applyBalancing); err != nil {
  88. return err
  89. }
  90. }
  91. }
  92. return nil
  93. }
  94. func balanceVolumeServers(commandEnv *CommandEnv, nodes []*Node, volumeSizeLimit uint64, collection string, applyBalancing bool) error {
  95. // balance writable volumes
  96. for _, n := range nodes {
  97. n.selectVolumes(func(v *master_pb.VolumeInformationMessage) bool {
  98. if collection != "ALL_COLLECTIONS" {
  99. if v.Collection != collection {
  100. return false
  101. }
  102. }
  103. return !v.ReadOnly && v.Size < volumeSizeLimit
  104. })
  105. }
  106. if err := balanceSelectedVolume(commandEnv, nodes, sortWritableVolumes, applyBalancing); err != nil {
  107. return err
  108. }
  109. // balance readable volumes
  110. for _, n := range nodes {
  111. n.selectVolumes(func(v *master_pb.VolumeInformationMessage) bool {
  112. if collection != "ALL_COLLECTIONS" {
  113. if v.Collection != collection {
  114. return false
  115. }
  116. }
  117. return v.ReadOnly || v.Size >= volumeSizeLimit
  118. })
  119. }
  120. if err := balanceSelectedVolume(commandEnv, nodes, sortReadOnlyVolumes, applyBalancing); err != nil {
  121. return err
  122. }
  123. return nil
  124. }
  125. func collectVolumeServersByType(t *master_pb.TopologyInfo, selectedDataCenter string) (typeToNodes map[uint64][]*Node) {
  126. typeToNodes = make(map[uint64][]*Node)
  127. for _, dc := range t.DataCenterInfos {
  128. if selectedDataCenter != "" && dc.Id != selectedDataCenter {
  129. continue
  130. }
  131. for _, r := range dc.RackInfos {
  132. for _, dn := range r.DataNodeInfos {
  133. typeToNodes[dn.MaxVolumeCount] = append(typeToNodes[dn.MaxVolumeCount], &Node{
  134. info: dn,
  135. dc: dc.Id,
  136. rack: r.Id,
  137. })
  138. }
  139. }
  140. }
  141. return
  142. }
  143. type Node struct {
  144. info *master_pb.DataNodeInfo
  145. selectedVolumes map[uint32]*master_pb.VolumeInformationMessage
  146. dc string
  147. rack string
  148. }
  149. func sortWritableVolumes(volumes []*master_pb.VolumeInformationMessage) {
  150. sort.Slice(volumes, func(i, j int) bool {
  151. return volumes[i].Size < volumes[j].Size
  152. })
  153. }
  154. func sortReadOnlyVolumes(volumes []*master_pb.VolumeInformationMessage) {
  155. sort.Slice(volumes, func(i, j int) bool {
  156. return volumes[i].Id < volumes[j].Id
  157. })
  158. }
  159. func balanceSelectedVolume(commandEnv *CommandEnv, nodes []*Node, sortCandidatesFn func(volumes []*master_pb.VolumeInformationMessage), applyBalancing bool) error {
  160. selectedVolumeCount := 0
  161. for _, dn := range nodes {
  162. selectedVolumeCount += len(dn.selectedVolumes)
  163. }
  164. idealSelectedVolumes := ceilDivide(selectedVolumeCount, len(nodes))
  165. hasMove := true
  166. for hasMove {
  167. hasMove = false
  168. sort.Slice(nodes, func(i, j int) bool {
  169. // TODO sort by free volume slots???
  170. return len(nodes[i].selectedVolumes) < len(nodes[j].selectedVolumes)
  171. })
  172. emptyNode, fullNode := nodes[0], nodes[len(nodes)-1]
  173. if len(fullNode.selectedVolumes) > idealSelectedVolumes && len(emptyNode.selectedVolumes)+1 <= idealSelectedVolumes {
  174. // sort the volumes to move
  175. var candidateVolumes []*master_pb.VolumeInformationMessage
  176. for _, v := range fullNode.selectedVolumes {
  177. candidateVolumes = append(candidateVolumes, v)
  178. }
  179. sortCandidatesFn(candidateVolumes)
  180. for _, v := range candidateVolumes {
  181. if v.ReplicaPlacement > 0 {
  182. if fullNode.dc != emptyNode.dc && fullNode.rack != emptyNode.rack {
  183. // TODO this logic is too simple, but should work most of the time
  184. // Need a correct algorithm to handle all different cases
  185. continue
  186. }
  187. }
  188. if _, found := emptyNode.selectedVolumes[v.Id]; !found {
  189. if err := moveVolume(commandEnv, v, fullNode, emptyNode, applyBalancing); err == nil {
  190. delete(fullNode.selectedVolumes, v.Id)
  191. emptyNode.selectedVolumes[v.Id] = v
  192. hasMove = true
  193. break
  194. } else {
  195. return err
  196. }
  197. }
  198. }
  199. }
  200. }
  201. return nil
  202. }
  203. func moveVolume(commandEnv *CommandEnv, v *master_pb.VolumeInformationMessage, fullNode *Node, emptyNode *Node, applyBalancing bool) error {
  204. collectionPrefix := v.Collection + "_"
  205. if v.Collection == "" {
  206. collectionPrefix = ""
  207. }
  208. fmt.Fprintf(os.Stdout, "moving volume %s%d %s => %s\n", collectionPrefix, v.Id, fullNode.info.Id, emptyNode.info.Id)
  209. if applyBalancing {
  210. ctx := context.Background()
  211. return LiveMoveVolume(ctx, commandEnv.option.GrpcDialOption, needle.VolumeId(v.Id), fullNode.info.Id, emptyNode.info.Id, 5*time.Second)
  212. }
  213. return nil
  214. }
  215. func (node *Node) selectVolumes(fn func(v *master_pb.VolumeInformationMessage) bool) {
  216. node.selectedVolumes = make(map[uint32]*master_pb.VolumeInformationMessage)
  217. for _, v := range node.info.VolumeInfos {
  218. if fn(v) {
  219. node.selectedVolumes[v.Id] = v
  220. }
  221. }
  222. }