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.

420 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
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/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", "ALL_COLLECTIONS", "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) isOneVolumeOnly() bool {
  184. if len(n.selectedVolumes) != 1 {
  185. return false
  186. }
  187. for _, disk := range n.info.DiskInfos {
  188. if disk.VolumeCount == 1 && disk.MaxVolumeCount == 1 {
  189. return true
  190. }
  191. }
  192. return false
  193. }
  194. func (n *Node) selectVolumes(fn func(v *master_pb.VolumeInformationMessage) bool) {
  195. n.selectedVolumes = make(map[uint32]*master_pb.VolumeInformationMessage)
  196. for _, diskInfo := range n.info.DiskInfos {
  197. for _, v := range diskInfo.VolumeInfos {
  198. if fn(v) {
  199. n.selectedVolumes[v.Id] = v
  200. }
  201. }
  202. }
  203. }
  204. func sortWritableVolumes(volumes []*master_pb.VolumeInformationMessage) {
  205. slices.SortFunc(volumes, func(a, b *master_pb.VolumeInformationMessage) bool {
  206. return a.Size < b.Size
  207. })
  208. }
  209. 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) {
  210. selectedVolumeCount, volumeMaxCount := 0, 0
  211. var nodesWithCapacity []*Node
  212. for _, dn := range nodes {
  213. selectedVolumeCount += len(dn.selectedVolumes)
  214. capacity := capacityFunc(dn.info)
  215. if capacity > 0 {
  216. nodesWithCapacity = append(nodesWithCapacity, dn)
  217. }
  218. volumeMaxCount += capacity
  219. }
  220. idealVolumeRatio := divide(selectedVolumeCount, volumeMaxCount)
  221. hasMoved := true
  222. // fmt.Fprintf(os.Stdout, " total %d volumes, max %d volumes, idealVolumeRatio %f\n", selectedVolumeCount, volumeMaxCount, idealVolumeRatio)
  223. for hasMoved {
  224. hasMoved = false
  225. slices.SortFunc(nodesWithCapacity, func(a, b *Node) bool {
  226. return a.localVolumeRatio(capacityFunc) < b.localVolumeRatio(capacityFunc)
  227. })
  228. if len(nodesWithCapacity) == 0 {
  229. fmt.Printf("no volume server found with capacity for %s", diskType.ReadableString())
  230. return nil
  231. }
  232. var fullNode *Node
  233. for fullNodeIndex := len(nodesWithCapacity) - 1; fullNodeIndex >= 0; fullNodeIndex-- {
  234. fullNode = nodesWithCapacity[fullNodeIndex]
  235. if !fullNode.isOneVolumeOnly() {
  236. break
  237. }
  238. }
  239. var candidateVolumes []*master_pb.VolumeInformationMessage
  240. for _, v := range fullNode.selectedVolumes {
  241. candidateVolumes = append(candidateVolumes, v)
  242. }
  243. sortCandidatesFn(candidateVolumes)
  244. for i := 0; i < len(nodesWithCapacity)-1; i++ {
  245. emptyNode := nodesWithCapacity[i]
  246. if !(fullNode.localVolumeRatio(capacityFunc) > idealVolumeRatio && emptyNode.localVolumeNextRatio(capacityFunc) <= idealVolumeRatio) {
  247. // no more volume servers with empty slots
  248. break
  249. }
  250. fmt.Fprintf(os.Stdout, "%s %.2f %.2f:%.2f\t", diskType.ReadableString(), idealVolumeRatio, fullNode.localVolumeRatio(capacityFunc), emptyNode.localVolumeNextRatio(capacityFunc))
  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 !commandEnv.isLocked() {
  277. return false, fmt.Errorf("lock is lost")
  278. }
  279. if candidateVolume.ReplicaPlacement > 0 {
  280. replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(candidateVolume.ReplicaPlacement))
  281. if !isGoodMove(replicaPlacement, volumeReplicas[candidateVolume.Id], fullNode, emptyNode) {
  282. return false, nil
  283. }
  284. }
  285. if _, found := emptyNode.selectedVolumes[candidateVolume.Id]; !found {
  286. if err = moveVolume(commandEnv, candidateVolume, fullNode, emptyNode, applyChange); err == nil {
  287. adjustAfterMove(candidateVolume, volumeReplicas, fullNode, emptyNode)
  288. return true, nil
  289. } else {
  290. return
  291. }
  292. }
  293. return
  294. }
  295. func moveVolume(commandEnv *CommandEnv, v *master_pb.VolumeInformationMessage, fullNode *Node, emptyNode *Node, applyChange bool) error {
  296. collectionPrefix := v.Collection + "_"
  297. if v.Collection == "" {
  298. collectionPrefix = ""
  299. }
  300. fmt.Fprintf(os.Stdout, " moving %s volume %s%d %s => %s\n", v.DiskType, collectionPrefix, v.Id, fullNode.info.Id, emptyNode.info.Id)
  301. if applyChange {
  302. 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)
  303. }
  304. return nil
  305. }
  306. func isGoodMove(placement *super_block.ReplicaPlacement, existingReplicas []*VolumeReplica, sourceNode, targetNode *Node) bool {
  307. for _, replica := range existingReplicas {
  308. if replica.location.dataNode.Id == targetNode.info.Id &&
  309. replica.location.rack == targetNode.rack &&
  310. replica.location.dc == targetNode.dc {
  311. // never move to existing nodes
  312. return false
  313. }
  314. }
  315. dcs, racks := make(map[string]bool), make(map[string]int)
  316. for _, replica := range existingReplicas {
  317. if replica.location.dataNode.Id != sourceNode.info.Id {
  318. dcs[replica.location.DataCenter()] = true
  319. racks[replica.location.Rack()]++
  320. }
  321. }
  322. dcs[targetNode.dc] = true
  323. racks[fmt.Sprintf("%s %s", targetNode.dc, targetNode.rack)]++
  324. if len(dcs) != placement.DiffDataCenterCount+1 {
  325. return false
  326. }
  327. if len(racks) != placement.DiffRackCount+placement.DiffDataCenterCount+1 {
  328. return false
  329. }
  330. for _, sameRackCount := range racks {
  331. if sameRackCount != placement.SameRackCount+1 {
  332. return false
  333. }
  334. }
  335. return true
  336. }
  337. func adjustAfterMove(v *master_pb.VolumeInformationMessage, volumeReplicas map[uint32][]*VolumeReplica, fullNode *Node, emptyNode *Node) {
  338. delete(fullNode.selectedVolumes, v.Id)
  339. if emptyNode.selectedVolumes != nil {
  340. emptyNode.selectedVolumes[v.Id] = v
  341. }
  342. existingReplicas := volumeReplicas[v.Id]
  343. for _, replica := range existingReplicas {
  344. if replica.location.dataNode.Id == fullNode.info.Id &&
  345. replica.location.rack == fullNode.rack &&
  346. replica.location.dc == fullNode.dc {
  347. loc := newLocation(emptyNode.dc, emptyNode.rack, emptyNode.info)
  348. replica.location = &loc
  349. for diskType, diskInfo := range fullNode.info.DiskInfos {
  350. if diskType == v.DiskType {
  351. diskInfo.VolumeCount--
  352. diskInfo.FreeVolumeCount++
  353. }
  354. }
  355. for diskType, diskInfo := range emptyNode.info.DiskInfos {
  356. if diskType == v.DiskType {
  357. diskInfo.VolumeCount++
  358. diskInfo.FreeVolumeCount--
  359. }
  360. }
  361. return
  362. }
  363. }
  364. }