command_volume_balance.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. package shell
  2. import (
  3. "flag"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/pb"
  6. "github.com/chrislusf/seaweedfs/weed/storage/super_block"
  7. "github.com/chrislusf/seaweedfs/weed/storage/types"
  8. "io"
  9. "os"
  10. "sort"
  11. "time"
  12. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  13. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  14. )
  15. func init() {
  16. Commands = append(Commands, &commandVolumeBalance{})
  17. }
  18. type commandVolumeBalance struct {
  19. }
  20. func (c *commandVolumeBalance) Name() string {
  21. return "volume.balance"
  22. }
  23. func (c *commandVolumeBalance) Help() string {
  24. return `balance all volumes among volume servers
  25. volume.balance [-collection ALL|EACH_COLLECTION|<collection_name>] [-force] [-dataCenter=<data_center_name>]
  26. Algorithm:
  27. For each type of volume server (different max volume count limit){
  28. for each collection {
  29. balanceWritableVolumes()
  30. balanceReadOnlyVolumes()
  31. }
  32. }
  33. func balanceWritableVolumes(){
  34. idealWritableVolumeRatio = totalWritableVolumes / totalNumberOfMaxVolumes
  35. for hasMovedOneVolume {
  36. sort all volume servers ordered by the localWritableVolumeRatio = localWritableVolumes to localVolumeMax
  37. pick the volume server B with the highest localWritableVolumeRatio y
  38. for any the volume server A with the number of writable volumes x + 1 <= idealWritableVolumeRatio * localVolumeMax {
  39. if y > localWritableVolumeRatio {
  40. if B has a writable volume id v that A does not have, and satisfy v replication requirements {
  41. move writable volume v from A to B
  42. }
  43. }
  44. }
  45. }
  46. }
  47. func balanceReadOnlyVolumes(){
  48. //similar to balanceWritableVolumes
  49. }
  50. `
  51. }
  52. func (c *commandVolumeBalance) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  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. if err = commandEnv.confirmIsLocked(args); err != nil {
  61. return
  62. }
  63. // collect topology information
  64. topologyInfo, volumeSizeLimitMb, err := collectTopologyInfo(commandEnv)
  65. if err != nil {
  66. return err
  67. }
  68. volumeServers := collectVolumeServersByDc(topologyInfo, *dc)
  69. volumeReplicas, _ := collectVolumeReplicaLocations(topologyInfo)
  70. diskTypes := collectVolumeDiskTypes(topologyInfo)
  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, diskTypes, volumeReplicas, volumeServers, volumeSizeLimitMb*1024*1024, c, *applyBalancing); err != nil {
  78. return err
  79. }
  80. }
  81. } else if *collection == "ALL_COLLECTIONS" {
  82. if err = balanceVolumeServers(commandEnv, diskTypes, volumeReplicas, volumeServers, volumeSizeLimitMb*1024*1024, "ALL_COLLECTIONS", *applyBalancing); err != nil {
  83. return err
  84. }
  85. } else {
  86. if err = balanceVolumeServers(commandEnv, diskTypes, volumeReplicas, volumeServers, volumeSizeLimitMb*1024*1024, *collection, *applyBalancing); err != nil {
  87. return err
  88. }
  89. }
  90. return nil
  91. }
  92. func balanceVolumeServers(commandEnv *CommandEnv, diskTypes []types.DiskType, volumeReplicas map[uint32][]*VolumeReplica, nodes []*Node, volumeSizeLimit uint64, collection string, applyBalancing bool) error {
  93. for _, diskType := range diskTypes {
  94. if err := balanceVolumeServersByDiskType(commandEnv, diskType, volumeReplicas, nodes, volumeSizeLimit, collection, applyBalancing); err != nil {
  95. return err
  96. }
  97. }
  98. return nil
  99. }
  100. func balanceVolumeServersByDiskType(commandEnv *CommandEnv, diskType types.DiskType, volumeReplicas map[uint32][]*VolumeReplica, nodes []*Node, volumeSizeLimit uint64, collection string, applyBalancing bool) error {
  101. for _, n := range nodes {
  102. n.selectVolumes(func(v *master_pb.VolumeInformationMessage) bool {
  103. if collection != "ALL_COLLECTIONS" {
  104. if v.Collection != collection {
  105. return false
  106. }
  107. }
  108. return v.DiskType == string(diskType)
  109. })
  110. }
  111. if err := balanceSelectedVolume(commandEnv, diskType, volumeReplicas, nodes, capacityByMaxVolumeCount(diskType), sortWritableVolumes, applyBalancing); err != nil {
  112. return err
  113. }
  114. return nil
  115. }
  116. func collectVolumeServersByDc(t *master_pb.TopologyInfo, selectedDataCenter string) (nodes []*Node) {
  117. for _, dc := range t.DataCenterInfos {
  118. if selectedDataCenter != "" && dc.Id != selectedDataCenter {
  119. continue
  120. }
  121. for _, r := range dc.RackInfos {
  122. for _, dn := range r.DataNodeInfos {
  123. nodes = append(nodes, &Node{
  124. info: dn,
  125. dc: dc.Id,
  126. rack: r.Id,
  127. })
  128. }
  129. }
  130. }
  131. return
  132. }
  133. func collectVolumeDiskTypes(t *master_pb.TopologyInfo) (diskTypes []types.DiskType) {
  134. knownTypes := make(map[string]bool)
  135. for _, dc := range t.DataCenterInfos {
  136. for _, r := range dc.RackInfos {
  137. for _, dn := range r.DataNodeInfos {
  138. for diskType, _ := range dn.DiskInfos {
  139. if _, found := knownTypes[diskType]; !found {
  140. knownTypes[diskType] = true
  141. }
  142. }
  143. }
  144. }
  145. }
  146. for diskType, _ := range knownTypes {
  147. diskTypes = append(diskTypes, types.ToDiskType(diskType))
  148. }
  149. return
  150. }
  151. type Node struct {
  152. info *master_pb.DataNodeInfo
  153. selectedVolumes map[uint32]*master_pb.VolumeInformationMessage
  154. dc string
  155. rack string
  156. }
  157. type CapacityFunc func(*master_pb.DataNodeInfo) int
  158. func capacityByMaxVolumeCount(diskType types.DiskType) CapacityFunc {
  159. return func(info *master_pb.DataNodeInfo) int {
  160. diskInfo, found := info.DiskInfos[string(diskType)]
  161. if !found {
  162. return 0
  163. }
  164. return int(diskInfo.MaxVolumeCount)
  165. }
  166. }
  167. func capacityByFreeVolumeCount(diskType types.DiskType) CapacityFunc {
  168. return func(info *master_pb.DataNodeInfo) int {
  169. diskInfo, found := info.DiskInfos[string(diskType)]
  170. if !found {
  171. return 0
  172. }
  173. return int(diskInfo.MaxVolumeCount - diskInfo.VolumeCount)
  174. }
  175. }
  176. func (n *Node) localVolumeRatio(capacityFunc CapacityFunc) float64 {
  177. return divide(len(n.selectedVolumes), capacityFunc(n.info))
  178. }
  179. func (n *Node) localVolumeNextRatio(capacityFunc CapacityFunc) float64 {
  180. return divide(len(n.selectedVolumes)+1, capacityFunc(n.info))
  181. }
  182. func (n *Node) selectVolumes(fn func(v *master_pb.VolumeInformationMessage) bool) {
  183. n.selectedVolumes = make(map[uint32]*master_pb.VolumeInformationMessage)
  184. for _, diskInfo := range n.info.DiskInfos {
  185. for _, v := range diskInfo.VolumeInfos {
  186. if fn(v) {
  187. n.selectedVolumes[v.Id] = v
  188. }
  189. }
  190. }
  191. }
  192. func sortWritableVolumes(volumes []*master_pb.VolumeInformationMessage) {
  193. sort.Slice(volumes, func(i, j int) bool {
  194. return volumes[i].Size < volumes[j].Size
  195. })
  196. }
  197. func sortReadOnlyVolumes(volumes []*master_pb.VolumeInformationMessage) {
  198. sort.Slice(volumes, func(i, j int) bool {
  199. return volumes[i].Id < volumes[j].Id
  200. })
  201. }
  202. func balanceSelectedVolume(commandEnv *CommandEnv, diskType types.DiskType, volumeReplicas map[uint32][]*VolumeReplica, nodes []*Node, capacityFunc CapacityFunc, sortCandidatesFn func(volumes []*master_pb.VolumeInformationMessage), applyBalancing bool) (err error) {
  203. selectedVolumeCount, volumeMaxCount := 0, 0
  204. var nodesWithCapacity []*Node
  205. for _, dn := range nodes {
  206. selectedVolumeCount += len(dn.selectedVolumes)
  207. capacity := capacityFunc(dn.info)
  208. if capacity > 0 {
  209. nodesWithCapacity = append(nodesWithCapacity, dn)
  210. }
  211. volumeMaxCount += capacity
  212. }
  213. idealVolumeRatio := divide(selectedVolumeCount, volumeMaxCount)
  214. hasMoved := true
  215. // fmt.Fprintf(os.Stdout, " total %d volumes, max %d volumes, idealVolumeRatio %f\n", selectedVolumeCount, volumeMaxCount, idealVolumeRatio)
  216. for hasMoved {
  217. hasMoved = false
  218. sort.Slice(nodesWithCapacity, func(i, j int) bool {
  219. return nodesWithCapacity[i].localVolumeRatio(capacityFunc) < nodesWithCapacity[j].localVolumeRatio(capacityFunc)
  220. })
  221. fullNode := nodesWithCapacity[len(nodesWithCapacity)-1]
  222. var candidateVolumes []*master_pb.VolumeInformationMessage
  223. for _, v := range fullNode.selectedVolumes {
  224. candidateVolumes = append(candidateVolumes, v)
  225. }
  226. sortCandidatesFn(candidateVolumes)
  227. for i := 0; i < len(nodesWithCapacity)-1; i++ {
  228. emptyNode := nodesWithCapacity[i]
  229. if !(fullNode.localVolumeRatio(capacityFunc) > idealVolumeRatio && emptyNode.localVolumeNextRatio(capacityFunc) <= idealVolumeRatio) {
  230. // no more volume servers with empty slots
  231. break
  232. }
  233. fmt.Fprintf(os.Stdout, "%s %.2f %.2f:%.2f\t", diskType.ReadableString(), idealVolumeRatio, fullNode.localVolumeRatio(capacityFunc), emptyNode.localVolumeNextRatio(capacityFunc))
  234. hasMoved, err = attemptToMoveOneVolume(commandEnv, volumeReplicas, fullNode, candidateVolumes, emptyNode, applyBalancing)
  235. if err != nil {
  236. return
  237. }
  238. if hasMoved {
  239. // moved one volume
  240. break
  241. }
  242. }
  243. }
  244. return nil
  245. }
  246. func attemptToMoveOneVolume(commandEnv *CommandEnv, volumeReplicas map[uint32][]*VolumeReplica, fullNode *Node, candidateVolumes []*master_pb.VolumeInformationMessage, emptyNode *Node, applyBalancing bool) (hasMoved bool, err error) {
  247. for _, v := range candidateVolumes {
  248. hasMoved, err = maybeMoveOneVolume(commandEnv, volumeReplicas, fullNode, v, emptyNode, applyBalancing)
  249. if err != nil {
  250. return
  251. }
  252. if hasMoved {
  253. break
  254. }
  255. }
  256. return
  257. }
  258. func maybeMoveOneVolume(commandEnv *CommandEnv, volumeReplicas map[uint32][]*VolumeReplica, fullNode *Node, candidateVolume *master_pb.VolumeInformationMessage, emptyNode *Node, applyChange bool) (hasMoved bool, err error) {
  259. if candidateVolume.ReplicaPlacement > 0 {
  260. replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(candidateVolume.ReplicaPlacement))
  261. if !isGoodMove(replicaPlacement, volumeReplicas[candidateVolume.Id], fullNode, emptyNode) {
  262. return false, nil
  263. }
  264. }
  265. if _, found := emptyNode.selectedVolumes[candidateVolume.Id]; !found {
  266. if err = moveVolume(commandEnv, candidateVolume, fullNode, emptyNode, applyChange); err == nil {
  267. adjustAfterMove(candidateVolume, volumeReplicas, fullNode, emptyNode)
  268. return true, nil
  269. } else {
  270. return
  271. }
  272. }
  273. return
  274. }
  275. func moveVolume(commandEnv *CommandEnv, v *master_pb.VolumeInformationMessage, fullNode *Node, emptyNode *Node, applyChange bool) error {
  276. collectionPrefix := v.Collection + "_"
  277. if v.Collection == "" {
  278. collectionPrefix = ""
  279. }
  280. fmt.Fprintf(os.Stdout, " moving %s volume %s%d %s => %s\n", v.DiskType, collectionPrefix, v.Id, fullNode.info.Id, emptyNode.info.Id)
  281. if applyChange {
  282. return LiveMoveVolume(commandEnv.option.GrpcDialOption, os.Stderr, needle.VolumeId(v.Id), pb.NewServerAddressFromDataNode(fullNode.info), pb.NewServerAddressFromDataNode(emptyNode.info), 5*time.Second, v.DiskType, false)
  283. }
  284. return nil
  285. }
  286. func isGoodMove(placement *super_block.ReplicaPlacement, existingReplicas []*VolumeReplica, sourceNode, targetNode *Node) bool {
  287. for _, replica := range existingReplicas {
  288. if replica.location.dataNode.Id == targetNode.info.Id &&
  289. replica.location.rack == targetNode.rack &&
  290. replica.location.dc == targetNode.dc {
  291. // never move to existing nodes
  292. return false
  293. }
  294. }
  295. dcs, racks := make(map[string]bool), make(map[string]int)
  296. for _, replica := range existingReplicas {
  297. if replica.location.dataNode.Id != sourceNode.info.Id {
  298. dcs[replica.location.DataCenter()] = true
  299. racks[replica.location.Rack()]++
  300. }
  301. }
  302. dcs[targetNode.dc] = true
  303. racks[fmt.Sprintf("%s %s", targetNode.dc, targetNode.rack)]++
  304. if len(dcs) != placement.DiffDataCenterCount+1 {
  305. return false
  306. }
  307. if len(racks) != placement.DiffRackCount+placement.DiffDataCenterCount+1 {
  308. return false
  309. }
  310. for _, sameRackCount := range racks {
  311. if sameRackCount != placement.SameRackCount+1 {
  312. return false
  313. }
  314. }
  315. return true
  316. }
  317. func adjustAfterMove(v *master_pb.VolumeInformationMessage, volumeReplicas map[uint32][]*VolumeReplica, fullNode *Node, emptyNode *Node) {
  318. delete(fullNode.selectedVolumes, v.Id)
  319. if emptyNode.selectedVolumes != nil {
  320. emptyNode.selectedVolumes[v.Id] = v
  321. }
  322. existingReplicas := volumeReplicas[v.Id]
  323. for _, replica := range existingReplicas {
  324. if replica.location.dataNode.Id == fullNode.info.Id &&
  325. replica.location.rack == fullNode.rack &&
  326. replica.location.dc == fullNode.dc {
  327. loc := newLocation(emptyNode.dc, emptyNode.rack, emptyNode.info)
  328. replica.location = &loc
  329. return
  330. }
  331. }
  332. }