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.

1104 lines
34 KiB

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