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.

1093 lines
34 KiB

4 years ago
4 years ago
  1. package shell
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "math/rand/v2"
  7. "sort"
  8. "sync"
  9. "time"
  10. "github.com/seaweedfs/seaweedfs/weed/glog"
  11. "github.com/seaweedfs/seaweedfs/weed/operation"
  12. "github.com/seaweedfs/seaweedfs/weed/pb"
  13. "github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
  14. "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
  15. "github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
  16. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  17. "github.com/seaweedfs/seaweedfs/weed/storage/super_block"
  18. "github.com/seaweedfs/seaweedfs/weed/storage/types"
  19. "google.golang.org/grpc"
  20. "slices"
  21. )
  22. type DataCenterId string
  23. type EcNodeId string
  24. type RackId string
  25. type EcNode struct {
  26. info *master_pb.DataNodeInfo
  27. dc DataCenterId
  28. rack RackId
  29. freeEcSlot int
  30. }
  31. type CandidateEcNode struct {
  32. ecNode *EcNode
  33. shardCount int
  34. }
  35. type EcRack struct {
  36. ecNodes map[EcNodeId]*EcNode
  37. freeEcSlot int
  38. }
  39. var (
  40. ecBalanceAlgorithmDescription = `
  41. func EcBalance() {
  42. for each collection:
  43. balanceEcVolumes(collectionName)
  44. for each rack:
  45. balanceEcRack(rack)
  46. }
  47. func balanceEcVolumes(collectionName){
  48. for each volume:
  49. doDeduplicateEcShards(volumeId)
  50. tracks rack~shardCount mapping
  51. for each volume:
  52. doBalanceEcShardsAcrossRacks(volumeId)
  53. for each volume:
  54. doBalanceEcShardsWithinRacks(volumeId)
  55. }
  56. // spread ec shards into more racks
  57. func doBalanceEcShardsAcrossRacks(volumeId){
  58. tracks rack~volumeIdShardCount mapping
  59. averageShardsPerEcRack = totalShardNumber / numRacks // totalShardNumber is 14 for now, later could varies for each dc
  60. ecShardsToMove = select overflown ec shards from racks with ec shard counts > averageShardsPerEcRack
  61. for each ecShardsToMove {
  62. destRack = pickOneRack(rack~shardCount, rack~volumeIdShardCount, ecShardReplicaPlacement)
  63. destVolumeServers = volume servers on the destRack
  64. pickOneEcNodeAndMoveOneShard(destVolumeServers)
  65. }
  66. }
  67. func doBalanceEcShardsWithinRacks(volumeId){
  68. racks = collect all racks that the volume id is on
  69. for rack, shards := range racks
  70. doBalanceEcShardsWithinOneRack(volumeId, shards, rack)
  71. }
  72. // move ec shards
  73. func doBalanceEcShardsWithinOneRack(volumeId, shards, rackId){
  74. tracks volumeServer~volumeIdShardCount mapping
  75. averageShardCount = len(shards) / numVolumeServers
  76. volumeServersOverAverage = volume servers with volumeId's ec shard counts > averageShardsPerEcRack
  77. ecShardsToMove = select overflown ec shards from volumeServersOverAverage
  78. for each ecShardsToMove {
  79. destVolumeServer = pickOneVolumeServer(volumeServer~shardCount, volumeServer~volumeIdShardCount, ecShardReplicaPlacement)
  80. pickOneEcNodeAndMoveOneShard(destVolumeServers)
  81. }
  82. }
  83. // move ec shards while keeping shard distribution for the same volume unchanged or more even
  84. func balanceEcRack(rack){
  85. averageShardCount = total shards / numVolumeServers
  86. for hasMovedOneEcShard {
  87. sort all volume servers ordered by the number of local ec shards
  88. pick the volume server A with the lowest number of ec shards x
  89. pick the volume server B with the highest number of ec shards y
  90. if y > averageShardCount and x +1 <= averageShardCount {
  91. if B has a ec shard with volume id v that A does not have {
  92. move one ec shard v from B to A
  93. hasMovedOneEcShard = true
  94. }
  95. }
  96. }
  97. }
  98. `
  99. // Overridable functions for testing.
  100. getDefaultReplicaPlacement = _getDefaultReplicaPlacement
  101. )
  102. type ErrorWaitGroup struct {
  103. maxConcurrency int
  104. wg *sync.WaitGroup
  105. wgSem chan bool
  106. errors []error
  107. errorsMu sync.Mutex
  108. }
  109. type ErrorWaitGroupTask func() error
  110. func NewErrorWaitGroup(maxConcurrency int) *ErrorWaitGroup {
  111. if maxConcurrency <= 0 {
  112. // No concurrency = one task at the time
  113. maxConcurrency = 1
  114. }
  115. return &ErrorWaitGroup{
  116. maxConcurrency: maxConcurrency,
  117. wg: &sync.WaitGroup{},
  118. wgSem: make(chan bool, maxConcurrency),
  119. }
  120. }
  121. func (ewg *ErrorWaitGroup) Add(f ErrorWaitGroupTask) {
  122. if ewg.maxConcurrency <= 1 {
  123. // Keep run order deterministic when parallelization is off
  124. ewg.errors = append(ewg.errors, f())
  125. return
  126. }
  127. ewg.wg.Add(1)
  128. go func() {
  129. ewg.wgSem <- true
  130. err := f()
  131. ewg.errorsMu.Lock()
  132. ewg.errors = append(ewg.errors, err)
  133. ewg.errorsMu.Unlock()
  134. <-ewg.wgSem
  135. ewg.wg.Done()
  136. }()
  137. }
  138. func (ewg *ErrorWaitGroup) Wait() error {
  139. ewg.wg.Wait()
  140. return errors.Join(ewg.errors...)
  141. }
  142. func _getDefaultReplicaPlacement(commandEnv *CommandEnv) (*super_block.ReplicaPlacement, error) {
  143. var resp *master_pb.GetMasterConfigurationResponse
  144. var err error
  145. err = commandEnv.MasterClient.WithClient(false, func(client master_pb.SeaweedClient) error {
  146. resp, err = client.GetMasterConfiguration(context.Background(), &master_pb.GetMasterConfigurationRequest{})
  147. return err
  148. })
  149. if err != nil {
  150. return nil, err
  151. }
  152. return super_block.NewReplicaPlacementFromString(resp.DefaultReplication)
  153. }
  154. func parseReplicaPlacementArg(commandEnv *CommandEnv, replicaStr string) (*super_block.ReplicaPlacement, error) {
  155. if replicaStr != "" {
  156. rp, err := super_block.NewReplicaPlacementFromString(replicaStr)
  157. if err == nil {
  158. fmt.Printf("using replica placement %q for EC volumes\n", rp.String())
  159. }
  160. return rp, err
  161. }
  162. // No replica placement argument provided, resolve from master default settings.
  163. rp, err := getDefaultReplicaPlacement(commandEnv)
  164. if err == nil {
  165. fmt.Printf("using master default replica placement %q for EC volumes\n", rp.String())
  166. }
  167. return rp, err
  168. }
  169. func collectTopologyInfo(commandEnv *CommandEnv, delayBeforeCollecting time.Duration) (topoInfo *master_pb.TopologyInfo, volumeSizeLimitMb uint64, err error) {
  170. if delayBeforeCollecting > 0 {
  171. time.Sleep(delayBeforeCollecting)
  172. }
  173. var resp *master_pb.VolumeListResponse
  174. err = commandEnv.MasterClient.WithClient(false, func(client master_pb.SeaweedClient) error {
  175. resp, err = client.VolumeList(context.Background(), &master_pb.VolumeListRequest{})
  176. return err
  177. })
  178. if err != nil {
  179. return
  180. }
  181. return resp.TopologyInfo, resp.VolumeSizeLimitMb, nil
  182. }
  183. func collectEcNodesForDC(commandEnv *CommandEnv, selectedDataCenter string) (ecNodes []*EcNode, totalFreeEcSlots int, err error) {
  184. // list all possible locations
  185. // collect topology information
  186. topologyInfo, _, err := collectTopologyInfo(commandEnv, 0)
  187. if err != nil {
  188. return
  189. }
  190. // find out all volume servers with one slot left.
  191. ecNodes, totalFreeEcSlots = collectEcVolumeServersByDc(topologyInfo, selectedDataCenter)
  192. sortEcNodesByFreeslotsDescending(ecNodes)
  193. return
  194. }
  195. func collectEcNodes(commandEnv *CommandEnv) (ecNodes []*EcNode, totalFreeEcSlots int, err error) {
  196. return collectEcNodesForDC(commandEnv, "")
  197. }
  198. func collectCollectionsForVolumeIds(t *master_pb.TopologyInfo, vids []needle.VolumeId) []string {
  199. if len(vids) == 0 {
  200. return nil
  201. }
  202. found := map[string]bool{}
  203. for _, dc := range t.DataCenterInfos {
  204. for _, r := range dc.RackInfos {
  205. for _, dn := range r.DataNodeInfos {
  206. for _, diskInfo := range dn.DiskInfos {
  207. for _, vi := range diskInfo.VolumeInfos {
  208. for _, vid := range vids {
  209. if needle.VolumeId(vi.Id) == vid && vi.Collection != "" {
  210. found[vi.Collection] = true
  211. }
  212. }
  213. }
  214. for _, ecs := range diskInfo.EcShardInfos {
  215. for _, vid := range vids {
  216. if needle.VolumeId(ecs.Id) == vid && ecs.Collection != "" {
  217. found[ecs.Collection] = true
  218. }
  219. }
  220. }
  221. }
  222. }
  223. }
  224. }
  225. if len(found) == 0 {
  226. return nil
  227. }
  228. collections := []string{}
  229. for k, _ := range found {
  230. collections = append(collections, k)
  231. }
  232. sort.Strings(collections)
  233. return collections
  234. }
  235. func moveMountedShardToEcNode(commandEnv *CommandEnv, existingLocation *EcNode, collection string, vid needle.VolumeId, shardId erasure_coding.ShardId, destinationEcNode *EcNode, applyBalancing bool) (err error) {
  236. if !commandEnv.isLocked() {
  237. return fmt.Errorf("lock is lost")
  238. }
  239. copiedShardIds := []uint32{uint32(shardId)}
  240. if applyBalancing {
  241. existingServerAddress := pb.NewServerAddressFromDataNode(existingLocation.info)
  242. // ask destination node to copy shard and the ecx file from source node, and mount it
  243. copiedShardIds, err = oneServerCopyAndMountEcShardsFromSource(commandEnv.option.GrpcDialOption, destinationEcNode, []uint32{uint32(shardId)}, vid, collection, existingServerAddress)
  244. if err != nil {
  245. return err
  246. }
  247. // unmount the to be deleted shards
  248. err = unmountEcShards(commandEnv.option.GrpcDialOption, vid, existingServerAddress, copiedShardIds)
  249. if err != nil {
  250. return err
  251. }
  252. // ask source node to delete the shard, and maybe the ecx file
  253. err = sourceServerDeleteEcShards(commandEnv.option.GrpcDialOption, collection, vid, existingServerAddress, copiedShardIds)
  254. if err != nil {
  255. return err
  256. }
  257. fmt.Printf("moved ec shard %d.%d %s => %s\n", vid, shardId, existingLocation.info.Id, destinationEcNode.info.Id)
  258. }
  259. destinationEcNode.addEcVolumeShards(vid, collection, copiedShardIds)
  260. existingLocation.deleteEcVolumeShards(vid, copiedShardIds)
  261. return nil
  262. }
  263. func oneServerCopyAndMountEcShardsFromSource(grpcDialOption grpc.DialOption,
  264. targetServer *EcNode, shardIdsToCopy []uint32,
  265. volumeId needle.VolumeId, collection string, existingLocation pb.ServerAddress) (copiedShardIds []uint32, err error) {
  266. fmt.Printf("allocate %d.%v %s => %s\n", volumeId, shardIdsToCopy, existingLocation, targetServer.info.Id)
  267. targetAddress := pb.NewServerAddressFromDataNode(targetServer.info)
  268. err = operation.WithVolumeServerClient(false, targetAddress, grpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
  269. if targetAddress != existingLocation {
  270. fmt.Printf("copy %d.%v %s => %s\n", volumeId, shardIdsToCopy, existingLocation, targetServer.info.Id)
  271. _, copyErr := volumeServerClient.VolumeEcShardsCopy(context.Background(), &volume_server_pb.VolumeEcShardsCopyRequest{
  272. VolumeId: uint32(volumeId),
  273. Collection: collection,
  274. ShardIds: shardIdsToCopy,
  275. CopyEcxFile: true,
  276. CopyEcjFile: true,
  277. CopyVifFile: true,
  278. SourceDataNode: string(existingLocation),
  279. })
  280. if copyErr != nil {
  281. return fmt.Errorf("copy %d.%v %s => %s : %v\n", volumeId, shardIdsToCopy, existingLocation, targetServer.info.Id, copyErr)
  282. }
  283. }
  284. fmt.Printf("mount %d.%v on %s\n", volumeId, shardIdsToCopy, targetServer.info.Id)
  285. _, mountErr := volumeServerClient.VolumeEcShardsMount(context.Background(), &volume_server_pb.VolumeEcShardsMountRequest{
  286. VolumeId: uint32(volumeId),
  287. Collection: collection,
  288. ShardIds: shardIdsToCopy,
  289. })
  290. if mountErr != nil {
  291. return fmt.Errorf("mount %d.%v on %s : %v\n", volumeId, shardIdsToCopy, targetServer.info.Id, mountErr)
  292. }
  293. if targetAddress != existingLocation {
  294. copiedShardIds = shardIdsToCopy
  295. glog.V(0).Infof("%s ec volume %d deletes shards %+v", existingLocation, volumeId, copiedShardIds)
  296. }
  297. return nil
  298. })
  299. if err != nil {
  300. return
  301. }
  302. return
  303. }
  304. func eachDataNode(topo *master_pb.TopologyInfo, fn func(dc DataCenterId, rack RackId, dn *master_pb.DataNodeInfo)) {
  305. for _, dc := range topo.DataCenterInfos {
  306. for _, rack := range dc.RackInfos {
  307. for _, dn := range rack.DataNodeInfos {
  308. fn(DataCenterId(dc.Id), RackId(rack.Id), dn)
  309. }
  310. }
  311. }
  312. }
  313. func sortEcNodesByFreeslotsDescending(ecNodes []*EcNode) {
  314. slices.SortFunc(ecNodes, func(a, b *EcNode) int {
  315. return b.freeEcSlot - a.freeEcSlot
  316. })
  317. }
  318. func sortEcNodesByFreeslotsAscending(ecNodes []*EcNode) {
  319. slices.SortFunc(ecNodes, func(a, b *EcNode) int {
  320. return a.freeEcSlot - b.freeEcSlot
  321. })
  322. }
  323. // if the index node changed the freeEcSlot, need to keep every EcNode still sorted
  324. func ensureSortedEcNodes(data []*CandidateEcNode, index int, lessThan func(i, j int) bool) {
  325. for i := index - 1; i >= 0; i-- {
  326. if lessThan(i+1, i) {
  327. swap(data, i, i+1)
  328. } else {
  329. break
  330. }
  331. }
  332. for i := index + 1; i < len(data); i++ {
  333. if lessThan(i, i-1) {
  334. swap(data, i, i-1)
  335. } else {
  336. break
  337. }
  338. }
  339. }
  340. func swap(data []*CandidateEcNode, i, j int) {
  341. t := data[i]
  342. data[i] = data[j]
  343. data[j] = t
  344. }
  345. func countShards(ecShardInfos []*master_pb.VolumeEcShardInformationMessage) (count int) {
  346. for _, ecShardInfo := range ecShardInfos {
  347. shardBits := erasure_coding.ShardBits(ecShardInfo.EcIndexBits)
  348. count += shardBits.ShardIdCount()
  349. }
  350. return
  351. }
  352. func countFreeShardSlots(dn *master_pb.DataNodeInfo, diskType types.DiskType) (count int) {
  353. if dn.DiskInfos == nil {
  354. return 0
  355. }
  356. diskInfo := dn.DiskInfos[string(diskType)]
  357. if diskInfo == nil {
  358. return 0
  359. }
  360. return int(diskInfo.MaxVolumeCount-diskInfo.VolumeCount)*erasure_coding.DataShardsCount - countShards(diskInfo.EcShardInfos)
  361. }
  362. func (ecNode *EcNode) localShardIdCount(vid uint32) int {
  363. for _, diskInfo := range ecNode.info.DiskInfos {
  364. for _, ecShardInfo := range diskInfo.EcShardInfos {
  365. if vid == ecShardInfo.Id {
  366. shardBits := erasure_coding.ShardBits(ecShardInfo.EcIndexBits)
  367. return shardBits.ShardIdCount()
  368. }
  369. }
  370. }
  371. return 0
  372. }
  373. func collectEcVolumeServersByDc(topo *master_pb.TopologyInfo, selectedDataCenter string) (ecNodes []*EcNode, totalFreeEcSlots int) {
  374. eachDataNode(topo, func(dc DataCenterId, rack RackId, dn *master_pb.DataNodeInfo) {
  375. if selectedDataCenter != "" && selectedDataCenter != string(dc) {
  376. return
  377. }
  378. freeEcSlots := countFreeShardSlots(dn, types.HardDriveType)
  379. ecNodes = append(ecNodes, &EcNode{
  380. info: dn,
  381. dc: dc,
  382. rack: rack,
  383. freeEcSlot: int(freeEcSlots),
  384. })
  385. totalFreeEcSlots += freeEcSlots
  386. })
  387. return
  388. }
  389. func sourceServerDeleteEcShards(grpcDialOption grpc.DialOption, collection string, volumeId needle.VolumeId, sourceLocation pb.ServerAddress, toBeDeletedShardIds []uint32) error {
  390. fmt.Printf("delete %d.%v from %s\n", volumeId, toBeDeletedShardIds, sourceLocation)
  391. return operation.WithVolumeServerClient(false, sourceLocation, grpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
  392. _, deleteErr := volumeServerClient.VolumeEcShardsDelete(context.Background(), &volume_server_pb.VolumeEcShardsDeleteRequest{
  393. VolumeId: uint32(volumeId),
  394. Collection: collection,
  395. ShardIds: toBeDeletedShardIds,
  396. })
  397. return deleteErr
  398. })
  399. }
  400. func unmountEcShards(grpcDialOption grpc.DialOption, volumeId needle.VolumeId, sourceLocation pb.ServerAddress, toBeUnmountedhardIds []uint32) error {
  401. fmt.Printf("unmount %d.%v from %s\n", volumeId, toBeUnmountedhardIds, sourceLocation)
  402. return operation.WithVolumeServerClient(false, sourceLocation, grpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
  403. _, deleteErr := volumeServerClient.VolumeEcShardsUnmount(context.Background(), &volume_server_pb.VolumeEcShardsUnmountRequest{
  404. VolumeId: uint32(volumeId),
  405. ShardIds: toBeUnmountedhardIds,
  406. })
  407. return deleteErr
  408. })
  409. }
  410. func mountEcShards(grpcDialOption grpc.DialOption, collection string, volumeId needle.VolumeId, sourceLocation pb.ServerAddress, toBeMountedhardIds []uint32) error {
  411. fmt.Printf("mount %d.%v on %s\n", volumeId, toBeMountedhardIds, sourceLocation)
  412. return operation.WithVolumeServerClient(false, sourceLocation, grpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
  413. _, mountErr := volumeServerClient.VolumeEcShardsMount(context.Background(), &volume_server_pb.VolumeEcShardsMountRequest{
  414. VolumeId: uint32(volumeId),
  415. Collection: collection,
  416. ShardIds: toBeMountedhardIds,
  417. })
  418. return mountErr
  419. })
  420. }
  421. func ceilDivide(a, b int) int {
  422. var r int
  423. if (a % b) != 0 {
  424. r = 1
  425. }
  426. return (a / b) + r
  427. }
  428. func findEcVolumeShards(ecNode *EcNode, vid needle.VolumeId) erasure_coding.ShardBits {
  429. if diskInfo, found := ecNode.info.DiskInfos[string(types.HardDriveType)]; found {
  430. for _, shardInfo := range diskInfo.EcShardInfos {
  431. if needle.VolumeId(shardInfo.Id) == vid {
  432. return erasure_coding.ShardBits(shardInfo.EcIndexBits)
  433. }
  434. }
  435. }
  436. return 0
  437. }
  438. func (ecNode *EcNode) addEcVolumeShards(vid needle.VolumeId, collection string, shardIds []uint32) *EcNode {
  439. foundVolume := false
  440. diskInfo, found := ecNode.info.DiskInfos[string(types.HardDriveType)]
  441. if found {
  442. for _, shardInfo := range diskInfo.EcShardInfos {
  443. if needle.VolumeId(shardInfo.Id) == vid {
  444. oldShardBits := erasure_coding.ShardBits(shardInfo.EcIndexBits)
  445. newShardBits := oldShardBits
  446. for _, shardId := range shardIds {
  447. newShardBits = newShardBits.AddShardId(erasure_coding.ShardId(shardId))
  448. }
  449. shardInfo.EcIndexBits = uint32(newShardBits)
  450. ecNode.freeEcSlot -= newShardBits.ShardIdCount() - oldShardBits.ShardIdCount()
  451. foundVolume = true
  452. break
  453. }
  454. }
  455. } else {
  456. diskInfo = &master_pb.DiskInfo{
  457. Type: string(types.HardDriveType),
  458. }
  459. ecNode.info.DiskInfos[string(types.HardDriveType)] = diskInfo
  460. }
  461. if !foundVolume {
  462. var newShardBits erasure_coding.ShardBits
  463. for _, shardId := range shardIds {
  464. newShardBits = newShardBits.AddShardId(erasure_coding.ShardId(shardId))
  465. }
  466. diskInfo.EcShardInfos = append(diskInfo.EcShardInfos, &master_pb.VolumeEcShardInformationMessage{
  467. Id: uint32(vid),
  468. Collection: collection,
  469. EcIndexBits: uint32(newShardBits),
  470. DiskType: string(types.HardDriveType),
  471. })
  472. ecNode.freeEcSlot -= len(shardIds)
  473. }
  474. return ecNode
  475. }
  476. func (ecNode *EcNode) deleteEcVolumeShards(vid needle.VolumeId, shardIds []uint32) *EcNode {
  477. if diskInfo, found := ecNode.info.DiskInfos[string(types.HardDriveType)]; found {
  478. for _, shardInfo := range diskInfo.EcShardInfos {
  479. if needle.VolumeId(shardInfo.Id) == vid {
  480. oldShardBits := erasure_coding.ShardBits(shardInfo.EcIndexBits)
  481. newShardBits := oldShardBits
  482. for _, shardId := range shardIds {
  483. newShardBits = newShardBits.RemoveShardId(erasure_coding.ShardId(shardId))
  484. }
  485. shardInfo.EcIndexBits = uint32(newShardBits)
  486. ecNode.freeEcSlot -= newShardBits.ShardIdCount() - oldShardBits.ShardIdCount()
  487. }
  488. }
  489. }
  490. return ecNode
  491. }
  492. func groupByCount(data []*EcNode, identifierFn func(*EcNode) (id string, count int)) map[string]int {
  493. countMap := make(map[string]int)
  494. for _, d := range data {
  495. id, count := identifierFn(d)
  496. countMap[id] += count
  497. }
  498. return countMap
  499. }
  500. func groupBy(data []*EcNode, identifierFn func(*EcNode) (id string)) map[string][]*EcNode {
  501. groupMap := make(map[string][]*EcNode)
  502. for _, d := range data {
  503. id := identifierFn(d)
  504. groupMap[id] = append(groupMap[id], d)
  505. }
  506. return groupMap
  507. }
  508. type ecBalancer struct {
  509. commandEnv *CommandEnv
  510. ecNodes []*EcNode
  511. replicaPlacement *super_block.ReplicaPlacement
  512. applyBalancing bool
  513. maxParallelization int
  514. }
  515. func (ecb *ecBalancer) errorWaitGroup() *ErrorWaitGroup {
  516. return NewErrorWaitGroup(ecb.maxParallelization)
  517. }
  518. func (ecb *ecBalancer) racks() map[RackId]*EcRack {
  519. racks := make(map[RackId]*EcRack)
  520. for _, ecNode := range ecb.ecNodes {
  521. if racks[ecNode.rack] == nil {
  522. racks[ecNode.rack] = &EcRack{
  523. ecNodes: make(map[EcNodeId]*EcNode),
  524. }
  525. }
  526. racks[ecNode.rack].ecNodes[EcNodeId(ecNode.info.Id)] = ecNode
  527. racks[ecNode.rack].freeEcSlot += ecNode.freeEcSlot
  528. }
  529. return racks
  530. }
  531. func (ecb *ecBalancer) balanceEcVolumes(collection string) error {
  532. fmt.Printf("balanceEcVolumes %s\n", collection)
  533. if err := ecb.deleteDuplicatedEcShards(collection); err != nil {
  534. return fmt.Errorf("delete duplicated collection %s ec shards: %v", collection, err)
  535. }
  536. if err := ecb.balanceEcShardsAcrossRacks(collection); err != nil {
  537. return fmt.Errorf("balance across racks collection %s ec shards: %v", collection, err)
  538. }
  539. if err := ecb.balanceEcShardsWithinRacks(collection); err != nil {
  540. return fmt.Errorf("balance within racks collection %s ec shards: %v", collection, err)
  541. }
  542. return nil
  543. }
  544. func (ecb *ecBalancer) deleteDuplicatedEcShards(collection string) error {
  545. vidLocations := ecb.collectVolumeIdToEcNodes(collection)
  546. ewg := ecb.errorWaitGroup()
  547. for vid, locations := range vidLocations {
  548. ewg.Add(func() error {
  549. return ecb.doDeduplicateEcShards(collection, vid, locations)
  550. })
  551. }
  552. return ewg.Wait()
  553. }
  554. func (ecb *ecBalancer) doDeduplicateEcShards(collection string, vid needle.VolumeId, locations []*EcNode) error {
  555. // check whether this volume has ecNodes that are over average
  556. shardToLocations := make([][]*EcNode, erasure_coding.TotalShardsCount)
  557. for _, ecNode := range locations {
  558. shardBits := findEcVolumeShards(ecNode, vid)
  559. for _, shardId := range shardBits.ShardIds() {
  560. shardToLocations[shardId] = append(shardToLocations[shardId], ecNode)
  561. }
  562. }
  563. for shardId, ecNodes := range shardToLocations {
  564. if len(ecNodes) <= 1 {
  565. continue
  566. }
  567. sortEcNodesByFreeslotsAscending(ecNodes)
  568. fmt.Printf("ec shard %d.%d has %d copies, keeping %v\n", vid, shardId, len(ecNodes), ecNodes[0].info.Id)
  569. if !ecb.applyBalancing {
  570. continue
  571. }
  572. duplicatedShardIds := []uint32{uint32(shardId)}
  573. for _, ecNode := range ecNodes[1:] {
  574. if err := unmountEcShards(ecb.commandEnv.option.GrpcDialOption, vid, pb.NewServerAddressFromDataNode(ecNode.info), duplicatedShardIds); err != nil {
  575. return err
  576. }
  577. if err := sourceServerDeleteEcShards(ecb.commandEnv.option.GrpcDialOption, collection, vid, pb.NewServerAddressFromDataNode(ecNode.info), duplicatedShardIds); err != nil {
  578. return err
  579. }
  580. ecNode.deleteEcVolumeShards(vid, duplicatedShardIds)
  581. }
  582. }
  583. return nil
  584. }
  585. func (ecb *ecBalancer) balanceEcShardsAcrossRacks(collection string) error {
  586. // collect vid => []ecNode, since previous steps can change the locations
  587. vidLocations := ecb.collectVolumeIdToEcNodes(collection)
  588. // spread the ec shards evenly
  589. ewg := ecb.errorWaitGroup()
  590. for vid, locations := range vidLocations {
  591. ewg.Add(func() error {
  592. return ecb.doBalanceEcShardsAcrossRacks(collection, vid, locations)
  593. })
  594. }
  595. return ewg.Wait()
  596. }
  597. func countShardsByRack(vid needle.VolumeId, locations []*EcNode) map[string]int {
  598. return groupByCount(locations, func(ecNode *EcNode) (id string, count int) {
  599. shardBits := findEcVolumeShards(ecNode, vid)
  600. return string(ecNode.rack), shardBits.ShardIdCount()
  601. })
  602. }
  603. func (ecb *ecBalancer) doBalanceEcShardsAcrossRacks(collection string, vid needle.VolumeId, locations []*EcNode) error {
  604. racks := ecb.racks()
  605. // calculate average number of shards an ec rack should have for one volume
  606. averageShardsPerEcRack := ceilDivide(erasure_coding.TotalShardsCount, len(racks))
  607. // see the volume's shards are in how many racks, and how many in each rack
  608. rackToShardCount := countShardsByRack(vid, locations)
  609. rackEcNodesWithVid := groupBy(locations, func(ecNode *EcNode) string {
  610. return string(ecNode.rack)
  611. })
  612. // ecShardsToMove = select overflown ec shards from racks with ec shard counts > averageShardsPerEcRack
  613. ecShardsToMove := make(map[erasure_coding.ShardId]*EcNode)
  614. for rackId, count := range rackToShardCount {
  615. if count <= averageShardsPerEcRack {
  616. continue
  617. }
  618. possibleEcNodes := rackEcNodesWithVid[rackId]
  619. for shardId, ecNode := range pickNEcShardsToMoveFrom(possibleEcNodes, vid, count-averageShardsPerEcRack) {
  620. ecShardsToMove[shardId] = ecNode
  621. }
  622. }
  623. for shardId, ecNode := range ecShardsToMove {
  624. rackId, err := ecb.pickRackToBalanceShardsInto(racks, rackToShardCount)
  625. if err != nil {
  626. fmt.Printf("ec shard %d.%d at %s can not find a destination rack:\n%s\n", vid, shardId, ecNode.info.Id, err.Error())
  627. continue
  628. }
  629. var possibleDestinationEcNodes []*EcNode
  630. for _, n := range racks[rackId].ecNodes {
  631. possibleDestinationEcNodes = append(possibleDestinationEcNodes, n)
  632. }
  633. err = ecb.pickOneEcNodeAndMoveOneShard(ecNode, collection, vid, shardId, possibleDestinationEcNodes)
  634. if err != nil {
  635. return err
  636. }
  637. rackToShardCount[string(rackId)] += 1
  638. rackToShardCount[string(ecNode.rack)] -= 1
  639. racks[rackId].freeEcSlot -= 1
  640. racks[ecNode.rack].freeEcSlot += 1
  641. }
  642. return nil
  643. }
  644. func (ecb *ecBalancer) pickRackToBalanceShardsInto(rackToEcNodes map[RackId]*EcRack, rackToShardCount map[string]int) (RackId, error) {
  645. targets := []RackId{}
  646. targetShards := -1
  647. for _, shards := range rackToShardCount {
  648. if shards > targetShards {
  649. targetShards = shards
  650. }
  651. }
  652. details := ""
  653. for rackId, rack := range rackToEcNodes {
  654. shards := rackToShardCount[string(rackId)]
  655. if rack.freeEcSlot <= 0 {
  656. details += fmt.Sprintf(" Skipped %s because it has no free slots\n", rackId)
  657. continue
  658. }
  659. if ecb.replicaPlacement != nil && shards >= ecb.replicaPlacement.DiffRackCount {
  660. details += fmt.Sprintf(" Skipped %s because shards %d >= replica placement limit for other racks (%d)\n", rackId, shards, ecb.replicaPlacement.DiffRackCount)
  661. continue
  662. }
  663. if shards < targetShards {
  664. // Favor racks with less shards, to ensure an uniform distribution.
  665. targets = nil
  666. targetShards = shards
  667. }
  668. if shards == targetShards {
  669. targets = append(targets, rackId)
  670. }
  671. }
  672. if len(targets) == 0 {
  673. return "", errors.New(details)
  674. }
  675. return targets[rand.IntN(len(targets))], nil
  676. }
  677. func (ecb *ecBalancer) balanceEcShardsWithinRacks(collection string) error {
  678. // collect vid => []ecNode, since previous steps can change the locations
  679. vidLocations := ecb.collectVolumeIdToEcNodes(collection)
  680. racks := ecb.racks()
  681. // spread the ec shards evenly
  682. ewg := ecb.errorWaitGroup()
  683. for vid, locations := range vidLocations {
  684. // see the volume's shards are in how many racks, and how many in each rack
  685. rackToShardCount := countShardsByRack(vid, locations)
  686. rackEcNodesWithVid := groupBy(locations, func(ecNode *EcNode) string {
  687. return string(ecNode.rack)
  688. })
  689. for rackId, _ := range rackToShardCount {
  690. var possibleDestinationEcNodes []*EcNode
  691. for _, n := range racks[RackId(rackId)].ecNodes {
  692. if _, found := n.info.DiskInfos[string(types.HardDriveType)]; found {
  693. possibleDestinationEcNodes = append(possibleDestinationEcNodes, n)
  694. }
  695. }
  696. sourceEcNodes := rackEcNodesWithVid[rackId]
  697. averageShardsPerEcNode := ceilDivide(rackToShardCount[rackId], len(possibleDestinationEcNodes))
  698. ewg.Add(func() error {
  699. return ecb.doBalanceEcShardsWithinOneRack(averageShardsPerEcNode, collection, vid, sourceEcNodes, possibleDestinationEcNodes)
  700. })
  701. }
  702. }
  703. return ewg.Wait()
  704. }
  705. func (ecb *ecBalancer) doBalanceEcShardsWithinOneRack(averageShardsPerEcNode int, collection string, vid needle.VolumeId, existingLocations, possibleDestinationEcNodes []*EcNode) error {
  706. for _, ecNode := range existingLocations {
  707. shardBits := findEcVolumeShards(ecNode, vid)
  708. overLimitCount := shardBits.ShardIdCount() - averageShardsPerEcNode
  709. for _, shardId := range shardBits.ShardIds() {
  710. if overLimitCount <= 0 {
  711. break
  712. }
  713. fmt.Printf("%s has %d overlimit, moving ec shard %d.%d\n", ecNode.info.Id, overLimitCount, vid, shardId)
  714. err := ecb.pickOneEcNodeAndMoveOneShard(ecNode, collection, vid, shardId, possibleDestinationEcNodes)
  715. if err != nil {
  716. return err
  717. }
  718. overLimitCount--
  719. }
  720. }
  721. return nil
  722. }
  723. func (ecb *ecBalancer) balanceEcRacks() error {
  724. // balance one rack for all ec shards
  725. ewg := ecb.errorWaitGroup()
  726. for _, ecRack := range ecb.racks() {
  727. ewg.Add(func() error {
  728. return ecb.doBalanceEcRack(ecRack)
  729. })
  730. }
  731. return ewg.Wait()
  732. }
  733. func (ecb *ecBalancer) doBalanceEcRack(ecRack *EcRack) error {
  734. if len(ecRack.ecNodes) <= 1 {
  735. return nil
  736. }
  737. var rackEcNodes []*EcNode
  738. for _, node := range ecRack.ecNodes {
  739. rackEcNodes = append(rackEcNodes, node)
  740. }
  741. ecNodeIdToShardCount := groupByCount(rackEcNodes, func(ecNode *EcNode) (id string, count int) {
  742. diskInfo, found := ecNode.info.DiskInfos[string(types.HardDriveType)]
  743. if !found {
  744. return
  745. }
  746. for _, ecShardInfo := range diskInfo.EcShardInfos {
  747. count += erasure_coding.ShardBits(ecShardInfo.EcIndexBits).ShardIdCount()
  748. }
  749. return ecNode.info.Id, count
  750. })
  751. var totalShardCount int
  752. for _, count := range ecNodeIdToShardCount {
  753. totalShardCount += count
  754. }
  755. averageShardCount := ceilDivide(totalShardCount, len(rackEcNodes))
  756. hasMove := true
  757. for hasMove {
  758. hasMove = false
  759. slices.SortFunc(rackEcNodes, func(a, b *EcNode) int {
  760. return b.freeEcSlot - a.freeEcSlot
  761. })
  762. emptyNode, fullNode := rackEcNodes[0], rackEcNodes[len(rackEcNodes)-1]
  763. emptyNodeShardCount, fullNodeShardCount := ecNodeIdToShardCount[emptyNode.info.Id], ecNodeIdToShardCount[fullNode.info.Id]
  764. if fullNodeShardCount > averageShardCount && emptyNodeShardCount+1 <= averageShardCount {
  765. emptyNodeIds := make(map[uint32]bool)
  766. if emptyDiskInfo, found := emptyNode.info.DiskInfos[string(types.HardDriveType)]; found {
  767. for _, shards := range emptyDiskInfo.EcShardInfos {
  768. emptyNodeIds[shards.Id] = true
  769. }
  770. }
  771. if fullDiskInfo, found := fullNode.info.DiskInfos[string(types.HardDriveType)]; found {
  772. for _, shards := range fullDiskInfo.EcShardInfos {
  773. if _, found := emptyNodeIds[shards.Id]; !found {
  774. for _, shardId := range erasure_coding.ShardBits(shards.EcIndexBits).ShardIds() {
  775. fmt.Printf("%s moves ec shards %d.%d to %s\n", fullNode.info.Id, shards.Id, shardId, emptyNode.info.Id)
  776. err := moveMountedShardToEcNode(ecb.commandEnv, fullNode, shards.Collection, needle.VolumeId(shards.Id), shardId, emptyNode, ecb.applyBalancing)
  777. if err != nil {
  778. return err
  779. }
  780. ecNodeIdToShardCount[emptyNode.info.Id]++
  781. ecNodeIdToShardCount[fullNode.info.Id]--
  782. hasMove = true
  783. break
  784. }
  785. break
  786. }
  787. }
  788. }
  789. }
  790. }
  791. return nil
  792. }
  793. func (ecb *ecBalancer) pickEcNodeToBalanceShardsInto(vid needle.VolumeId, existingLocation *EcNode, possibleDestinations []*EcNode) (*EcNode, error) {
  794. if existingLocation == nil {
  795. return nil, fmt.Errorf("INTERNAL: missing source nodes")
  796. }
  797. if len(possibleDestinations) == 0 {
  798. return nil, fmt.Errorf("INTERNAL: missing destination nodes")
  799. }
  800. nodeShards := map[*EcNode]int{}
  801. for _, node := range possibleDestinations {
  802. nodeShards[node] = findEcVolumeShards(node, vid).ShardIdCount()
  803. }
  804. targets := []*EcNode{}
  805. targetShards := -1
  806. for _, shards := range nodeShards {
  807. if shards > targetShards {
  808. targetShards = shards
  809. }
  810. }
  811. details := ""
  812. for _, node := range possibleDestinations {
  813. if node.info.Id == existingLocation.info.Id {
  814. continue
  815. }
  816. if node.freeEcSlot <= 0 {
  817. details += fmt.Sprintf(" Skipped %s because it has no free slots\n", node.info.Id)
  818. continue
  819. }
  820. shards := nodeShards[node]
  821. if ecb.replicaPlacement != nil && shards >= ecb.replicaPlacement.SameRackCount {
  822. details += fmt.Sprintf(" Skipped %s because shards %d >= replica placement limit for the rack (%d)\n", node.info.Id, shards, ecb.replicaPlacement.SameRackCount)
  823. continue
  824. }
  825. if shards < targetShards {
  826. // Favor nodes with less shards, to ensure an uniform distribution.
  827. targets = nil
  828. targetShards = shards
  829. }
  830. if shards == targetShards {
  831. targets = append(targets, node)
  832. }
  833. }
  834. if len(targets) == 0 {
  835. return nil, errors.New(details)
  836. }
  837. return targets[rand.IntN(len(targets))], nil
  838. }
  839. func (ecb *ecBalancer) pickOneEcNodeAndMoveOneShard(existingLocation *EcNode, collection string, vid needle.VolumeId, shardId erasure_coding.ShardId, possibleDestinationEcNodes []*EcNode) error {
  840. destNode, err := ecb.pickEcNodeToBalanceShardsInto(vid, existingLocation, possibleDestinationEcNodes)
  841. if err != nil {
  842. fmt.Printf("WARNING: Could not find suitable taget node for %d.%d:\n%s", vid, shardId, err.Error())
  843. return nil
  844. }
  845. fmt.Printf("%s moves ec shard %d.%d to %s\n", existingLocation.info.Id, vid, shardId, destNode.info.Id)
  846. return moveMountedShardToEcNode(ecb.commandEnv, existingLocation, collection, vid, shardId, destNode, ecb.applyBalancing)
  847. }
  848. func pickNEcShardsToMoveFrom(ecNodes []*EcNode, vid needle.VolumeId, n int) map[erasure_coding.ShardId]*EcNode {
  849. picked := make(map[erasure_coding.ShardId]*EcNode)
  850. var candidateEcNodes []*CandidateEcNode
  851. for _, ecNode := range ecNodes {
  852. shardBits := findEcVolumeShards(ecNode, vid)
  853. if shardBits.ShardIdCount() > 0 {
  854. candidateEcNodes = append(candidateEcNodes, &CandidateEcNode{
  855. ecNode: ecNode,
  856. shardCount: shardBits.ShardIdCount(),
  857. })
  858. }
  859. }
  860. slices.SortFunc(candidateEcNodes, func(a, b *CandidateEcNode) int {
  861. return b.shardCount - a.shardCount
  862. })
  863. for i := 0; i < n; i++ {
  864. selectedEcNodeIndex := -1
  865. for i, candidateEcNode := range candidateEcNodes {
  866. shardBits := findEcVolumeShards(candidateEcNode.ecNode, vid)
  867. if shardBits > 0 {
  868. selectedEcNodeIndex = i
  869. for _, shardId := range shardBits.ShardIds() {
  870. candidateEcNode.shardCount--
  871. picked[shardId] = candidateEcNode.ecNode
  872. candidateEcNode.ecNode.deleteEcVolumeShards(vid, []uint32{uint32(shardId)})
  873. break
  874. }
  875. break
  876. }
  877. }
  878. if selectedEcNodeIndex >= 0 {
  879. ensureSortedEcNodes(candidateEcNodes, selectedEcNodeIndex, func(i, j int) bool {
  880. return candidateEcNodes[i].shardCount > candidateEcNodes[j].shardCount
  881. })
  882. }
  883. }
  884. return picked
  885. }
  886. func (ecb *ecBalancer) collectVolumeIdToEcNodes(collection string) map[needle.VolumeId][]*EcNode {
  887. vidLocations := make(map[needle.VolumeId][]*EcNode)
  888. for _, ecNode := range ecb.ecNodes {
  889. diskInfo, found := ecNode.info.DiskInfos[string(types.HardDriveType)]
  890. if !found {
  891. continue
  892. }
  893. for _, shardInfo := range diskInfo.EcShardInfos {
  894. // ignore if not in current collection
  895. if shardInfo.Collection == collection {
  896. vidLocations[needle.VolumeId(shardInfo.Id)] = append(vidLocations[needle.VolumeId(shardInfo.Id)], ecNode)
  897. }
  898. }
  899. }
  900. return vidLocations
  901. }
  902. func EcBalance(commandEnv *CommandEnv, collections []string, dc string, ecReplicaPlacement *super_block.ReplicaPlacement, maxParallelization int, applyBalancing bool) (err error) {
  903. if len(collections) == 0 {
  904. return fmt.Errorf("no collections to balance")
  905. }
  906. // collect all ec nodes
  907. allEcNodes, totalFreeEcSlots, err := collectEcNodesForDC(commandEnv, dc)
  908. if err != nil {
  909. return err
  910. }
  911. if totalFreeEcSlots < 1 {
  912. return fmt.Errorf("no free ec shard slots. only %d left", totalFreeEcSlots)
  913. }
  914. ecb := &ecBalancer{
  915. commandEnv: commandEnv,
  916. ecNodes: allEcNodes,
  917. replicaPlacement: ecReplicaPlacement,
  918. applyBalancing: applyBalancing,
  919. maxParallelization: maxParallelization,
  920. }
  921. for _, c := range collections {
  922. if err = ecb.balanceEcVolumes(c); err != nil {
  923. return err
  924. }
  925. }
  926. if err := ecb.balanceEcRacks(); err != nil {
  927. return fmt.Errorf("balance ec racks: %v", err)
  928. }
  929. return nil
  930. }