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.

933 lines
30 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, averageShardsPerEcRack)
  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(averageShardsPerEcRack, 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, averageShardsPerEcRack 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 >= averageShardsPerEcRack {
  505. details += fmt.Sprintf(" Skipped %s because shards %d >= averageShards (%d)\n", rackId, shards, averageShardsPerEcRack)
  506. continue
  507. }
  508. if shards < targetShards {
  509. // Favor racks with less shards, to ensure an uniform distribution.
  510. targets = nil
  511. targetShards = shards
  512. }
  513. if shards == targetShards {
  514. targets = append(targets, rackId)
  515. }
  516. }
  517. if len(targets) == 0 {
  518. return "", errors.New(details)
  519. }
  520. return targets[rand.IntN(len(targets))], nil
  521. }
  522. func (ecb *ecBalancer) balanceEcShardsWithinRacks(collection string) error {
  523. // collect vid => []ecNode, since previous steps can change the locations
  524. vidLocations := ecb.collectVolumeIdToEcNodes(collection)
  525. racks := ecb.racks()
  526. // spread the ec shards evenly
  527. for vid, locations := range vidLocations {
  528. // see the volume's shards are in how many racks, and how many in each rack
  529. rackToShardCount := countShardsByRack(vid, locations)
  530. rackEcNodesWithVid := groupBy(locations, func(ecNode *EcNode) string {
  531. return string(ecNode.rack)
  532. })
  533. for rackId, _ := range rackToShardCount {
  534. var possibleDestinationEcNodes []*EcNode
  535. for _, n := range racks[RackId(rackId)].ecNodes {
  536. if _, found := n.info.DiskInfos[string(types.HardDriveType)]; found {
  537. possibleDestinationEcNodes = append(possibleDestinationEcNodes, n)
  538. }
  539. }
  540. sourceEcNodes := rackEcNodesWithVid[rackId]
  541. averageShardsPerEcNode := ceilDivide(rackToShardCount[rackId], len(possibleDestinationEcNodes))
  542. if err := ecb.doBalanceEcShardsWithinOneRack(averageShardsPerEcNode, collection, vid, sourceEcNodes, possibleDestinationEcNodes); err != nil {
  543. return err
  544. }
  545. }
  546. }
  547. return nil
  548. }
  549. func (ecb *ecBalancer) doBalanceEcShardsWithinOneRack(averageShardsPerEcNode int, collection string, vid needle.VolumeId, existingLocations, possibleDestinationEcNodes []*EcNode) error {
  550. for _, ecNode := range existingLocations {
  551. shardBits := findEcVolumeShards(ecNode, vid)
  552. overLimitCount := shardBits.ShardIdCount() - averageShardsPerEcNode
  553. for _, shardId := range shardBits.ShardIds() {
  554. if overLimitCount <= 0 {
  555. break
  556. }
  557. fmt.Printf("%s has %d overlimit, moving ec shard %d.%d\n", ecNode.info.Id, overLimitCount, vid, shardId)
  558. err := ecb.pickOneEcNodeAndMoveOneShard(averageShardsPerEcNode, ecNode, collection, vid, shardId, possibleDestinationEcNodes)
  559. if err != nil {
  560. return err
  561. }
  562. overLimitCount--
  563. }
  564. }
  565. return nil
  566. }
  567. func (ecb *ecBalancer) balanceEcRacks() error {
  568. // balance one rack for all ec shards
  569. for _, ecRack := range ecb.racks() {
  570. if err := ecb.doBalanceEcRack(ecRack); err != nil {
  571. return err
  572. }
  573. }
  574. return nil
  575. }
  576. func (ecb *ecBalancer) doBalanceEcRack(ecRack *EcRack) error {
  577. if len(ecRack.ecNodes) <= 1 {
  578. return nil
  579. }
  580. var rackEcNodes []*EcNode
  581. for _, node := range ecRack.ecNodes {
  582. rackEcNodes = append(rackEcNodes, node)
  583. }
  584. ecNodeIdToShardCount := groupByCount(rackEcNodes, func(ecNode *EcNode) (id string, count int) {
  585. diskInfo, found := ecNode.info.DiskInfos[string(types.HardDriveType)]
  586. if !found {
  587. return
  588. }
  589. for _, ecShardInfo := range diskInfo.EcShardInfos {
  590. count += erasure_coding.ShardBits(ecShardInfo.EcIndexBits).ShardIdCount()
  591. }
  592. return ecNode.info.Id, count
  593. })
  594. var totalShardCount int
  595. for _, count := range ecNodeIdToShardCount {
  596. totalShardCount += count
  597. }
  598. averageShardCount := ceilDivide(totalShardCount, len(rackEcNodes))
  599. hasMove := true
  600. for hasMove {
  601. hasMove = false
  602. slices.SortFunc(rackEcNodes, func(a, b *EcNode) int {
  603. return b.freeEcSlot - a.freeEcSlot
  604. })
  605. emptyNode, fullNode := rackEcNodes[0], rackEcNodes[len(rackEcNodes)-1]
  606. emptyNodeShardCount, fullNodeShardCount := ecNodeIdToShardCount[emptyNode.info.Id], ecNodeIdToShardCount[fullNode.info.Id]
  607. if fullNodeShardCount > averageShardCount && emptyNodeShardCount+1 <= averageShardCount {
  608. emptyNodeIds := make(map[uint32]bool)
  609. if emptyDiskInfo, found := emptyNode.info.DiskInfos[string(types.HardDriveType)]; found {
  610. for _, shards := range emptyDiskInfo.EcShardInfos {
  611. emptyNodeIds[shards.Id] = true
  612. }
  613. }
  614. if fullDiskInfo, found := fullNode.info.DiskInfos[string(types.HardDriveType)]; found {
  615. for _, shards := range fullDiskInfo.EcShardInfos {
  616. if _, found := emptyNodeIds[shards.Id]; !found {
  617. for _, shardId := range erasure_coding.ShardBits(shards.EcIndexBits).ShardIds() {
  618. fmt.Printf("%s moves ec shards %d.%d to %s\n", fullNode.info.Id, shards.Id, shardId, emptyNode.info.Id)
  619. err := moveMountedShardToEcNode(ecb.commandEnv, fullNode, shards.Collection, needle.VolumeId(shards.Id), shardId, emptyNode, ecb.applyBalancing)
  620. if err != nil {
  621. return err
  622. }
  623. ecNodeIdToShardCount[emptyNode.info.Id]++
  624. ecNodeIdToShardCount[fullNode.info.Id]--
  625. hasMove = true
  626. break
  627. }
  628. break
  629. }
  630. }
  631. }
  632. }
  633. }
  634. return nil
  635. }
  636. func (ecb *ecBalancer) pickEcNodeToBalanceShardsInto(vid needle.VolumeId, existingLocation *EcNode, possibleDestinations []*EcNode, averageShardsPerEcNode int) (*EcNode, error) {
  637. if existingLocation == nil {
  638. return nil, fmt.Errorf("INTERNAL: missing source nodes")
  639. }
  640. if len(possibleDestinations) == 0 {
  641. return nil, fmt.Errorf("INTERNAL: missing destination nodes")
  642. }
  643. nodeShards := map[*EcNode]int{}
  644. for _, node := range possibleDestinations {
  645. nodeShards[node] = findEcVolumeShards(node, vid).ShardIdCount()
  646. }
  647. targets := []*EcNode{}
  648. targetShards := -1
  649. for _, shards := range nodeShards {
  650. if shards > targetShards {
  651. targetShards = shards
  652. }
  653. }
  654. details := ""
  655. for _, node := range possibleDestinations {
  656. if node.info.Id == existingLocation.info.Id {
  657. continue
  658. }
  659. if node.freeEcSlot <= 0 {
  660. details += fmt.Sprintf(" Skipped %s because it has no free slots\n", node.info.Id)
  661. continue
  662. }
  663. shards := nodeShards[node]
  664. if ecb.replicaPlacement != nil && shards >= ecb.replicaPlacement.SameRackCount {
  665. details += fmt.Sprintf(" Skipped %s because shards %d >= replica placement limit for the rack (%d)\n", node.info.Id, shards, ecb.replicaPlacement.SameRackCount)
  666. continue
  667. }
  668. if shards >= averageShardsPerEcNode {
  669. details += fmt.Sprintf(" Skipped %s because shards %d >= averageShards (%d)\n",
  670. node.info.Id, shards, averageShardsPerEcNode)
  671. continue
  672. }
  673. if shards < targetShards {
  674. // Favor nodes with less shards, to ensure an uniform distribution.
  675. targets = nil
  676. targetShards = shards
  677. }
  678. if shards == targetShards {
  679. targets = append(targets, node)
  680. }
  681. }
  682. if len(targets) == 0 {
  683. return nil, errors.New(details)
  684. }
  685. return targets[rand.IntN(len(targets))], nil
  686. }
  687. // TODO: Maybe remove averages constraints? We don't need those anymore now that we're properly balancing shards.
  688. func (ecb *ecBalancer) pickOneEcNodeAndMoveOneShard(averageShardsPerEcNode int, existingLocation *EcNode, collection string, vid needle.VolumeId, shardId erasure_coding.ShardId, possibleDestinationEcNodes []*EcNode) error {
  689. destNode, err := ecb.pickEcNodeToBalanceShardsInto(vid, existingLocation, possibleDestinationEcNodes, averageShardsPerEcNode)
  690. if err != nil {
  691. fmt.Printf("WARNING: Could not find suitable taget node for %d.%d:\n%s", vid, shardId, err.Error())
  692. return nil
  693. }
  694. fmt.Printf("%s moves ec shard %d.%d to %s\n", existingLocation.info.Id, vid, shardId, destNode.info.Id)
  695. return moveMountedShardToEcNode(ecb.commandEnv, existingLocation, collection, vid, shardId, destNode, ecb.applyBalancing)
  696. }
  697. func pickNEcShardsToMoveFrom(ecNodes []*EcNode, vid needle.VolumeId, n int) map[erasure_coding.ShardId]*EcNode {
  698. picked := make(map[erasure_coding.ShardId]*EcNode)
  699. var candidateEcNodes []*CandidateEcNode
  700. for _, ecNode := range ecNodes {
  701. shardBits := findEcVolumeShards(ecNode, vid)
  702. if shardBits.ShardIdCount() > 0 {
  703. candidateEcNodes = append(candidateEcNodes, &CandidateEcNode{
  704. ecNode: ecNode,
  705. shardCount: shardBits.ShardIdCount(),
  706. })
  707. }
  708. }
  709. slices.SortFunc(candidateEcNodes, func(a, b *CandidateEcNode) int {
  710. return b.shardCount - a.shardCount
  711. })
  712. for i := 0; i < n; i++ {
  713. selectedEcNodeIndex := -1
  714. for i, candidateEcNode := range candidateEcNodes {
  715. shardBits := findEcVolumeShards(candidateEcNode.ecNode, vid)
  716. if shardBits > 0 {
  717. selectedEcNodeIndex = i
  718. for _, shardId := range shardBits.ShardIds() {
  719. candidateEcNode.shardCount--
  720. picked[shardId] = candidateEcNode.ecNode
  721. candidateEcNode.ecNode.deleteEcVolumeShards(vid, []uint32{uint32(shardId)})
  722. break
  723. }
  724. break
  725. }
  726. }
  727. if selectedEcNodeIndex >= 0 {
  728. ensureSortedEcNodes(candidateEcNodes, selectedEcNodeIndex, func(i, j int) bool {
  729. return candidateEcNodes[i].shardCount > candidateEcNodes[j].shardCount
  730. })
  731. }
  732. }
  733. return picked
  734. }
  735. func (ecb *ecBalancer) collectVolumeIdToEcNodes(collection string) map[needle.VolumeId][]*EcNode {
  736. vidLocations := make(map[needle.VolumeId][]*EcNode)
  737. for _, ecNode := range ecb.ecNodes {
  738. diskInfo, found := ecNode.info.DiskInfos[string(types.HardDriveType)]
  739. if !found {
  740. continue
  741. }
  742. for _, shardInfo := range diskInfo.EcShardInfos {
  743. // ignore if not in current collection
  744. if shardInfo.Collection == collection {
  745. vidLocations[needle.VolumeId(shardInfo.Id)] = append(vidLocations[needle.VolumeId(shardInfo.Id)], ecNode)
  746. }
  747. }
  748. }
  749. return vidLocations
  750. }
  751. // TODO: Unused, delete me.
  752. func (ecb *ecBalancer) volumeIdToReplicaPlacement(vid needle.VolumeId) (*super_block.ReplicaPlacement, error) {
  753. for _, ecNode := range ecb.ecNodes {
  754. for _, diskInfo := range ecNode.info.DiskInfos {
  755. for _, volumeInfo := range diskInfo.VolumeInfos {
  756. if needle.VolumeId(volumeInfo.Id) == vid {
  757. return super_block.NewReplicaPlacementFromByte(byte(volumeInfo.ReplicaPlacement))
  758. }
  759. }
  760. for _, ecShardInfo := range diskInfo.EcShardInfos {
  761. if needle.VolumeId(ecShardInfo.Id) == vid {
  762. return ecb.replicaPlacement, nil
  763. }
  764. }
  765. }
  766. }
  767. return nil, fmt.Errorf("failed to resolve replica placement for volume ID %d", vid)
  768. }
  769. func EcBalance(commandEnv *CommandEnv, collections []string, dc string, ecReplicaPlacement *super_block.ReplicaPlacement, applyBalancing bool) (err error) {
  770. if len(collections) == 0 {
  771. return fmt.Errorf("no collections to balance")
  772. }
  773. // collect all ec nodes
  774. allEcNodes, totalFreeEcSlots, err := collectEcNodes(commandEnv, dc)
  775. if err != nil {
  776. return err
  777. }
  778. if totalFreeEcSlots < 1 {
  779. return fmt.Errorf("no free ec shard slots. only %d left", totalFreeEcSlots)
  780. }
  781. ecb := &ecBalancer{
  782. commandEnv: commandEnv,
  783. ecNodes: allEcNodes,
  784. replicaPlacement: ecReplicaPlacement,
  785. applyBalancing: applyBalancing,
  786. }
  787. for _, c := range collections {
  788. if err = ecb.balanceEcVolumes(c); err != nil {
  789. return err
  790. }
  791. }
  792. if err := ecb.balanceEcRacks(); err != nil {
  793. return fmt.Errorf("balance ec racks: %v", err)
  794. }
  795. return nil
  796. }