command_volume_balance.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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, 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_COLLECTIONS" {
  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_COLLECTIONS" {
  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 := 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 _, found := emptyNode.selectedVolumes[v.Id]; !found {
  182. if err := moveVolume(commandEnv, v, fullNode, emptyNode, applyBalancing); err == nil {
  183. delete(fullNode.selectedVolumes, v.Id)
  184. emptyNode.selectedVolumes[v.Id] = v
  185. hasMove = true
  186. break
  187. } else {
  188. return err
  189. }
  190. }
  191. }
  192. }
  193. }
  194. return nil
  195. }
  196. func moveVolume(commandEnv *CommandEnv, v *master_pb.VolumeInformationMessage, fullNode *Node, emptyNode *Node, applyBalancing bool) error {
  197. collectionPrefix := v.Collection + "_"
  198. if v.Collection == "" {
  199. collectionPrefix = ""
  200. }
  201. fmt.Fprintf(os.Stdout, "moving volume %s%d %s => %s\n", collectionPrefix, v.Id, fullNode.info.Id, emptyNode.info.Id)
  202. if applyBalancing {
  203. ctx := context.Background()
  204. return LiveMoveVolume(ctx, commandEnv.option.GrpcDialOption, needle.VolumeId(v.Id), fullNode.info.Id, emptyNode.info.Id, 5*time.Second)
  205. }
  206. return nil
  207. }
  208. func (node *Node) selectVolumes(fn func(v *master_pb.VolumeInformationMessage) bool) {
  209. node.selectedVolumes = make(map[uint32]*master_pb.VolumeInformationMessage)
  210. for _, v := range node.info.VolumeInfos {
  211. if fn(v) {
  212. node.selectedVolumes[v.Id] = v
  213. }
  214. }
  215. }