command_volume_balance.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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>] [-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 _, volumeServers := range typeToNodes {
  68. if len(volumeServers) < 2 {
  69. continue
  70. }
  71. if *collection == "EACH_COLLECTION" {
  72. collections, err := ListCollectionNames(commandEnv, true, false)
  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 := ceilDivide(selectedVolumeCount, len(nodes))
  164. hasMove := true
  165. for hasMove {
  166. hasMove = false
  167. sort.Slice(nodes, func(i, j int) bool {
  168. // TODO sort by free volume slots???
  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. }