command_ec_balance.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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. if _, found := n.info.DiskInfos[string(types.HardDriveType)]; found {
  276. possibleDestinationEcNodes = append(possibleDestinationEcNodes, n)
  277. }
  278. }
  279. sourceEcNodes := rackEcNodesWithVid[rackId]
  280. averageShardsPerEcNode := ceilDivide(rackToShardCount[rackId], len(possibleDestinationEcNodes))
  281. if err := doBalanceEcShardsWithinOneRack(commandEnv, averageShardsPerEcNode, collection, vid, sourceEcNodes, possibleDestinationEcNodes, applyBalancing); err != nil {
  282. return err
  283. }
  284. }
  285. }
  286. return nil
  287. }
  288. func doBalanceEcShardsWithinOneRack(commandEnv *CommandEnv, averageShardsPerEcNode int, collection string, vid needle.VolumeId, existingLocations, possibleDestinationEcNodes []*EcNode, applyBalancing bool) error {
  289. for _, ecNode := range existingLocations {
  290. shardBits := findEcVolumeShards(ecNode, vid)
  291. overLimitCount := shardBits.ShardIdCount() - averageShardsPerEcNode
  292. for _, shardId := range shardBits.ShardIds() {
  293. if overLimitCount <= 0 {
  294. break
  295. }
  296. fmt.Printf("%s has %d overlimit, moving ec shard %d.%d\n", ecNode.info.Id, overLimitCount, vid, shardId)
  297. err := pickOneEcNodeAndMoveOneShard(commandEnv, averageShardsPerEcNode, ecNode, collection, vid, shardId, possibleDestinationEcNodes, applyBalancing)
  298. if err != nil {
  299. return err
  300. }
  301. overLimitCount--
  302. }
  303. }
  304. return nil
  305. }
  306. func balanceEcRacks(commandEnv *CommandEnv, racks map[RackId]*EcRack, applyBalancing bool) error {
  307. // balance one rack for all ec shards
  308. for _, ecRack := range racks {
  309. if err := doBalanceEcRack(commandEnv, ecRack, applyBalancing); err != nil {
  310. return err
  311. }
  312. }
  313. return nil
  314. }
  315. func doBalanceEcRack(commandEnv *CommandEnv, ecRack *EcRack, applyBalancing bool) error {
  316. if len(ecRack.ecNodes) <= 1 {
  317. return nil
  318. }
  319. var rackEcNodes []*EcNode
  320. for _, node := range ecRack.ecNodes {
  321. rackEcNodes = append(rackEcNodes, node)
  322. }
  323. ecNodeIdToShardCount := groupByCount(rackEcNodes, func(ecNode *EcNode) (id string, count int) {
  324. diskInfo, found := ecNode.info.DiskInfos[string(types.HardDriveType)]
  325. if !found {
  326. return
  327. }
  328. for _, ecShardInfo := range diskInfo.EcShardInfos {
  329. count += erasure_coding.ShardBits(ecShardInfo.EcIndexBits).ShardIdCount()
  330. }
  331. return ecNode.info.Id, count
  332. })
  333. var totalShardCount int
  334. for _, count := range ecNodeIdToShardCount {
  335. totalShardCount += count
  336. }
  337. averageShardCount := ceilDivide(totalShardCount, len(rackEcNodes))
  338. hasMove := true
  339. for hasMove {
  340. hasMove = false
  341. sort.Slice(rackEcNodes, func(i, j int) bool {
  342. return rackEcNodes[i].freeEcSlot > rackEcNodes[j].freeEcSlot
  343. })
  344. emptyNode, fullNode := rackEcNodes[0], rackEcNodes[len(rackEcNodes)-1]
  345. emptyNodeShardCount, fullNodeShardCount := ecNodeIdToShardCount[emptyNode.info.Id], ecNodeIdToShardCount[fullNode.info.Id]
  346. if fullNodeShardCount > averageShardCount && emptyNodeShardCount+1 <= averageShardCount {
  347. emptyNodeIds := make(map[uint32]bool)
  348. if emptyDiskInfo, found := emptyNode.info.DiskInfos[string(types.HardDriveType)]; found {
  349. for _, shards := range emptyDiskInfo.EcShardInfos {
  350. emptyNodeIds[shards.Id] = true
  351. }
  352. }
  353. if fullDiskInfo, found := fullNode.info.DiskInfos[string(types.HardDriveType)]; found {
  354. for _, shards := range fullDiskInfo.EcShardInfos {
  355. if _, found := emptyNodeIds[shards.Id]; !found {
  356. for _, shardId := range erasure_coding.ShardBits(shards.EcIndexBits).ShardIds() {
  357. fmt.Printf("%s moves ec shards %d.%d to %s\n", fullNode.info.Id, shards.Id, shardId, emptyNode.info.Id)
  358. err := moveMountedShardToEcNode(commandEnv, fullNode, shards.Collection, needle.VolumeId(shards.Id), shardId, emptyNode, applyBalancing)
  359. if err != nil {
  360. return err
  361. }
  362. ecNodeIdToShardCount[emptyNode.info.Id]++
  363. ecNodeIdToShardCount[fullNode.info.Id]--
  364. hasMove = true
  365. break
  366. }
  367. break
  368. }
  369. }
  370. }
  371. }
  372. }
  373. return nil
  374. }
  375. func pickOneEcNodeAndMoveOneShard(commandEnv *CommandEnv, averageShardsPerEcNode int, existingLocation *EcNode, collection string, vid needle.VolumeId, shardId erasure_coding.ShardId, possibleDestinationEcNodes []*EcNode, applyBalancing bool) error {
  376. sortEcNodesByFreeslotsDecending(possibleDestinationEcNodes)
  377. for _, destEcNode := range possibleDestinationEcNodes {
  378. if destEcNode.info.Id == existingLocation.info.Id {
  379. continue
  380. }
  381. if destEcNode.freeEcSlot <= 0 {
  382. continue
  383. }
  384. if findEcVolumeShards(destEcNode, vid).ShardIdCount() >= averageShardsPerEcNode {
  385. continue
  386. }
  387. fmt.Printf("%s moves ec shard %d.%d to %s\n", existingLocation.info.Id, vid, shardId, destEcNode.info.Id)
  388. err := moveMountedShardToEcNode(commandEnv, existingLocation, collection, vid, shardId, destEcNode, applyBalancing)
  389. if err != nil {
  390. return err
  391. }
  392. return nil
  393. }
  394. return nil
  395. }
  396. func pickNEcShardsToMoveFrom(ecNodes []*EcNode, vid needle.VolumeId, n int) map[erasure_coding.ShardId]*EcNode {
  397. picked := make(map[erasure_coding.ShardId]*EcNode)
  398. var candidateEcNodes []*CandidateEcNode
  399. for _, ecNode := range ecNodes {
  400. shardBits := findEcVolumeShards(ecNode, vid)
  401. if shardBits.ShardIdCount() > 0 {
  402. candidateEcNodes = append(candidateEcNodes, &CandidateEcNode{
  403. ecNode: ecNode,
  404. shardCount: shardBits.ShardIdCount(),
  405. })
  406. }
  407. }
  408. sort.Slice(candidateEcNodes, func(i, j int) bool {
  409. return candidateEcNodes[i].shardCount > candidateEcNodes[j].shardCount
  410. })
  411. for i := 0; i < n; i++ {
  412. selectedEcNodeIndex := -1
  413. for i, candidateEcNode := range candidateEcNodes {
  414. shardBits := findEcVolumeShards(candidateEcNode.ecNode, vid)
  415. if shardBits > 0 {
  416. selectedEcNodeIndex = i
  417. for _, shardId := range shardBits.ShardIds() {
  418. candidateEcNode.shardCount--
  419. picked[shardId] = candidateEcNode.ecNode
  420. candidateEcNode.ecNode.deleteEcVolumeShards(vid, []uint32{uint32(shardId)})
  421. break
  422. }
  423. break
  424. }
  425. }
  426. if selectedEcNodeIndex >= 0 {
  427. ensureSortedEcNodes(candidateEcNodes, selectedEcNodeIndex, func(i, j int) bool {
  428. return candidateEcNodes[i].shardCount > candidateEcNodes[j].shardCount
  429. })
  430. }
  431. }
  432. return picked
  433. }
  434. func collectVolumeIdToEcNodes(allEcNodes []*EcNode) map[needle.VolumeId][]*EcNode {
  435. vidLocations := make(map[needle.VolumeId][]*EcNode)
  436. for _, ecNode := range allEcNodes {
  437. diskInfo, found := ecNode.info.DiskInfos[string(types.HardDriveType)]
  438. if !found {
  439. continue
  440. }
  441. for _, shardInfo := range diskInfo.EcShardInfos {
  442. vidLocations[needle.VolumeId(shardInfo.Id)] = append(vidLocations[needle.VolumeId(shardInfo.Id)], ecNode)
  443. }
  444. }
  445. return vidLocations
  446. }