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.

246 lines
7.1 KiB

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