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.

389 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
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/seaweedfs/seaweedfs/weed/pb"
  6. "github.com/seaweedfs/seaweedfs/weed/storage/super_block"
  7. "github.com/seaweedfs/seaweedfs/weed/storage/types"
  8. "golang.org/x/exp/slices"
  9. "io"
  10. "os"
  11. "time"
  12. "github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
  13. "github.com/seaweedfs/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. infoAboutSimulationMode(writer, *applyBalancing, "-force")
  61. if err = commandEnv.confirmIsLocked(args); err != nil {
  62. return
  63. }
  64. // collect topology information
  65. topologyInfo, volumeSizeLimitMb, err := collectTopologyInfo(commandEnv, 15*time.Second)
  66. if err != nil {
  67. return err
  68. }
  69. volumeServers := collectVolumeServersByDc(topologyInfo, *dc)
  70. volumeReplicas, _ := collectVolumeReplicaLocations(topologyInfo)
  71. diskTypes := collectVolumeDiskTypes(topologyInfo)
  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, diskTypes, volumeReplicas, volumeServers, volumeSizeLimitMb*1024*1024, c, *applyBalancing); err != nil {
  79. return err
  80. }
  81. }
  82. } else if *collection == "ALL_COLLECTIONS" {
  83. if err = balanceVolumeServers(commandEnv, diskTypes, volumeReplicas, volumeServers, volumeSizeLimitMb*1024*1024, "ALL_COLLECTIONS", *applyBalancing); err != nil {
  84. return err
  85. }
  86. } else {
  87. if err = balanceVolumeServers(commandEnv, diskTypes, volumeReplicas, volumeServers, volumeSizeLimitMb*1024*1024, *collection, *applyBalancing); err != nil {
  88. return err
  89. }
  90. }
  91. return nil
  92. }
  93. func balanceVolumeServers(commandEnv *CommandEnv, diskTypes []types.DiskType, volumeReplicas map[uint32][]*VolumeReplica, nodes []*Node, volumeSizeLimit uint64, collection string, applyBalancing bool) error {
  94. for _, diskType := range diskTypes {
  95. if err := balanceVolumeServersByDiskType(commandEnv, diskType, volumeReplicas, nodes, volumeSizeLimit, collection, applyBalancing); err != nil {
  96. return err
  97. }
  98. }
  99. return nil
  100. }
  101. func balanceVolumeServersByDiskType(commandEnv *CommandEnv, diskType types.DiskType, volumeReplicas map[uint32][]*VolumeReplica, nodes []*Node, volumeSizeLimit uint64, collection string, applyBalancing bool) error {
  102. for _, n := range nodes {
  103. n.selectVolumes(func(v *master_pb.VolumeInformationMessage) bool {
  104. if collection != "ALL_COLLECTIONS" {
  105. if v.Collection != collection {
  106. return false
  107. }
  108. }
  109. return v.DiskType == string(diskType)
  110. })
  111. }
  112. if err := balanceSelectedVolume(commandEnv, diskType, volumeReplicas, nodes, capacityByMaxVolumeCount(diskType), sortWritableVolumes, applyBalancing); err != nil {
  113. return err
  114. }
  115. return nil
  116. }
  117. func collectVolumeServersByDc(t *master_pb.TopologyInfo, selectedDataCenter string) (nodes []*Node) {
  118. for _, dc := range t.DataCenterInfos {
  119. if selectedDataCenter != "" && dc.Id != selectedDataCenter {
  120. continue
  121. }
  122. for _, r := range dc.RackInfos {
  123. for _, dn := range r.DataNodeInfos {
  124. nodes = append(nodes, &Node{
  125. info: dn,
  126. dc: dc.Id,
  127. rack: r.Id,
  128. })
  129. }
  130. }
  131. }
  132. return
  133. }
  134. func collectVolumeDiskTypes(t *master_pb.TopologyInfo) (diskTypes []types.DiskType) {
  135. knownTypes := make(map[string]bool)
  136. for _, dc := range t.DataCenterInfos {
  137. for _, r := range dc.RackInfos {
  138. for _, dn := range r.DataNodeInfos {
  139. for diskType, _ := range dn.DiskInfos {
  140. if _, found := knownTypes[diskType]; !found {
  141. knownTypes[diskType] = true
  142. }
  143. }
  144. }
  145. }
  146. }
  147. for diskType, _ := range knownTypes {
  148. diskTypes = append(diskTypes, types.ToDiskType(diskType))
  149. }
  150. return
  151. }
  152. type Node struct {
  153. info *master_pb.DataNodeInfo
  154. selectedVolumes map[uint32]*master_pb.VolumeInformationMessage
  155. dc string
  156. rack string
  157. }
  158. type CapacityFunc func(*master_pb.DataNodeInfo) int
  159. func capacityByMaxVolumeCount(diskType types.DiskType) CapacityFunc {
  160. return func(info *master_pb.DataNodeInfo) int {
  161. diskInfo, found := info.DiskInfos[string(diskType)]
  162. if !found {
  163. return 0
  164. }
  165. return int(diskInfo.MaxVolumeCount)
  166. }
  167. }
  168. func capacityByFreeVolumeCount(diskType types.DiskType) CapacityFunc {
  169. return func(info *master_pb.DataNodeInfo) int {
  170. diskInfo, found := info.DiskInfos[string(diskType)]
  171. if !found {
  172. return 0
  173. }
  174. return int(diskInfo.MaxVolumeCount - diskInfo.VolumeCount)
  175. }
  176. }
  177. func (n *Node) localVolumeRatio(capacityFunc CapacityFunc) float64 {
  178. return divide(len(n.selectedVolumes), capacityFunc(n.info))
  179. }
  180. func (n *Node) localVolumeNextRatio(capacityFunc CapacityFunc) float64 {
  181. return divide(len(n.selectedVolumes)+1, capacityFunc(n.info))
  182. }
  183. func (n *Node) selectVolumes(fn func(v *master_pb.VolumeInformationMessage) bool) {
  184. n.selectedVolumes = make(map[uint32]*master_pb.VolumeInformationMessage)
  185. for _, diskInfo := range n.info.DiskInfos {
  186. for _, v := range diskInfo.VolumeInfos {
  187. if fn(v) {
  188. n.selectedVolumes[v.Id] = v
  189. }
  190. }
  191. }
  192. }
  193. func sortWritableVolumes(volumes []*master_pb.VolumeInformationMessage) {
  194. slices.SortFunc(volumes, func(a, b *master_pb.VolumeInformationMessage) bool {
  195. return a.Size < b.Size
  196. })
  197. }
  198. 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) {
  199. selectedVolumeCount, volumeMaxCount := 0, 0
  200. var nodesWithCapacity []*Node
  201. for _, dn := range nodes {
  202. selectedVolumeCount += len(dn.selectedVolumes)
  203. capacity := capacityFunc(dn.info)
  204. if capacity > 0 {
  205. nodesWithCapacity = append(nodesWithCapacity, dn)
  206. }
  207. volumeMaxCount += capacity
  208. }
  209. idealVolumeRatio := divide(selectedVolumeCount, volumeMaxCount)
  210. hasMoved := true
  211. // fmt.Fprintf(os.Stdout, " total %d volumes, max %d volumes, idealVolumeRatio %f\n", selectedVolumeCount, volumeMaxCount, idealVolumeRatio)
  212. for hasMoved {
  213. hasMoved = false
  214. slices.SortFunc(nodesWithCapacity, func(a, b *Node) bool {
  215. return a.localVolumeRatio(capacityFunc) < b.localVolumeRatio(capacityFunc)
  216. })
  217. if len(nodesWithCapacity) == 0 {
  218. fmt.Printf("no volume server found with capacity for %s", diskType.ReadableString())
  219. return nil
  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 !commandEnv.isLocked() {
  260. return false, fmt.Errorf("lock is lost")
  261. }
  262. if candidateVolume.ReplicaPlacement > 0 {
  263. replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(candidateVolume.ReplicaPlacement))
  264. if !isGoodMove(replicaPlacement, volumeReplicas[candidateVolume.Id], fullNode, emptyNode) {
  265. return false, nil
  266. }
  267. }
  268. if _, found := emptyNode.selectedVolumes[candidateVolume.Id]; !found {
  269. if err = moveVolume(commandEnv, candidateVolume, fullNode, emptyNode, applyChange); err == nil {
  270. adjustAfterMove(candidateVolume, volumeReplicas, fullNode, emptyNode)
  271. return true, nil
  272. } else {
  273. return
  274. }
  275. }
  276. return
  277. }
  278. func moveVolume(commandEnv *CommandEnv, v *master_pb.VolumeInformationMessage, fullNode *Node, emptyNode *Node, applyChange bool) error {
  279. collectionPrefix := v.Collection + "_"
  280. if v.Collection == "" {
  281. collectionPrefix = ""
  282. }
  283. fmt.Fprintf(os.Stdout, " moving %s volume %s%d %s => %s\n", v.DiskType, collectionPrefix, v.Id, fullNode.info.Id, emptyNode.info.Id)
  284. if applyChange {
  285. return LiveMoveVolume(commandEnv.option.GrpcDialOption, os.Stderr, needle.VolumeId(v.Id), pb.NewServerAddressFromDataNode(fullNode.info), pb.NewServerAddressFromDataNode(emptyNode.info), 5*time.Second, v.DiskType, 0, false)
  286. }
  287. return nil
  288. }
  289. func isGoodMove(placement *super_block.ReplicaPlacement, existingReplicas []*VolumeReplica, sourceNode, targetNode *Node) bool {
  290. for _, replica := range existingReplicas {
  291. if replica.location.dataNode.Id == targetNode.info.Id &&
  292. replica.location.rack == targetNode.rack &&
  293. replica.location.dc == targetNode.dc {
  294. // never move to existing nodes
  295. return false
  296. }
  297. }
  298. dcs, racks := make(map[string]bool), make(map[string]int)
  299. for _, replica := range existingReplicas {
  300. if replica.location.dataNode.Id != sourceNode.info.Id {
  301. dcs[replica.location.DataCenter()] = true
  302. racks[replica.location.Rack()]++
  303. }
  304. }
  305. dcs[targetNode.dc] = true
  306. racks[fmt.Sprintf("%s %s", targetNode.dc, targetNode.rack)]++
  307. if len(dcs) != placement.DiffDataCenterCount+1 {
  308. return false
  309. }
  310. if len(racks) != placement.DiffRackCount+placement.DiffDataCenterCount+1 {
  311. return false
  312. }
  313. for _, sameRackCount := range racks {
  314. if sameRackCount != placement.SameRackCount+1 {
  315. return false
  316. }
  317. }
  318. return true
  319. }
  320. func adjustAfterMove(v *master_pb.VolumeInformationMessage, volumeReplicas map[uint32][]*VolumeReplica, fullNode *Node, emptyNode *Node) {
  321. delete(fullNode.selectedVolumes, v.Id)
  322. if emptyNode.selectedVolumes != nil {
  323. emptyNode.selectedVolumes[v.Id] = v
  324. }
  325. existingReplicas := volumeReplicas[v.Id]
  326. for _, replica := range existingReplicas {
  327. if replica.location.dataNode.Id == fullNode.info.Id &&
  328. replica.location.rack == fullNode.rack &&
  329. replica.location.dc == fullNode.dc {
  330. loc := newLocation(emptyNode.dc, emptyNode.rack, emptyNode.info)
  331. replica.location = &loc
  332. return
  333. }
  334. }
  335. }