command_volume_balance.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. if err = commandEnv.confirmIsLocked(); err != nil {
  51. return
  52. }
  53. balanceCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
  54. collection := balanceCommand.String("collection", "EACH_COLLECTION", "collection name, or use \"ALL_COLLECTIONS\" across collections, \"EACH_COLLECTION\" for each collection")
  55. dc := balanceCommand.String("dataCenter", "", "only apply the balancing for this dataCenter")
  56. applyBalancing := balanceCommand.Bool("force", false, "apply the balancing plan.")
  57. if err = balanceCommand.Parse(args); err != nil {
  58. return nil
  59. }
  60. var resp *master_pb.VolumeListResponse
  61. err = commandEnv.MasterClient.WithClient(func(client master_pb.SeaweedClient) error {
  62. resp, err = client.VolumeList(context.Background(), &master_pb.VolumeListRequest{})
  63. return err
  64. })
  65. if err != nil {
  66. return err
  67. }
  68. typeToNodes := collectVolumeServersByType(resp.TopologyInfo, *dc)
  69. for maxVolumeCount, volumeServers := range typeToNodes {
  70. if len(volumeServers) < 2 {
  71. fmt.Printf("only 1 node is configured max %d volumes, skipping balancing\n", maxVolumeCount)
  72. continue
  73. }
  74. if *collection == "EACH_COLLECTION" {
  75. collections, err := ListCollectionNames(commandEnv, true, false)
  76. if err != nil {
  77. return err
  78. }
  79. for _, c := range collections {
  80. if err = balanceVolumeServers(commandEnv, volumeServers, resp.VolumeSizeLimitMb*1024*1024, c, *applyBalancing); err != nil {
  81. return err
  82. }
  83. }
  84. } else if *collection == "ALL_COLLECTIONS" {
  85. if err = balanceVolumeServers(commandEnv, volumeServers, resp.VolumeSizeLimitMb*1024*1024, "ALL_COLLECTIONS", *applyBalancing); err != nil {
  86. return err
  87. }
  88. } else {
  89. if err = balanceVolumeServers(commandEnv, volumeServers, resp.VolumeSizeLimitMb*1024*1024, *collection, *applyBalancing); err != nil {
  90. return err
  91. }
  92. }
  93. }
  94. return nil
  95. }
  96. func balanceVolumeServers(commandEnv *CommandEnv, nodes []*Node, volumeSizeLimit uint64, collection string, applyBalancing bool) error {
  97. // balance writable volumes
  98. for _, n := range nodes {
  99. n.selectVolumes(func(v *master_pb.VolumeInformationMessage) bool {
  100. if collection != "ALL_COLLECTIONS" {
  101. if v.Collection != collection {
  102. return false
  103. }
  104. }
  105. return !v.ReadOnly && v.Size < volumeSizeLimit
  106. })
  107. }
  108. if err := balanceSelectedVolume(commandEnv, nodes, sortWritableVolumes, applyBalancing); err != nil {
  109. return err
  110. }
  111. // balance readable volumes
  112. for _, n := range nodes {
  113. n.selectVolumes(func(v *master_pb.VolumeInformationMessage) bool {
  114. if collection != "ALL_COLLECTIONS" {
  115. if v.Collection != collection {
  116. return false
  117. }
  118. }
  119. return v.ReadOnly || v.Size >= volumeSizeLimit
  120. })
  121. }
  122. if err := balanceSelectedVolume(commandEnv, nodes, sortReadOnlyVolumes, applyBalancing); err != nil {
  123. return err
  124. }
  125. return nil
  126. }
  127. func collectVolumeServersByType(t *master_pb.TopologyInfo, selectedDataCenter string) (typeToNodes map[uint64][]*Node) {
  128. typeToNodes = make(map[uint64][]*Node)
  129. for _, dc := range t.DataCenterInfos {
  130. if selectedDataCenter != "" && dc.Id != selectedDataCenter {
  131. continue
  132. }
  133. for _, r := range dc.RackInfos {
  134. for _, dn := range r.DataNodeInfos {
  135. typeToNodes[dn.MaxVolumeCount] = append(typeToNodes[dn.MaxVolumeCount], &Node{
  136. info: dn,
  137. dc: dc.Id,
  138. rack: r.Id,
  139. })
  140. }
  141. }
  142. }
  143. return
  144. }
  145. type Node struct {
  146. info *master_pb.DataNodeInfo
  147. selectedVolumes map[uint32]*master_pb.VolumeInformationMessage
  148. dc string
  149. rack string
  150. }
  151. func sortWritableVolumes(volumes []*master_pb.VolumeInformationMessage) {
  152. sort.Slice(volumes, func(i, j int) bool {
  153. return volumes[i].Size < volumes[j].Size
  154. })
  155. }
  156. func sortReadOnlyVolumes(volumes []*master_pb.VolumeInformationMessage) {
  157. sort.Slice(volumes, func(i, j int) bool {
  158. return volumes[i].Id < volumes[j].Id
  159. })
  160. }
  161. func balanceSelectedVolume(commandEnv *CommandEnv, nodes []*Node, sortCandidatesFn func(volumes []*master_pb.VolumeInformationMessage), applyBalancing bool) error {
  162. selectedVolumeCount := 0
  163. for _, dn := range nodes {
  164. selectedVolumeCount += len(dn.selectedVolumes)
  165. }
  166. idealSelectedVolumes := ceilDivide(selectedVolumeCount, len(nodes))
  167. hasMove := true
  168. for hasMove {
  169. hasMove = false
  170. sort.Slice(nodes, func(i, j int) bool {
  171. // TODO sort by free volume slots???
  172. return len(nodes[i].selectedVolumes) < len(nodes[j].selectedVolumes)
  173. })
  174. emptyNode, fullNode := nodes[0], nodes[len(nodes)-1]
  175. if len(fullNode.selectedVolumes) > idealSelectedVolumes && len(emptyNode.selectedVolumes)+1 <= idealSelectedVolumes {
  176. // sort the volumes to move
  177. var candidateVolumes []*master_pb.VolumeInformationMessage
  178. for _, v := range fullNode.selectedVolumes {
  179. candidateVolumes = append(candidateVolumes, v)
  180. }
  181. sortCandidatesFn(candidateVolumes)
  182. for _, v := range candidateVolumes {
  183. if v.ReplicaPlacement > 0 {
  184. if fullNode.dc != emptyNode.dc && fullNode.rack != emptyNode.rack {
  185. // TODO this logic is too simple, but should work most of the time
  186. // Need a correct algorithm to handle all different cases
  187. continue
  188. }
  189. }
  190. if _, found := emptyNode.selectedVolumes[v.Id]; !found {
  191. if err := moveVolume(commandEnv, v, fullNode, emptyNode, applyBalancing); err == nil {
  192. delete(fullNode.selectedVolumes, v.Id)
  193. emptyNode.selectedVolumes[v.Id] = v
  194. hasMove = true
  195. break
  196. } else {
  197. return err
  198. }
  199. }
  200. }
  201. }
  202. }
  203. return nil
  204. }
  205. func moveVolume(commandEnv *CommandEnv, v *master_pb.VolumeInformationMessage, fullNode *Node, emptyNode *Node, applyBalancing bool) error {
  206. collectionPrefix := v.Collection + "_"
  207. if v.Collection == "" {
  208. collectionPrefix = ""
  209. }
  210. fmt.Fprintf(os.Stdout, "moving volume %s%d %s => %s\n", collectionPrefix, v.Id, fullNode.info.Id, emptyNode.info.Id)
  211. if applyBalancing {
  212. return LiveMoveVolume(commandEnv.option.GrpcDialOption, needle.VolumeId(v.Id), fullNode.info.Id, emptyNode.info.Id, 5*time.Second)
  213. }
  214. return nil
  215. }
  216. func (node *Node) selectVolumes(fn func(v *master_pb.VolumeInformationMessage) bool) {
  217. node.selectedVolumes = make(map[uint32]*master_pb.VolumeInformationMessage)
  218. for _, v := range node.info.VolumeInfos {
  219. if fn(v) {
  220. node.selectedVolumes[v.Id] = v
  221. }
  222. }
  223. }