command_volume_balance.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. package shell
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "github.com/chrislusf/seaweedfs/weed/storage/super_block"
  7. "io"
  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 [-collection 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. idealWritableVolumeRatio = totalWritableVolumes / totalNumberOfMaxVolumes
  34. for hasMovedOneVolume {
  35. sort all volume servers ordered by the localWritableVolumeRatio = localWritableVolumes to localVolumeMax
  36. pick the volume server B with the highest localWritableVolumeRatio y
  37. for any the volume server A with the number of writable volumes x + 1 <= idealWritableVolumeRatio * localVolumeMax {
  38. if y > localWritableVolumeRatio {
  39. if B has a writable volume id v that A does not have, and satisfy v replication requirements {
  40. move writable volume v from A to B
  41. }
  42. }
  43. }
  44. }
  45. }
  46. func balanceReadOnlyVolumes(){
  47. //similar to balanceWritableVolumes
  48. }
  49. `
  50. }
  51. func (c *commandVolumeBalance) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  52. if err = commandEnv.confirmIsLocked(); err != nil {
  53. return
  54. }
  55. balanceCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
  56. collection := balanceCommand.String("collection", "EACH_COLLECTION", "collection name, or use \"ALL_COLLECTIONS\" across collections, \"EACH_COLLECTION\" for each collection")
  57. dc := balanceCommand.String("dataCenter", "", "only apply the balancing for this dataCenter")
  58. applyBalancing := balanceCommand.Bool("force", false, "apply the balancing plan.")
  59. if err = balanceCommand.Parse(args); err != nil {
  60. return nil
  61. }
  62. var resp *master_pb.VolumeListResponse
  63. err = commandEnv.MasterClient.WithClient(func(client master_pb.SeaweedClient) error {
  64. resp, err = client.VolumeList(context.Background(), &master_pb.VolumeListRequest{})
  65. return err
  66. })
  67. if err != nil {
  68. return err
  69. }
  70. volumeServers := collectVolumeServersByDc(resp.TopologyInfo, *dc)
  71. volumeReplicas, _ := collectVolumeReplicaLocations(resp)
  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, volumeReplicas, 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, volumeReplicas, volumeServers, resp.VolumeSizeLimitMb*1024*1024, "ALL_COLLECTIONS", *applyBalancing); err != nil {
  84. return err
  85. }
  86. } else {
  87. if err = balanceVolumeServers(commandEnv, volumeReplicas, volumeServers, resp.VolumeSizeLimitMb*1024*1024, *collection, *applyBalancing); err != nil {
  88. return err
  89. }
  90. }
  91. return nil
  92. }
  93. func balanceVolumeServers(commandEnv *CommandEnv, volumeReplicas map[uint32][]*VolumeReplica, nodes []*Node, volumeSizeLimit uint64, collection string, applyBalancing bool) error {
  94. // balance writable volumes
  95. for _, n := range nodes {
  96. n.selectVolumes(func(v *master_pb.VolumeInformationMessage) bool {
  97. if collection != "ALL_COLLECTIONS" {
  98. if v.Collection != collection {
  99. return false
  100. }
  101. }
  102. return !v.ReadOnly && v.Size < volumeSizeLimit
  103. })
  104. }
  105. if err := balanceSelectedVolume(commandEnv, volumeReplicas, nodes, sortWritableVolumes, applyBalancing); err != nil {
  106. return err
  107. }
  108. // balance readable volumes
  109. for _, n := range nodes {
  110. n.selectVolumes(func(v *master_pb.VolumeInformationMessage) bool {
  111. if collection != "ALL_COLLECTIONS" {
  112. if v.Collection != collection {
  113. return false
  114. }
  115. }
  116. return v.ReadOnly || v.Size >= volumeSizeLimit
  117. })
  118. }
  119. if err := balanceSelectedVolume(commandEnv, volumeReplicas, nodes, sortReadOnlyVolumes, applyBalancing); err != nil {
  120. return err
  121. }
  122. return nil
  123. }
  124. func collectVolumeServersByDc(t *master_pb.TopologyInfo, selectedDataCenter string) (nodes []*Node) {
  125. for _, dc := range t.DataCenterInfos {
  126. if selectedDataCenter != "" && dc.Id != selectedDataCenter {
  127. continue
  128. }
  129. for _, r := range dc.RackInfos {
  130. for _, dn := range r.DataNodeInfos {
  131. nodes = append(nodes, &Node{
  132. info: dn,
  133. dc: dc.Id,
  134. rack: r.Id,
  135. })
  136. }
  137. }
  138. }
  139. return
  140. }
  141. type Node struct {
  142. info *master_pb.DataNodeInfo
  143. selectedVolumes map[uint32]*master_pb.VolumeInformationMessage
  144. dc string
  145. rack string
  146. }
  147. func (n *Node) localVolumeRatio() float64 {
  148. return divide(len(n.selectedVolumes), int(n.info.MaxVolumeCount))
  149. }
  150. func (n *Node) localVolumeNextRatio() float64 {
  151. return divide(len(n.selectedVolumes)+1, int(n.info.MaxVolumeCount))
  152. }
  153. func (n *Node) selectVolumes(fn func(v *master_pb.VolumeInformationMessage) bool) {
  154. n.selectedVolumes = make(map[uint32]*master_pb.VolumeInformationMessage)
  155. for _, v := range n.info.VolumeInfos {
  156. if fn(v) {
  157. n.selectedVolumes[v.Id] = v
  158. }
  159. }
  160. }
  161. func sortWritableVolumes(volumes []*master_pb.VolumeInformationMessage) {
  162. sort.Slice(volumes, func(i, j int) bool {
  163. return volumes[i].Size < volumes[j].Size
  164. })
  165. }
  166. func sortReadOnlyVolumes(volumes []*master_pb.VolumeInformationMessage) {
  167. sort.Slice(volumes, func(i, j int) bool {
  168. return volumes[i].Id < volumes[j].Id
  169. })
  170. }
  171. func balanceSelectedVolume(commandEnv *CommandEnv, volumeReplicas map[uint32][]*VolumeReplica, nodes []*Node, sortCandidatesFn func(volumes []*master_pb.VolumeInformationMessage), applyBalancing bool) (err error) {
  172. selectedVolumeCount, volumeMaxCount := 0, 0
  173. for _, dn := range nodes {
  174. selectedVolumeCount += len(dn.selectedVolumes)
  175. volumeMaxCount += int(dn.info.MaxVolumeCount)
  176. }
  177. idealVolumeRatio := divide(selectedVolumeCount, volumeMaxCount)
  178. hasMoved := true
  179. for hasMoved {
  180. hasMoved = false
  181. sort.Slice(nodes, func(i, j int) bool {
  182. return nodes[i].localVolumeRatio() < nodes[j].localVolumeRatio()
  183. })
  184. fullNode := nodes[len(nodes)-1]
  185. var candidateVolumes []*master_pb.VolumeInformationMessage
  186. for _, v := range fullNode.selectedVolumes {
  187. candidateVolumes = append(candidateVolumes, v)
  188. }
  189. sortCandidatesFn(candidateVolumes)
  190. for i := 0; i < len(nodes)-1; i++ {
  191. emptyNode := nodes[i]
  192. if !(fullNode.localVolumeRatio() > idealVolumeRatio && emptyNode.localVolumeNextRatio() <= idealVolumeRatio) {
  193. // no more volume servers with empty slots
  194. break
  195. }
  196. hasMoved, err = attemptToMoveOneVolume(commandEnv, volumeReplicas, fullNode, candidateVolumes, emptyNode, applyBalancing)
  197. if err != nil {
  198. return
  199. }
  200. if hasMoved {
  201. // moved one volume
  202. break
  203. }
  204. }
  205. }
  206. return nil
  207. }
  208. func attemptToMoveOneVolume(commandEnv *CommandEnv, volumeReplicas map[uint32][]*VolumeReplica, fullNode *Node, candidateVolumes []*master_pb.VolumeInformationMessage, emptyNode *Node, applyBalancing bool) (hasMoved bool, err error) {
  209. for _, v := range candidateVolumes {
  210. hasMoved, err = maybeMoveOneVolume(commandEnv, volumeReplicas, fullNode, v, emptyNode, applyBalancing)
  211. if err != nil {
  212. return
  213. }
  214. if hasMoved {
  215. break
  216. }
  217. }
  218. return
  219. }
  220. func maybeMoveOneVolume(commandEnv *CommandEnv, volumeReplicas map[uint32][]*VolumeReplica, fullNode *Node, candidateVolume *master_pb.VolumeInformationMessage, emptyNode *Node, applyChange bool) (hasMoved bool, err error) {
  221. if candidateVolume.ReplicaPlacement > 0 {
  222. replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(candidateVolume.ReplicaPlacement))
  223. if !isGoodMove(replicaPlacement, volumeReplicas[candidateVolume.Id], fullNode, emptyNode) {
  224. return false, nil
  225. }
  226. }
  227. if _, found := emptyNode.selectedVolumes[candidateVolume.Id]; !found {
  228. if err = moveVolume(commandEnv, candidateVolume, fullNode, emptyNode, applyChange); err == nil {
  229. adjustAfterMove(candidateVolume, volumeReplicas, fullNode, emptyNode)
  230. return true, nil
  231. } else {
  232. return
  233. }
  234. }
  235. return
  236. }
  237. func moveVolume(commandEnv *CommandEnv, v *master_pb.VolumeInformationMessage, fullNode *Node, emptyNode *Node, applyChange bool) error {
  238. collectionPrefix := v.Collection + "_"
  239. if v.Collection == "" {
  240. collectionPrefix = ""
  241. }
  242. fmt.Fprintf(os.Stdout, "moving volume %s%d %s => %s\n", collectionPrefix, v.Id, fullNode.info.Id, emptyNode.info.Id)
  243. if applyChange {
  244. return LiveMoveVolume(commandEnv.option.GrpcDialOption, needle.VolumeId(v.Id), fullNode.info.Id, emptyNode.info.Id, 5*time.Second)
  245. }
  246. return nil
  247. }
  248. func isGoodMove(placement *super_block.ReplicaPlacement, existingReplicas []*VolumeReplica, sourceNode, targetNode *Node) bool {
  249. for _, replica := range existingReplicas {
  250. if replica.location.dataNode.Id == targetNode.info.Id &&
  251. replica.location.rack == targetNode.rack &&
  252. replica.location.dc == targetNode.dc {
  253. // never move to existing nodes
  254. return false
  255. }
  256. }
  257. dcs, racks := make(map[string]bool), make(map[string]int)
  258. for _, replica := range existingReplicas {
  259. if replica.location.dataNode.Id != sourceNode.info.Id {
  260. dcs[replica.location.DataCenter()] = true
  261. racks[replica.location.Rack()]++
  262. }
  263. }
  264. dcs[targetNode.dc] = true
  265. racks[fmt.Sprintf("%s %s", targetNode.dc, targetNode.rack)]++
  266. if len(dcs) > placement.DiffDataCenterCount+1 {
  267. return false
  268. }
  269. if len(racks) > placement.DiffRackCount+placement.DiffDataCenterCount+1 {
  270. return false
  271. }
  272. for _, sameRackCount := range racks {
  273. if sameRackCount > placement.SameRackCount+1 {
  274. return false
  275. }
  276. }
  277. return true
  278. }
  279. func adjustAfterMove(v *master_pb.VolumeInformationMessage, volumeReplicas map[uint32][]*VolumeReplica, fullNode *Node, emptyNode *Node) {
  280. delete(fullNode.selectedVolumes, v.Id)
  281. if emptyNode.selectedVolumes != nil {
  282. emptyNode.selectedVolumes[v.Id] = v
  283. }
  284. existingReplicas := volumeReplicas[v.Id]
  285. for _, replica := range existingReplicas {
  286. if replica.location.dataNode.Id == fullNode.info.Id &&
  287. replica.location.rack == fullNode.rack &&
  288. replica.location.dc == fullNode.dc {
  289. replica.location.dc = emptyNode.dc
  290. replica.location.rack = emptyNode.rack
  291. replica.location.dataNode = emptyNode.info
  292. return
  293. }
  294. }
  295. }