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.

904 lines
28 KiB

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