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. "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 [-c ALL|EACH_COLLECTION|<collection_name>] [-f] [-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 {
  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("c", "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("f", 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 _, volumeServers := range typeToNodes {
  68. if len(volumeServers) < 2 {
  69. continue
  70. }
  71. if *collection == "EACH_COLLECTION" {
  72. collections, err := ListCollectionNames(commandEnv)
  73. if err != nil {
  74. return err
  75. }
  76. for _, c := range collections {
  77. if err = balanceVolumeServers(commandEnv, volumeServers, resp.VolumeSizeLimitMb*1024*1024, c, *applyBalancing); err != nil {
  78. return err
  79. }
  80. }
  81. } else if *collection == "ALL" {
  82. if err = balanceVolumeServers(commandEnv, volumeServers, resp.VolumeSizeLimitMb*1024*1024, "ALL", *applyBalancing); err != nil {
  83. return err
  84. }
  85. } else {
  86. if err = balanceVolumeServers(commandEnv, volumeServers, resp.VolumeSizeLimitMb*1024*1024, *collection, *applyBalancing); err != nil {
  87. return err
  88. }
  89. }
  90. }
  91. return nil
  92. }
  93. func balanceVolumeServers(commandEnv *commandEnv, dataNodeInfos []*master_pb.DataNodeInfo, volumeSizeLimit uint64, collection string, applyBalancing bool) error {
  94. var nodes []*Node
  95. for _, dn := range dataNodeInfos {
  96. nodes = append(nodes, &Node{
  97. info: dn,
  98. })
  99. }
  100. // balance writable volumes
  101. for _, n := range nodes {
  102. n.selectVolumes(func(v *master_pb.VolumeInformationMessage) bool {
  103. if collection != "ALL" {
  104. if v.Collection != collection {
  105. return false
  106. }
  107. }
  108. return !v.ReadOnly && v.Size < volumeSizeLimit
  109. })
  110. }
  111. if err := balanceSelectedVolume(commandEnv, nodes, sortWritableVolumes, applyBalancing); err != nil {
  112. return err
  113. }
  114. // balance readable volumes
  115. for _, n := range nodes {
  116. n.selectVolumes(func(v *master_pb.VolumeInformationMessage) bool {
  117. if collection != "ALL" {
  118. if v.Collection != collection {
  119. return false
  120. }
  121. }
  122. return v.ReadOnly || v.Size >= volumeSizeLimit
  123. })
  124. }
  125. if err := balanceSelectedVolume(commandEnv, nodes, sortReadOnlyVolumes, applyBalancing); err != nil {
  126. return err
  127. }
  128. return nil
  129. }
  130. func collectVolumeServersByType(t *master_pb.TopologyInfo, selectedDataCenter string) (typeToNodes map[uint64][]*master_pb.DataNodeInfo) {
  131. typeToNodes = make(map[uint64][]*master_pb.DataNodeInfo)
  132. for _, dc := range t.DataCenterInfos {
  133. if selectedDataCenter != "" && dc.Id != selectedDataCenter {
  134. continue
  135. }
  136. for _, r := range dc.RackInfos {
  137. for _, dn := range r.DataNodeInfos {
  138. typeToNodes[dn.MaxVolumeCount] = append(typeToNodes[dn.MaxVolumeCount], dn)
  139. }
  140. }
  141. }
  142. return
  143. }
  144. type Node struct {
  145. info *master_pb.DataNodeInfo
  146. selectedVolumes map[uint32]*master_pb.VolumeInformationMessage
  147. }
  148. func sortWritableVolumes(volumes []*master_pb.VolumeInformationMessage) {
  149. sort.Slice(volumes, func(i, j int) bool {
  150. return volumes[i].Size < volumes[j].Size
  151. })
  152. }
  153. func sortReadOnlyVolumes(volumes []*master_pb.VolumeInformationMessage) {
  154. sort.Slice(volumes, func(i, j int) bool {
  155. return volumes[i].Id < volumes[j].Id
  156. })
  157. }
  158. func balanceSelectedVolume(commandEnv *commandEnv, nodes []*Node, sortCandidatesFn func(volumes []*master_pb.VolumeInformationMessage), applyBalancing bool) error {
  159. selectedVolumeCount := 0
  160. for _, dn := range nodes {
  161. selectedVolumeCount += len(dn.selectedVolumes)
  162. }
  163. idealSelectedVolumes := selectedVolumeCount / len(nodes)
  164. hasMove := true
  165. for hasMove {
  166. hasMove = false
  167. sort.Slice(nodes, func(i, j int) bool {
  168. return len(nodes[i].selectedVolumes) < len(nodes[j].selectedVolumes)
  169. })
  170. emptyNode, fullNode := nodes[0], nodes[len(nodes)-1]
  171. if len(fullNode.selectedVolumes) > idealSelectedVolumes && len(emptyNode.selectedVolumes)+1 <= idealSelectedVolumes {
  172. // sort the volumes to move
  173. var candidateVolumes []*master_pb.VolumeInformationMessage
  174. for _, v := range fullNode.selectedVolumes {
  175. candidateVolumes = append(candidateVolumes, v)
  176. }
  177. sortCandidatesFn(candidateVolumes)
  178. for _, v := range candidateVolumes {
  179. if _, found := emptyNode.selectedVolumes[v.Id]; !found {
  180. if err := moveVolume(commandEnv, v, fullNode, emptyNode, applyBalancing); err == nil {
  181. delete(fullNode.selectedVolumes, v.Id)
  182. emptyNode.selectedVolumes[v.Id] = v
  183. hasMove = true
  184. break
  185. } else {
  186. return err
  187. }
  188. }
  189. }
  190. }
  191. }
  192. return nil
  193. }
  194. func moveVolume(commandEnv *commandEnv, v *master_pb.VolumeInformationMessage, fullNode *Node, emptyNode *Node, applyBalancing bool) error {
  195. collectionPrefix := v.Collection + "_"
  196. if v.Collection == "" {
  197. collectionPrefix = ""
  198. }
  199. fmt.Fprintf(os.Stdout, "moving volume %s%d %s => %s\n", collectionPrefix, v.Id, fullNode.info.Id, emptyNode.info.Id)
  200. if applyBalancing {
  201. ctx := context.Background()
  202. return LiveMoveVolume(ctx, commandEnv.option.GrpcDialOption, needle.VolumeId(v.Id), fullNode.info.Id, emptyNode.info.Id, 5*time.Second)
  203. }
  204. return nil
  205. }
  206. func (node *Node) selectVolumes(fn func(v *master_pb.VolumeInformationMessage) bool) {
  207. node.selectedVolumes = make(map[uint32]*master_pb.VolumeInformationMessage)
  208. for _, v := range node.info.VolumeInfos {
  209. if fn(v) {
  210. node.selectedVolumes[v.Id] = v
  211. }
  212. }
  213. }