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.

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