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.

524 lines
17 KiB

4 years ago
6 years ago
  1. package shell
  2. import (
  3. "flag"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/storage/types"
  6. "io"
  7. "sort"
  8. "github.com/chrislusf/seaweedfs/weed/storage/erasure_coding"
  9. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  10. )
  11. func init() {
  12. Commands = append(Commands, &commandEcBalance{})
  13. }
  14. type commandEcBalance struct {
  15. }
  16. func (c *commandEcBalance) Name() string {
  17. return "ec.balance"
  18. }
  19. func (c *commandEcBalance) Help() string {
  20. return `balance all ec shards among all racks and volume servers
  21. ec.balance [-c EACH_COLLECTION|<collection_name>] [-force] [-dataCenter <data_center>]
  22. Algorithm:
  23. func EcBalance() {
  24. for each collection:
  25. balanceEcVolumes(collectionName)
  26. for each rack:
  27. balanceEcRack(rack)
  28. }
  29. func balanceEcVolumes(collectionName){
  30. for each volume:
  31. doDeduplicateEcShards(volumeId)
  32. tracks rack~shardCount mapping
  33. for each volume:
  34. doBalanceEcShardsAcrossRacks(volumeId)
  35. for each volume:
  36. doBalanceEcShardsWithinRacks(volumeId)
  37. }
  38. // spread ec shards into more racks
  39. func doBalanceEcShardsAcrossRacks(volumeId){
  40. tracks rack~volumeIdShardCount mapping
  41. averageShardsPerEcRack = totalShardNumber / numRacks // totalShardNumber is 14 for now, later could varies for each dc
  42. ecShardsToMove = select overflown ec shards from racks with ec shard counts > averageShardsPerEcRack
  43. for each ecShardsToMove {
  44. destRack = pickOneRack(rack~shardCount, rack~volumeIdShardCount, averageShardsPerEcRack)
  45. destVolumeServers = volume servers on the destRack
  46. pickOneEcNodeAndMoveOneShard(destVolumeServers)
  47. }
  48. }
  49. func doBalanceEcShardsWithinRacks(volumeId){
  50. racks = collect all racks that the volume id is on
  51. for rack, shards := range racks
  52. doBalanceEcShardsWithinOneRack(volumeId, shards, rack)
  53. }
  54. // move ec shards
  55. func doBalanceEcShardsWithinOneRack(volumeId, shards, rackId){
  56. tracks volumeServer~volumeIdShardCount mapping
  57. averageShardCount = len(shards) / numVolumeServers
  58. volumeServersOverAverage = volume servers with volumeId's ec shard counts > averageShardsPerEcRack
  59. ecShardsToMove = select overflown ec shards from volumeServersOverAverage
  60. for each ecShardsToMove {
  61. destVolumeServer = pickOneVolumeServer(volumeServer~shardCount, volumeServer~volumeIdShardCount, averageShardCount)
  62. pickOneEcNodeAndMoveOneShard(destVolumeServers)
  63. }
  64. }
  65. // move ec shards while keeping shard distribution for the same volume unchanged or more even
  66. func balanceEcRack(rack){
  67. averageShardCount = total shards / numVolumeServers
  68. for hasMovedOneEcShard {
  69. sort all volume servers ordered by the number of local ec shards
  70. pick the volume server A with the lowest number of ec shards x
  71. pick the volume server B with the highest number of ec shards y
  72. if y > averageShardCount and x +1 <= averageShardCount {
  73. if B has a ec shard with volume id v that A does not have {
  74. move one ec shard v from B to A
  75. hasMovedOneEcShard = true
  76. }
  77. }
  78. }
  79. }
  80. `
  81. }
  82. func (c *commandEcBalance) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  83. if err = commandEnv.confirmIsLocked(); err != nil {
  84. return
  85. }
  86. balanceCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
  87. collection := balanceCommand.String("collection", "EACH_COLLECTION", "collection name, or \"EACH_COLLECTION\" for each collection")
  88. dc := balanceCommand.String("dataCenter", "", "only apply the balancing for this dataCenter")
  89. applyBalancing := balanceCommand.Bool("force", false, "apply the balancing plan")
  90. if err = balanceCommand.Parse(args); err != nil {
  91. return nil
  92. }
  93. // collect all ec nodes
  94. allEcNodes, totalFreeEcSlots, err := collectEcNodes(commandEnv, *dc)
  95. if err != nil {
  96. return err
  97. }
  98. if totalFreeEcSlots < 1 {
  99. return fmt.Errorf("no free ec shard slots. only %d left", totalFreeEcSlots)
  100. }
  101. racks := collectRacks(allEcNodes)
  102. if *collection == "EACH_COLLECTION" {
  103. collections, err := ListCollectionNames(commandEnv, false, true)
  104. if err != nil {
  105. return err
  106. }
  107. fmt.Printf("balanceEcVolumes collections %+v\n", len(collections))
  108. for _, c := range collections {
  109. fmt.Printf("balanceEcVolumes collection %+v\n", c)
  110. if err = balanceEcVolumes(commandEnv, c, allEcNodes, racks, *applyBalancing); err != nil {
  111. return err
  112. }
  113. }
  114. } else {
  115. if err = balanceEcVolumes(commandEnv, *collection, allEcNodes, racks, *applyBalancing); err != nil {
  116. return err
  117. }
  118. }
  119. if err := balanceEcRacks(commandEnv, racks, *applyBalancing); err != nil {
  120. return fmt.Errorf("balance ec racks: %v", err)
  121. }
  122. return nil
  123. }
  124. func collectRacks(allEcNodes []*EcNode) map[RackId]*EcRack {
  125. // collect racks info
  126. racks := make(map[RackId]*EcRack)
  127. for _, ecNode := range allEcNodes {
  128. if racks[ecNode.rack] == nil {
  129. racks[ecNode.rack] = &EcRack{
  130. ecNodes: make(map[EcNodeId]*EcNode),
  131. }
  132. }
  133. racks[ecNode.rack].ecNodes[EcNodeId(ecNode.info.Id)] = ecNode
  134. racks[ecNode.rack].freeEcSlot += ecNode.freeEcSlot
  135. }
  136. return racks
  137. }
  138. func balanceEcVolumes(commandEnv *CommandEnv, collection string, allEcNodes []*EcNode, racks map[RackId]*EcRack, applyBalancing bool) error {
  139. fmt.Printf("balanceEcVolumes %s\n", collection)
  140. if err := deleteDuplicatedEcShards(commandEnv, allEcNodes, collection, applyBalancing); err != nil {
  141. return fmt.Errorf("delete duplicated collection %s ec shards: %v", collection, err)
  142. }
  143. if err := balanceEcShardsAcrossRacks(commandEnv, allEcNodes, racks, collection, applyBalancing); err != nil {
  144. return fmt.Errorf("balance across racks collection %s ec shards: %v", collection, err)
  145. }
  146. if err := balanceEcShardsWithinRacks(commandEnv, allEcNodes, racks, collection, applyBalancing); err != nil {
  147. return fmt.Errorf("balance within racks collection %s ec shards: %v", collection, err)
  148. }
  149. return nil
  150. }
  151. func deleteDuplicatedEcShards(commandEnv *CommandEnv, allEcNodes []*EcNode, collection string, applyBalancing bool) error {
  152. // vid => []ecNode
  153. vidLocations := collectVolumeIdToEcNodes(allEcNodes)
  154. // deduplicate ec shards
  155. for vid, locations := range vidLocations {
  156. if err := doDeduplicateEcShards(commandEnv, collection, vid, locations, applyBalancing); err != nil {
  157. return err
  158. }
  159. }
  160. return nil
  161. }
  162. func doDeduplicateEcShards(commandEnv *CommandEnv, collection string, vid needle.VolumeId, locations []*EcNode, applyBalancing bool) error {
  163. // check whether this volume has ecNodes that are over average
  164. shardToLocations := make([][]*EcNode, erasure_coding.TotalShardsCount)
  165. for _, ecNode := range locations {
  166. shardBits := findEcVolumeShards(ecNode, vid)
  167. for _, shardId := range shardBits.ShardIds() {
  168. shardToLocations[shardId] = append(shardToLocations[shardId], ecNode)
  169. }
  170. }
  171. for shardId, ecNodes := range shardToLocations {
  172. if len(ecNodes) <= 1 {
  173. continue
  174. }
  175. sortEcNodesByFreeslotsAscending(ecNodes)
  176. fmt.Printf("ec shard %d.%d has %d copies, keeping %v\n", vid, shardId, len(ecNodes), ecNodes[0].info.Id)
  177. if !applyBalancing {
  178. continue
  179. }
  180. duplicatedShardIds := []uint32{uint32(shardId)}
  181. for _, ecNode := range ecNodes[1:] {
  182. if err := unmountEcShards(commandEnv.option.GrpcDialOption, vid, ecNode.info.Id, duplicatedShardIds); err != nil {
  183. return err
  184. }
  185. if err := sourceServerDeleteEcShards(commandEnv.option.GrpcDialOption, collection, vid, ecNode.info.Id, duplicatedShardIds); err != nil {
  186. return err
  187. }
  188. ecNode.deleteEcVolumeShards(vid, duplicatedShardIds)
  189. }
  190. }
  191. return nil
  192. }
  193. func balanceEcShardsAcrossRacks(commandEnv *CommandEnv, allEcNodes []*EcNode, racks map[RackId]*EcRack, collection string, applyBalancing bool) error {
  194. // collect vid => []ecNode, since previous steps can change the locations
  195. vidLocations := collectVolumeIdToEcNodes(allEcNodes)
  196. // spread the ec shards evenly
  197. for vid, locations := range vidLocations {
  198. if err := doBalanceEcShardsAcrossRacks(commandEnv, collection, vid, locations, racks, applyBalancing); err != nil {
  199. return err
  200. }
  201. }
  202. return nil
  203. }
  204. func doBalanceEcShardsAcrossRacks(commandEnv *CommandEnv, collection string, vid needle.VolumeId, locations []*EcNode, racks map[RackId]*EcRack, applyBalancing bool) error {
  205. // calculate average number of shards an ec rack should have for one volume
  206. averageShardsPerEcRack := ceilDivide(erasure_coding.TotalShardsCount, len(racks))
  207. // see the volume's shards are in how many racks, and how many in each rack
  208. rackToShardCount := groupByCount(locations, func(ecNode *EcNode) (id string, count int) {
  209. shardBits := findEcVolumeShards(ecNode, vid)
  210. return string(ecNode.rack), shardBits.ShardIdCount()
  211. })
  212. rackEcNodesWithVid := groupBy(locations, func(ecNode *EcNode) string {
  213. return string(ecNode.rack)
  214. })
  215. // ecShardsToMove = select overflown ec shards from racks with ec shard counts > averageShardsPerEcRack
  216. ecShardsToMove := make(map[erasure_coding.ShardId]*EcNode)
  217. for rackId, count := range rackToShardCount {
  218. if count > averageShardsPerEcRack {
  219. possibleEcNodes := rackEcNodesWithVid[rackId]
  220. for shardId, ecNode := range pickNEcShardsToMoveFrom(possibleEcNodes, vid, count-averageShardsPerEcRack) {
  221. ecShardsToMove[shardId] = ecNode
  222. }
  223. }
  224. }
  225. for shardId, ecNode := range ecShardsToMove {
  226. rackId := pickOneRack(racks, rackToShardCount, averageShardsPerEcRack)
  227. if rackId == "" {
  228. fmt.Printf("ec shard %d.%d at %s can not find a destination rack\n", vid, shardId, ecNode.info.Id)
  229. continue
  230. }
  231. var possibleDestinationEcNodes []*EcNode
  232. for _, n := range racks[rackId].ecNodes {
  233. possibleDestinationEcNodes = append(possibleDestinationEcNodes, n)
  234. }
  235. err := pickOneEcNodeAndMoveOneShard(commandEnv, averageShardsPerEcRack, ecNode, collection, vid, shardId, possibleDestinationEcNodes, applyBalancing)
  236. if err != nil {
  237. return err
  238. }
  239. rackToShardCount[string(rackId)] += 1
  240. rackToShardCount[string(ecNode.rack)] -= 1
  241. racks[rackId].freeEcSlot -= 1
  242. racks[ecNode.rack].freeEcSlot += 1
  243. }
  244. return nil
  245. }
  246. func pickOneRack(rackToEcNodes map[RackId]*EcRack, rackToShardCount map[string]int, averageShardsPerEcRack int) RackId {
  247. // TODO later may need to add some randomness
  248. for rackId, rack := range rackToEcNodes {
  249. if rackToShardCount[string(rackId)] >= averageShardsPerEcRack {
  250. continue
  251. }
  252. if rack.freeEcSlot <= 0 {
  253. continue
  254. }
  255. return rackId
  256. }
  257. return ""
  258. }
  259. func balanceEcShardsWithinRacks(commandEnv *CommandEnv, allEcNodes []*EcNode, racks map[RackId]*EcRack, collection string, applyBalancing bool) error {
  260. // collect vid => []ecNode, since previous steps can change the locations
  261. vidLocations := collectVolumeIdToEcNodes(allEcNodes)
  262. // spread the ec shards evenly
  263. for vid, locations := range vidLocations {
  264. // see the volume's shards are in how many racks, and how many in each rack
  265. rackToShardCount := groupByCount(locations, func(ecNode *EcNode) (id string, count int) {
  266. shardBits := findEcVolumeShards(ecNode, vid)
  267. return string(ecNode.rack), shardBits.ShardIdCount()
  268. })
  269. rackEcNodesWithVid := groupBy(locations, func(ecNode *EcNode) string {
  270. return string(ecNode.rack)
  271. })
  272. for rackId, _ := range rackToShardCount {
  273. var possibleDestinationEcNodes []*EcNode
  274. for _, n := range racks[RackId(rackId)].ecNodes {
  275. possibleDestinationEcNodes = append(possibleDestinationEcNodes, n)
  276. }
  277. sourceEcNodes := rackEcNodesWithVid[rackId]
  278. averageShardsPerEcNode := ceilDivide(rackToShardCount[rackId], len(possibleDestinationEcNodes))
  279. if err := doBalanceEcShardsWithinOneRack(commandEnv, averageShardsPerEcNode, collection, vid, sourceEcNodes, possibleDestinationEcNodes, applyBalancing); err != nil {
  280. return err
  281. }
  282. }
  283. }
  284. return nil
  285. }
  286. func doBalanceEcShardsWithinOneRack(commandEnv *CommandEnv, averageShardsPerEcNode int, collection string, vid needle.VolumeId, existingLocations, possibleDestinationEcNodes []*EcNode, applyBalancing bool) error {
  287. for _, ecNode := range existingLocations {
  288. shardBits := findEcVolumeShards(ecNode, vid)
  289. overLimitCount := shardBits.ShardIdCount() - averageShardsPerEcNode
  290. for _, shardId := range shardBits.ShardIds() {
  291. if overLimitCount <= 0 {
  292. break
  293. }
  294. fmt.Printf("%s has %d overlimit, moving ec shard %d.%d\n", ecNode.info.Id, overLimitCount, vid, shardId)
  295. err := pickOneEcNodeAndMoveOneShard(commandEnv, averageShardsPerEcNode, ecNode, collection, vid, shardId, possibleDestinationEcNodes, applyBalancing)
  296. if err != nil {
  297. return err
  298. }
  299. overLimitCount--
  300. }
  301. }
  302. return nil
  303. }
  304. func balanceEcRacks(commandEnv *CommandEnv, racks map[RackId]*EcRack, applyBalancing bool) error {
  305. // balance one rack for all ec shards
  306. for _, ecRack := range racks {
  307. if err := doBalanceEcRack(commandEnv, ecRack, applyBalancing); err != nil {
  308. return err
  309. }
  310. }
  311. return nil
  312. }
  313. func doBalanceEcRack(commandEnv *CommandEnv, ecRack *EcRack, applyBalancing bool) error {
  314. if len(ecRack.ecNodes) <= 1 {
  315. return nil
  316. }
  317. var rackEcNodes []*EcNode
  318. for _, node := range ecRack.ecNodes {
  319. rackEcNodes = append(rackEcNodes, node)
  320. }
  321. ecNodeIdToShardCount := groupByCount(rackEcNodes, func(ecNode *EcNode) (id string, count int) {
  322. diskInfo := ecNode.info.DiskInfos[string(types.HardDriveType)]
  323. for _, ecShardInfo := range diskInfo.EcShardInfos {
  324. count += erasure_coding.ShardBits(ecShardInfo.EcIndexBits).ShardIdCount()
  325. }
  326. return ecNode.info.Id, count
  327. })
  328. var totalShardCount int
  329. for _, count := range ecNodeIdToShardCount {
  330. totalShardCount += count
  331. }
  332. averageShardCount := ceilDivide(totalShardCount, len(rackEcNodes))
  333. hasMove := true
  334. for hasMove {
  335. hasMove = false
  336. sort.Slice(rackEcNodes, func(i, j int) bool {
  337. return rackEcNodes[i].freeEcSlot > rackEcNodes[j].freeEcSlot
  338. })
  339. emptyNode, fullNode := rackEcNodes[0], rackEcNodes[len(rackEcNodes)-1]
  340. emptyNodeShardCount, fullNodeShardCount := ecNodeIdToShardCount[emptyNode.info.Id], ecNodeIdToShardCount[fullNode.info.Id]
  341. if fullNodeShardCount > averageShardCount && emptyNodeShardCount+1 <= averageShardCount {
  342. emptyNodeIds := make(map[uint32]bool)
  343. emptyDiskInfo := emptyNode.info.DiskInfos[string(types.HardDriveType)]
  344. for _, shards := range emptyDiskInfo.EcShardInfos {
  345. emptyNodeIds[shards.Id] = true
  346. }
  347. fullDiskInfo := fullNode.info.DiskInfos[string(types.HardDriveType)]
  348. for _, shards := range fullDiskInfo.EcShardInfos {
  349. if _, found := emptyNodeIds[shards.Id]; !found {
  350. for _, shardId := range erasure_coding.ShardBits(shards.EcIndexBits).ShardIds() {
  351. fmt.Printf("%s moves ec shards %d.%d to %s\n", fullNode.info.Id, shards.Id, shardId, emptyNode.info.Id)
  352. err := moveMountedShardToEcNode(commandEnv, fullNode, shards.Collection, needle.VolumeId(shards.Id), shardId, emptyNode, applyBalancing)
  353. if err != nil {
  354. return err
  355. }
  356. ecNodeIdToShardCount[emptyNode.info.Id]++
  357. ecNodeIdToShardCount[fullNode.info.Id]--
  358. hasMove = true
  359. break
  360. }
  361. break
  362. }
  363. }
  364. }
  365. }
  366. return nil
  367. }
  368. func pickOneEcNodeAndMoveOneShard(commandEnv *CommandEnv, averageShardsPerEcNode int, existingLocation *EcNode, collection string, vid needle.VolumeId, shardId erasure_coding.ShardId, possibleDestinationEcNodes []*EcNode, applyBalancing bool) error {
  369. sortEcNodesByFreeslotsDecending(possibleDestinationEcNodes)
  370. for _, destEcNode := range possibleDestinationEcNodes {
  371. if destEcNode.info.Id == existingLocation.info.Id {
  372. continue
  373. }
  374. if destEcNode.freeEcSlot <= 0 {
  375. continue
  376. }
  377. if findEcVolumeShards(destEcNode, vid).ShardIdCount() >= averageShardsPerEcNode {
  378. continue
  379. }
  380. fmt.Printf("%s moves ec shard %d.%d to %s\n", existingLocation.info.Id, vid, shardId, destEcNode.info.Id)
  381. err := moveMountedShardToEcNode(commandEnv, existingLocation, collection, vid, shardId, destEcNode, applyBalancing)
  382. if err != nil {
  383. return err
  384. }
  385. return nil
  386. }
  387. return nil
  388. }
  389. func pickNEcShardsToMoveFrom(ecNodes []*EcNode, vid needle.VolumeId, n int) map[erasure_coding.ShardId]*EcNode {
  390. picked := make(map[erasure_coding.ShardId]*EcNode)
  391. var candidateEcNodes []*CandidateEcNode
  392. for _, ecNode := range ecNodes {
  393. shardBits := findEcVolumeShards(ecNode, vid)
  394. if shardBits.ShardIdCount() > 0 {
  395. candidateEcNodes = append(candidateEcNodes, &CandidateEcNode{
  396. ecNode: ecNode,
  397. shardCount: shardBits.ShardIdCount(),
  398. })
  399. }
  400. }
  401. sort.Slice(candidateEcNodes, func(i, j int) bool {
  402. return candidateEcNodes[i].shardCount > candidateEcNodes[j].shardCount
  403. })
  404. for i := 0; i < n; i++ {
  405. selectedEcNodeIndex := -1
  406. for i, candidateEcNode := range candidateEcNodes {
  407. shardBits := findEcVolumeShards(candidateEcNode.ecNode, vid)
  408. if shardBits > 0 {
  409. selectedEcNodeIndex = i
  410. for _, shardId := range shardBits.ShardIds() {
  411. candidateEcNode.shardCount--
  412. picked[shardId] = candidateEcNode.ecNode
  413. candidateEcNode.ecNode.deleteEcVolumeShards(vid, []uint32{uint32(shardId)})
  414. break
  415. }
  416. break
  417. }
  418. }
  419. if selectedEcNodeIndex >= 0 {
  420. ensureSortedEcNodes(candidateEcNodes, selectedEcNodeIndex, func(i, j int) bool {
  421. return candidateEcNodes[i].shardCount > candidateEcNodes[j].shardCount
  422. })
  423. }
  424. }
  425. return picked
  426. }
  427. func collectVolumeIdToEcNodes(allEcNodes []*EcNode) map[needle.VolumeId][]*EcNode {
  428. vidLocations := make(map[needle.VolumeId][]*EcNode)
  429. for _, ecNode := range allEcNodes {
  430. diskInfo := ecNode.info.DiskInfos[string(types.HardDriveType)]
  431. for _, shardInfo := range diskInfo.EcShardInfos {
  432. vidLocations[needle.VolumeId(shardInfo.Id)] = append(vidLocations[needle.VolumeId(shardInfo.Id)], ecNode)
  433. }
  434. }
  435. return vidLocations
  436. }