You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

386 lines
12 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package shell
  2. import (
  3. "flag"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/storage/super_block"
  6. "github.com/chrislusf/seaweedfs/weed/storage/types"
  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. // collect topology information
  63. topologyInfo, volumeSizeLimitMb, err := collectTopologyInfo(commandEnv)
  64. if err != nil {
  65. return err
  66. }
  67. volumeServers := collectVolumeServersByDc(topologyInfo, *dc)
  68. volumeReplicas, _ := collectVolumeReplicaLocations(topologyInfo)
  69. diskTypes := collectVolumeDiskTypes(topologyInfo)
  70. if *collection == "EACH_COLLECTION" {
  71. collections, err := ListCollectionNames(commandEnv, true, false)
  72. if err != nil {
  73. return err
  74. }
  75. for _, c := range collections {
  76. if err = balanceVolumeServers(commandEnv, diskTypes, volumeReplicas, volumeServers, volumeSizeLimitMb*1024*1024, c, *applyBalancing); err != nil {
  77. return err
  78. }
  79. }
  80. } else if *collection == "ALL_COLLECTIONS" {
  81. if err = balanceVolumeServers(commandEnv, diskTypes, volumeReplicas, volumeServers, volumeSizeLimitMb*1024*1024, "ALL_COLLECTIONS", *applyBalancing); err != nil {
  82. return err
  83. }
  84. } else {
  85. if err = balanceVolumeServers(commandEnv, diskTypes, volumeReplicas, volumeServers, volumeSizeLimitMb*1024*1024, *collection, *applyBalancing); err != nil {
  86. return err
  87. }
  88. }
  89. return nil
  90. }
  91. func balanceVolumeServers(commandEnv *CommandEnv, diskTypes []types.DiskType, volumeReplicas map[uint32][]*VolumeReplica, nodes []*Node, volumeSizeLimit uint64, collection string, applyBalancing bool) error {
  92. for _, diskType := range diskTypes {
  93. if err := balanceVolumeServersByDiskType(commandEnv, diskType, volumeReplicas, nodes, volumeSizeLimit, collection, applyBalancing); err != nil {
  94. return err
  95. }
  96. }
  97. return nil
  98. }
  99. func balanceVolumeServersByDiskType(commandEnv *CommandEnv, diskType types.DiskType, volumeReplicas map[uint32][]*VolumeReplica, nodes []*Node, volumeSizeLimit uint64, collection string, applyBalancing bool) error {
  100. for _, n := range nodes {
  101. n.selectVolumes(func(v *master_pb.VolumeInformationMessage) bool {
  102. if collection != "ALL_COLLECTIONS" {
  103. if v.Collection != collection {
  104. return false
  105. }
  106. }
  107. return v.DiskType == string(diskType)
  108. })
  109. }
  110. if err := balanceSelectedVolume(commandEnv, diskType, volumeReplicas, nodes, capacityByMaxVolumeCount(diskType), sortWritableVolumes, applyBalancing); err != nil {
  111. return err
  112. }
  113. return nil
  114. }
  115. func collectVolumeServersByDc(t *master_pb.TopologyInfo, selectedDataCenter string) (nodes []*Node) {
  116. for _, dc := range t.DataCenterInfos {
  117. if selectedDataCenter != "" && dc.Id != selectedDataCenter {
  118. continue
  119. }
  120. for _, r := range dc.RackInfos {
  121. for _, dn := range r.DataNodeInfos {
  122. nodes = append(nodes, &Node{
  123. info: dn,
  124. dc: dc.Id,
  125. rack: r.Id,
  126. })
  127. }
  128. }
  129. }
  130. return
  131. }
  132. func collectVolumeDiskTypes(t *master_pb.TopologyInfo) (diskTypes []types.DiskType) {
  133. knownTypes := make(map[string]bool)
  134. for _, dc := range t.DataCenterInfos {
  135. for _, r := range dc.RackInfos {
  136. for _, dn := range r.DataNodeInfos {
  137. for diskType, _ := range dn.DiskInfos {
  138. if _, found := knownTypes[diskType]; !found {
  139. knownTypes[diskType] = true
  140. }
  141. }
  142. }
  143. }
  144. }
  145. for diskType, _ := range knownTypes {
  146. diskTypes = append(diskTypes, types.ToDiskType(diskType))
  147. }
  148. return
  149. }
  150. type Node struct {
  151. info *master_pb.DataNodeInfo
  152. selectedVolumes map[uint32]*master_pb.VolumeInformationMessage
  153. dc string
  154. rack string
  155. }
  156. type CapacityFunc func(*master_pb.DataNodeInfo) int
  157. func capacityByMaxVolumeCount(diskType types.DiskType) CapacityFunc {
  158. return func(info *master_pb.DataNodeInfo) int {
  159. diskInfo, found := info.DiskInfos[string(diskType)]
  160. if !found {
  161. return 0
  162. }
  163. return int(diskInfo.MaxVolumeCount)
  164. }
  165. }
  166. func capacityByFreeVolumeCount(diskType types.DiskType) CapacityFunc {
  167. return func(info *master_pb.DataNodeInfo) int {
  168. diskInfo, found := info.DiskInfos[string(diskType)]
  169. if !found {
  170. return 0
  171. }
  172. return int(diskInfo.MaxVolumeCount - diskInfo.VolumeCount)
  173. }
  174. }
  175. func (n *Node) localVolumeRatio(capacityFunc CapacityFunc) float64 {
  176. return divide(len(n.selectedVolumes), capacityFunc(n.info))
  177. }
  178. func (n *Node) localVolumeNextRatio(capacityFunc CapacityFunc) float64 {
  179. return divide(len(n.selectedVolumes)+1, capacityFunc(n.info))
  180. }
  181. func (n *Node) selectVolumes(fn func(v *master_pb.VolumeInformationMessage) bool) {
  182. n.selectedVolumes = make(map[uint32]*master_pb.VolumeInformationMessage)
  183. for _, diskInfo := range n.info.DiskInfos {
  184. for _, v := range diskInfo.VolumeInfos {
  185. if fn(v) {
  186. n.selectedVolumes[v.Id] = v
  187. }
  188. }
  189. }
  190. }
  191. func sortWritableVolumes(volumes []*master_pb.VolumeInformationMessage) {
  192. sort.Slice(volumes, func(i, j int) bool {
  193. return volumes[i].Size < volumes[j].Size
  194. })
  195. }
  196. func sortReadOnlyVolumes(volumes []*master_pb.VolumeInformationMessage) {
  197. sort.Slice(volumes, func(i, j int) bool {
  198. return volumes[i].Id < volumes[j].Id
  199. })
  200. }
  201. 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) {
  202. selectedVolumeCount, volumeMaxCount := 0, 0
  203. var nodesWithCapacity []*Node
  204. for _, dn := range nodes {
  205. selectedVolumeCount += len(dn.selectedVolumes)
  206. capacity := capacityFunc(dn.info)
  207. if capacity > 0 {
  208. nodesWithCapacity = append(nodesWithCapacity, dn)
  209. }
  210. volumeMaxCount += capacity
  211. }
  212. idealVolumeRatio := divide(selectedVolumeCount, volumeMaxCount)
  213. hasMoved := true
  214. // fmt.Fprintf(os.Stdout, " total %d volumes, max %d volumes, idealVolumeRatio %f\n", selectedVolumeCount, volumeMaxCount, idealVolumeRatio)
  215. for hasMoved {
  216. hasMoved = false
  217. sort.Slice(nodesWithCapacity, func(i, j int) bool {
  218. return nodesWithCapacity[i].localVolumeRatio(capacityFunc) < nodesWithCapacity[j].localVolumeRatio(capacityFunc)
  219. })
  220. fullNode := nodesWithCapacity[len(nodesWithCapacity)-1]
  221. var candidateVolumes []*master_pb.VolumeInformationMessage
  222. for _, v := range fullNode.selectedVolumes {
  223. candidateVolumes = append(candidateVolumes, v)
  224. }
  225. sortCandidatesFn(candidateVolumes)
  226. for i := 0; i < len(nodesWithCapacity)-1; i++ {
  227. emptyNode := nodesWithCapacity[i]
  228. if !(fullNode.localVolumeRatio(capacityFunc) > idealVolumeRatio && emptyNode.localVolumeNextRatio(capacityFunc) <= idealVolumeRatio) {
  229. // no more volume servers with empty slots
  230. break
  231. }
  232. fmt.Fprintf(os.Stdout, "%s %.2f %.2f:%.2f\t", diskType.ReadableString(), idealVolumeRatio, fullNode.localVolumeRatio(capacityFunc), emptyNode.localVolumeNextRatio(capacityFunc))
  233. hasMoved, err = attemptToMoveOneVolume(commandEnv, volumeReplicas, fullNode, candidateVolumes, emptyNode, applyBalancing)
  234. if err != nil {
  235. return
  236. }
  237. if hasMoved {
  238. // moved one volume
  239. break
  240. }
  241. }
  242. }
  243. return nil
  244. }
  245. func attemptToMoveOneVolume(commandEnv *CommandEnv, volumeReplicas map[uint32][]*VolumeReplica, fullNode *Node, candidateVolumes []*master_pb.VolumeInformationMessage, emptyNode *Node, applyBalancing bool) (hasMoved bool, err error) {
  246. for _, v := range candidateVolumes {
  247. hasMoved, err = maybeMoveOneVolume(commandEnv, volumeReplicas, fullNode, v, emptyNode, applyBalancing)
  248. if err != nil {
  249. return
  250. }
  251. if hasMoved {
  252. break
  253. }
  254. }
  255. return
  256. }
  257. func maybeMoveOneVolume(commandEnv *CommandEnv, volumeReplicas map[uint32][]*VolumeReplica, fullNode *Node, candidateVolume *master_pb.VolumeInformationMessage, emptyNode *Node, applyChange bool) (hasMoved bool, err error) {
  258. if candidateVolume.ReplicaPlacement > 0 {
  259. replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(candidateVolume.ReplicaPlacement))
  260. if !isGoodMove(replicaPlacement, volumeReplicas[candidateVolume.Id], fullNode, emptyNode) {
  261. return false, nil
  262. }
  263. }
  264. if _, found := emptyNode.selectedVolumes[candidateVolume.Id]; !found {
  265. if err = moveVolume(commandEnv, candidateVolume, fullNode, emptyNode, applyChange); err == nil {
  266. adjustAfterMove(candidateVolume, volumeReplicas, fullNode, emptyNode)
  267. return true, nil
  268. } else {
  269. return
  270. }
  271. }
  272. return
  273. }
  274. func moveVolume(commandEnv *CommandEnv, v *master_pb.VolumeInformationMessage, fullNode *Node, emptyNode *Node, applyChange bool) error {
  275. collectionPrefix := v.Collection + "_"
  276. if v.Collection == "" {
  277. collectionPrefix = ""
  278. }
  279. fmt.Fprintf(os.Stdout, " moving %s volume %s%d %s => %s\n", v.DiskType, collectionPrefix, v.Id, fullNode.info.Id, emptyNode.info.Id)
  280. if applyChange {
  281. return LiveMoveVolume(commandEnv.option.GrpcDialOption, os.Stderr, needle.VolumeId(v.Id), fullNode.info.Id, emptyNode.info.Id, 5*time.Second, v.DiskType, false)
  282. }
  283. return nil
  284. }
  285. func isGoodMove(placement *super_block.ReplicaPlacement, existingReplicas []*VolumeReplica, sourceNode, targetNode *Node) bool {
  286. for _, replica := range existingReplicas {
  287. if replica.location.dataNode.Id == targetNode.info.Id &&
  288. replica.location.rack == targetNode.rack &&
  289. replica.location.dc == targetNode.dc {
  290. // never move to existing nodes
  291. return false
  292. }
  293. }
  294. dcs, racks := make(map[string]bool), make(map[string]int)
  295. for _, replica := range existingReplicas {
  296. if replica.location.dataNode.Id != sourceNode.info.Id {
  297. dcs[replica.location.DataCenter()] = true
  298. racks[replica.location.Rack()]++
  299. }
  300. }
  301. dcs[targetNode.dc] = true
  302. racks[fmt.Sprintf("%s %s", targetNode.dc, targetNode.rack)]++
  303. if len(dcs) != placement.DiffDataCenterCount+1 {
  304. return false
  305. }
  306. if len(racks) != placement.DiffRackCount+placement.DiffDataCenterCount+1 {
  307. return false
  308. }
  309. for _, sameRackCount := range racks {
  310. if sameRackCount != placement.SameRackCount+1 {
  311. return false
  312. }
  313. }
  314. return true
  315. }
  316. func adjustAfterMove(v *master_pb.VolumeInformationMessage, volumeReplicas map[uint32][]*VolumeReplica, fullNode *Node, emptyNode *Node) {
  317. delete(fullNode.selectedVolumes, v.Id)
  318. if emptyNode.selectedVolumes != nil {
  319. emptyNode.selectedVolumes[v.Id] = v
  320. }
  321. existingReplicas := volumeReplicas[v.Id]
  322. for _, replica := range existingReplicas {
  323. if replica.location.dataNode.Id == fullNode.info.Id &&
  324. replica.location.rack == fullNode.rack &&
  325. replica.location.dc == fullNode.dc {
  326. loc := newLocation(emptyNode.dc, emptyNode.rack, emptyNode.info)
  327. replica.location = &loc
  328. return
  329. }
  330. }
  331. }