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.

925 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. func collectRacks(allEcNodes []*EcNode) map[RackId]*EcRack {
  353. // collect racks info
  354. racks := make(map[RackId]*EcRack)
  355. for _, ecNode := range allEcNodes {
  356. if racks[ecNode.rack] == nil {
  357. racks[ecNode.rack] = &EcRack{
  358. ecNodes: make(map[EcNodeId]*EcNode),
  359. }
  360. }
  361. racks[ecNode.rack].ecNodes[EcNodeId(ecNode.info.Id)] = ecNode
  362. racks[ecNode.rack].freeEcSlot += ecNode.freeEcSlot
  363. }
  364. return racks
  365. }
  366. func balanceEcVolumes(commandEnv *CommandEnv, collection string, allEcNodes []*EcNode, racks map[RackId]*EcRack, applyBalancing bool) error {
  367. fmt.Printf("balanceEcVolumes %s\n", collection)
  368. if err := deleteDuplicatedEcShards(commandEnv, allEcNodes, collection, applyBalancing); err != nil {
  369. return fmt.Errorf("delete duplicated collection %s ec shards: %v", collection, err)
  370. }
  371. if err := balanceEcShardsAcrossRacks(commandEnv, allEcNodes, racks, collection, applyBalancing); err != nil {
  372. return fmt.Errorf("balance across racks collection %s ec shards: %v", collection, err)
  373. }
  374. if err := balanceEcShardsWithinRacks(commandEnv, allEcNodes, racks, collection, applyBalancing); err != nil {
  375. return fmt.Errorf("balance within racks collection %s ec shards: %v", collection, err)
  376. }
  377. return nil
  378. }
  379. func deleteDuplicatedEcShards(commandEnv *CommandEnv, allEcNodes []*EcNode, collection string, applyBalancing bool) error {
  380. // vid => []ecNode
  381. vidLocations := collectVolumeIdToEcNodes(allEcNodes, collection)
  382. // deduplicate ec shards
  383. for vid, locations := range vidLocations {
  384. if err := doDeduplicateEcShards(commandEnv, collection, vid, locations, applyBalancing); err != nil {
  385. return err
  386. }
  387. }
  388. return nil
  389. }
  390. func doDeduplicateEcShards(commandEnv *CommandEnv, collection string, vid needle.VolumeId, locations []*EcNode, applyBalancing bool) error {
  391. // check whether this volume has ecNodes that are over average
  392. shardToLocations := make([][]*EcNode, erasure_coding.TotalShardsCount)
  393. for _, ecNode := range locations {
  394. shardBits := findEcVolumeShards(ecNode, vid)
  395. for _, shardId := range shardBits.ShardIds() {
  396. shardToLocations[shardId] = append(shardToLocations[shardId], ecNode)
  397. }
  398. }
  399. for shardId, ecNodes := range shardToLocations {
  400. if len(ecNodes) <= 1 {
  401. continue
  402. }
  403. sortEcNodesByFreeslotsAscending(ecNodes)
  404. fmt.Printf("ec shard %d.%d has %d copies, keeping %v\n", vid, shardId, len(ecNodes), ecNodes[0].info.Id)
  405. if !applyBalancing {
  406. continue
  407. }
  408. duplicatedShardIds := []uint32{uint32(shardId)}
  409. for _, ecNode := range ecNodes[1:] {
  410. if err := unmountEcShards(commandEnv.option.GrpcDialOption, vid, pb.NewServerAddressFromDataNode(ecNode.info), duplicatedShardIds); err != nil {
  411. return err
  412. }
  413. if err := sourceServerDeleteEcShards(commandEnv.option.GrpcDialOption, collection, vid, pb.NewServerAddressFromDataNode(ecNode.info), duplicatedShardIds); err != nil {
  414. return err
  415. }
  416. ecNode.deleteEcVolumeShards(vid, duplicatedShardIds)
  417. }
  418. }
  419. return nil
  420. }
  421. func balanceEcShardsAcrossRacks(commandEnv *CommandEnv, allEcNodes []*EcNode, racks map[RackId]*EcRack, collection string, applyBalancing bool) error {
  422. // collect vid => []ecNode, since previous steps can change the locations
  423. vidLocations := collectVolumeIdToEcNodes(allEcNodes, collection)
  424. // spread the ec shards evenly
  425. for vid, locations := range vidLocations {
  426. if err := doBalanceEcShardsAcrossRacks(commandEnv, collection, vid, locations, racks, applyBalancing); err != nil {
  427. return err
  428. }
  429. }
  430. return nil
  431. }
  432. func countShardsByRack(vid needle.VolumeId, locations []*EcNode) map[string]int {
  433. return groupByCount(locations, func(ecNode *EcNode) (id string, count int) {
  434. shardBits := findEcVolumeShards(ecNode, vid)
  435. return string(ecNode.rack), shardBits.ShardIdCount()
  436. })
  437. }
  438. // TODO: Maybe remove averages constraints? We don't need those anymore now that we're properly balancing shards.
  439. func doBalanceEcShardsAcrossRacks(commandEnv *CommandEnv, collection string, vid needle.VolumeId, locations []*EcNode, racks map[RackId]*EcRack, applyBalancing bool) error {
  440. // calculate average number of shards an ec rack should have for one volume
  441. averageShardsPerEcRack := ceilDivide(erasure_coding.TotalShardsCount, len(racks))
  442. // see the volume's shards are in how many racks, and how many in each rack
  443. rackToShardCount := countShardsByRack(vid, locations)
  444. rackEcNodesWithVid := groupBy(locations, func(ecNode *EcNode) string {
  445. return string(ecNode.rack)
  446. })
  447. // ecShardsToMove = select overflown ec shards from racks with ec shard counts > averageShardsPerEcRack
  448. ecShardsToMove := make(map[erasure_coding.ShardId]*EcNode)
  449. for rackId, count := range rackToShardCount {
  450. if count <= averageShardsPerEcRack {
  451. continue
  452. }
  453. possibleEcNodes := rackEcNodesWithVid[rackId]
  454. for shardId, ecNode := range pickNEcShardsToMoveFrom(possibleEcNodes, vid, count-averageShardsPerEcRack) {
  455. ecShardsToMove[shardId] = ecNode
  456. }
  457. }
  458. for shardId, ecNode := range ecShardsToMove {
  459. // TODO: consider volume replica info when balancing racks
  460. rackId, err := pickRackToBalanceShardsInto(racks, rackToShardCount, nil, averageShardsPerEcRack)
  461. if err != nil {
  462. fmt.Printf("ec shard %d.%d at %s can not find a destination rack:\n%s\n", vid, shardId, ecNode.info.Id, err.Error())
  463. continue
  464. }
  465. var possibleDestinationEcNodes []*EcNode
  466. for _, n := range racks[rackId].ecNodes {
  467. possibleDestinationEcNodes = append(possibleDestinationEcNodes, n)
  468. }
  469. err = pickOneEcNodeAndMoveOneShard(commandEnv, averageShardsPerEcRack, ecNode, collection, vid, shardId, possibleDestinationEcNodes, applyBalancing)
  470. if err != nil {
  471. return err
  472. }
  473. rackToShardCount[string(rackId)] += 1
  474. rackToShardCount[string(ecNode.rack)] -= 1
  475. racks[rackId].freeEcSlot -= 1
  476. racks[ecNode.rack].freeEcSlot += 1
  477. }
  478. return nil
  479. }
  480. func pickRackToBalanceShardsInto(rackToEcNodes map[RackId]*EcRack, rackToShardCount map[string]int, replicaPlacement *super_block.ReplicaPlacement, averageShardsPerEcRack int) (RackId, error) {
  481. targets := []RackId{}
  482. targetShards := -1
  483. for _, shards := range rackToShardCount {
  484. if shards > targetShards {
  485. targetShards = shards
  486. }
  487. }
  488. details := ""
  489. for rackId, rack := range rackToEcNodes {
  490. shards := rackToShardCount[string(rackId)]
  491. if rack.freeEcSlot <= 0 {
  492. details += fmt.Sprintf(" Skipped %s because it has no free slots\n", rackId)
  493. continue
  494. }
  495. if replicaPlacement != nil && shards >= replicaPlacement.DiffRackCount {
  496. details += fmt.Sprintf(" Skipped %s because shards %d >= replica placement limit for other racks (%d)\n", rackId, shards, replicaPlacement.DiffRackCount)
  497. continue
  498. }
  499. if shards >= averageShardsPerEcRack {
  500. details += fmt.Sprintf(" Skipped %s because shards %d >= averageShards (%d)\n", rackId, shards, averageShardsPerEcRack)
  501. continue
  502. }
  503. if shards < targetShards {
  504. // Favor racks with less shards, to ensure an uniform distribution.
  505. targets = nil
  506. targetShards = shards
  507. }
  508. if shards == targetShards {
  509. targets = append(targets, rackId)
  510. }
  511. }
  512. if len(targets) == 0 {
  513. return "", errors.New(details)
  514. }
  515. return targets[rand.IntN(len(targets))], nil
  516. }
  517. func balanceEcShardsWithinRacks(commandEnv *CommandEnv, allEcNodes []*EcNode, racks map[RackId]*EcRack, collection string, applyBalancing bool) error {
  518. // collect vid => []ecNode, since previous steps can change the locations
  519. vidLocations := collectVolumeIdToEcNodes(allEcNodes, collection)
  520. // spread the ec shards evenly
  521. for vid, locations := range vidLocations {
  522. // see the volume's shards are in how many racks, and how many in each rack
  523. rackToShardCount := countShardsByRack(vid, locations)
  524. rackEcNodesWithVid := groupBy(locations, func(ecNode *EcNode) string {
  525. return string(ecNode.rack)
  526. })
  527. for rackId, _ := range rackToShardCount {
  528. var possibleDestinationEcNodes []*EcNode
  529. for _, n := range racks[RackId(rackId)].ecNodes {
  530. if _, found := n.info.DiskInfos[string(types.HardDriveType)]; found {
  531. possibleDestinationEcNodes = append(possibleDestinationEcNodes, n)
  532. }
  533. }
  534. sourceEcNodes := rackEcNodesWithVid[rackId]
  535. averageShardsPerEcNode := ceilDivide(rackToShardCount[rackId], len(possibleDestinationEcNodes))
  536. if err := doBalanceEcShardsWithinOneRack(commandEnv, averageShardsPerEcNode, collection, vid, sourceEcNodes, possibleDestinationEcNodes, applyBalancing); err != nil {
  537. return err
  538. }
  539. }
  540. }
  541. return nil
  542. }
  543. func doBalanceEcShardsWithinOneRack(commandEnv *CommandEnv, averageShardsPerEcNode int, collection string, vid needle.VolumeId, existingLocations, possibleDestinationEcNodes []*EcNode, applyBalancing bool) error {
  544. for _, ecNode := range existingLocations {
  545. shardBits := findEcVolumeShards(ecNode, vid)
  546. overLimitCount := shardBits.ShardIdCount() - averageShardsPerEcNode
  547. for _, shardId := range shardBits.ShardIds() {
  548. if overLimitCount <= 0 {
  549. break
  550. }
  551. fmt.Printf("%s has %d overlimit, moving ec shard %d.%d\n", ecNode.info.Id, overLimitCount, vid, shardId)
  552. err := pickOneEcNodeAndMoveOneShard(commandEnv, averageShardsPerEcNode, ecNode, collection, vid, shardId, possibleDestinationEcNodes, applyBalancing)
  553. if err != nil {
  554. return err
  555. }
  556. overLimitCount--
  557. }
  558. }
  559. return nil
  560. }
  561. func balanceEcRacks(commandEnv *CommandEnv, racks map[RackId]*EcRack, applyBalancing bool) error {
  562. // balance one rack for all ec shards
  563. for _, ecRack := range racks {
  564. if err := doBalanceEcRack(commandEnv, ecRack, applyBalancing); err != nil {
  565. return err
  566. }
  567. }
  568. return nil
  569. }
  570. func doBalanceEcRack(commandEnv *CommandEnv, ecRack *EcRack, applyBalancing bool) error {
  571. if len(ecRack.ecNodes) <= 1 {
  572. return nil
  573. }
  574. var rackEcNodes []*EcNode
  575. for _, node := range ecRack.ecNodes {
  576. rackEcNodes = append(rackEcNodes, node)
  577. }
  578. ecNodeIdToShardCount := groupByCount(rackEcNodes, func(ecNode *EcNode) (id string, count int) {
  579. diskInfo, found := ecNode.info.DiskInfos[string(types.HardDriveType)]
  580. if !found {
  581. return
  582. }
  583. for _, ecShardInfo := range diskInfo.EcShardInfos {
  584. count += erasure_coding.ShardBits(ecShardInfo.EcIndexBits).ShardIdCount()
  585. }
  586. return ecNode.info.Id, count
  587. })
  588. var totalShardCount int
  589. for _, count := range ecNodeIdToShardCount {
  590. totalShardCount += count
  591. }
  592. averageShardCount := ceilDivide(totalShardCount, len(rackEcNodes))
  593. hasMove := true
  594. for hasMove {
  595. hasMove = false
  596. slices.SortFunc(rackEcNodes, func(a, b *EcNode) int {
  597. return b.freeEcSlot - a.freeEcSlot
  598. })
  599. emptyNode, fullNode := rackEcNodes[0], rackEcNodes[len(rackEcNodes)-1]
  600. emptyNodeShardCount, fullNodeShardCount := ecNodeIdToShardCount[emptyNode.info.Id], ecNodeIdToShardCount[fullNode.info.Id]
  601. if fullNodeShardCount > averageShardCount && emptyNodeShardCount+1 <= averageShardCount {
  602. emptyNodeIds := make(map[uint32]bool)
  603. if emptyDiskInfo, found := emptyNode.info.DiskInfos[string(types.HardDriveType)]; found {
  604. for _, shards := range emptyDiskInfo.EcShardInfos {
  605. emptyNodeIds[shards.Id] = true
  606. }
  607. }
  608. if fullDiskInfo, found := fullNode.info.DiskInfos[string(types.HardDriveType)]; found {
  609. for _, shards := range fullDiskInfo.EcShardInfos {
  610. if _, found := emptyNodeIds[shards.Id]; !found {
  611. for _, shardId := range erasure_coding.ShardBits(shards.EcIndexBits).ShardIds() {
  612. fmt.Printf("%s moves ec shards %d.%d to %s\n", fullNode.info.Id, shards.Id, shardId, emptyNode.info.Id)
  613. err := moveMountedShardToEcNode(commandEnv, fullNode, shards.Collection, needle.VolumeId(shards.Id), shardId, emptyNode, applyBalancing)
  614. if err != nil {
  615. return err
  616. }
  617. ecNodeIdToShardCount[emptyNode.info.Id]++
  618. ecNodeIdToShardCount[fullNode.info.Id]--
  619. hasMove = true
  620. break
  621. }
  622. break
  623. }
  624. }
  625. }
  626. }
  627. }
  628. return nil
  629. }
  630. func pickEcNodeToBalanceShardsInto(vid needle.VolumeId, existingLocation *EcNode, possibleDestinations []*EcNode, replicaPlacement *super_block.ReplicaPlacement, averageShardsPerEcNode int) (*EcNode, error) {
  631. if existingLocation == nil {
  632. return nil, fmt.Errorf("INTERNAL: missing source nodes")
  633. }
  634. if len(possibleDestinations) == 0 {
  635. return nil, fmt.Errorf("INTERNAL: missing destination nodes")
  636. }
  637. nodeShards := map[*EcNode]int{}
  638. for _, node := range possibleDestinations {
  639. nodeShards[node] = findEcVolumeShards(node, vid).ShardIdCount()
  640. }
  641. targets := []*EcNode{}
  642. targetShards := -1
  643. for _, shards := range nodeShards {
  644. if shards > targetShards {
  645. targetShards = shards
  646. }
  647. }
  648. details := ""
  649. for _, node := range possibleDestinations {
  650. if node.info.Id == existingLocation.info.Id {
  651. continue
  652. }
  653. if node.freeEcSlot <= 0 {
  654. details += fmt.Sprintf(" Skipped %s because it has no free slots\n", node.info.Id)
  655. continue
  656. }
  657. shards := nodeShards[node]
  658. if replicaPlacement != nil && shards >= replicaPlacement.SameRackCount {
  659. details += fmt.Sprintf(" Skipped %s because shards %d >= replica placement limit for the rack (%d)\n", node.info.Id, shards, replicaPlacement.SameRackCount)
  660. continue
  661. }
  662. if shards >= averageShardsPerEcNode {
  663. details += fmt.Sprintf(" Skipped %s because shards %d >= averageShards (%d)\n",
  664. node.info.Id, shards, averageShardsPerEcNode)
  665. continue
  666. }
  667. if shards < targetShards {
  668. // Favor nodes with less shards, to ensure an uniform distribution.
  669. targets = nil
  670. targetShards = shards
  671. }
  672. if shards == targetShards {
  673. targets = append(targets, node)
  674. }
  675. }
  676. if len(targets) == 0 {
  677. return nil, errors.New(details)
  678. }
  679. return targets[rand.IntN(len(targets))], nil
  680. }
  681. // TODO: Maybe remove averages constraints? We don't need those anymore now that we're properly balancing shards.
  682. func pickOneEcNodeAndMoveOneShard(commandEnv *CommandEnv, averageShardsPerEcNode int, existingLocation *EcNode, collection string, vid needle.VolumeId, shardId erasure_coding.ShardId, possibleDestinationEcNodes []*EcNode, applyBalancing bool) error {
  683. // TODO: consider volume replica info when balancing nodes
  684. destNode, err := pickEcNodeToBalanceShardsInto(vid, existingLocation, possibleDestinationEcNodes, nil, averageShardsPerEcNode)
  685. if err != nil {
  686. fmt.Printf("WARNING: Could not find suitable taget node for %d.%d:\n%s", vid, shardId, err.Error())
  687. return nil
  688. }
  689. fmt.Printf("%s moves ec shard %d.%d to %s\n", existingLocation.info.Id, vid, shardId, destNode.info.Id)
  690. return moveMountedShardToEcNode(commandEnv, existingLocation, collection, vid, shardId, destNode, applyBalancing)
  691. }
  692. func pickNEcShardsToMoveFrom(ecNodes []*EcNode, vid needle.VolumeId, n int) map[erasure_coding.ShardId]*EcNode {
  693. picked := make(map[erasure_coding.ShardId]*EcNode)
  694. var candidateEcNodes []*CandidateEcNode
  695. for _, ecNode := range ecNodes {
  696. shardBits := findEcVolumeShards(ecNode, vid)
  697. if shardBits.ShardIdCount() > 0 {
  698. candidateEcNodes = append(candidateEcNodes, &CandidateEcNode{
  699. ecNode: ecNode,
  700. shardCount: shardBits.ShardIdCount(),
  701. })
  702. }
  703. }
  704. slices.SortFunc(candidateEcNodes, func(a, b *CandidateEcNode) int {
  705. return b.shardCount - a.shardCount
  706. })
  707. for i := 0; i < n; i++ {
  708. selectedEcNodeIndex := -1
  709. for i, candidateEcNode := range candidateEcNodes {
  710. shardBits := findEcVolumeShards(candidateEcNode.ecNode, vid)
  711. if shardBits > 0 {
  712. selectedEcNodeIndex = i
  713. for _, shardId := range shardBits.ShardIds() {
  714. candidateEcNode.shardCount--
  715. picked[shardId] = candidateEcNode.ecNode
  716. candidateEcNode.ecNode.deleteEcVolumeShards(vid, []uint32{uint32(shardId)})
  717. break
  718. }
  719. break
  720. }
  721. }
  722. if selectedEcNodeIndex >= 0 {
  723. ensureSortedEcNodes(candidateEcNodes, selectedEcNodeIndex, func(i, j int) bool {
  724. return candidateEcNodes[i].shardCount > candidateEcNodes[j].shardCount
  725. })
  726. }
  727. }
  728. return picked
  729. }
  730. func collectVolumeIdToEcNodes(allEcNodes []*EcNode, collection string) map[needle.VolumeId][]*EcNode {
  731. vidLocations := make(map[needle.VolumeId][]*EcNode)
  732. for _, ecNode := range allEcNodes {
  733. diskInfo, found := ecNode.info.DiskInfos[string(types.HardDriveType)]
  734. if !found {
  735. continue
  736. }
  737. for _, shardInfo := range diskInfo.EcShardInfos {
  738. // ignore if not in current collection
  739. if shardInfo.Collection == collection {
  740. vidLocations[needle.VolumeId(shardInfo.Id)] = append(vidLocations[needle.VolumeId(shardInfo.Id)], ecNode)
  741. }
  742. }
  743. }
  744. return vidLocations
  745. }
  746. // TODO: EC volumes have no topology replica placement info :( We need a better solution to resolve topology, and balancing, for those.
  747. func volumeIdToReplicaPlacement(commandEnv *CommandEnv, vid needle.VolumeId, nodes []*EcNode, ecReplicaPlacement *super_block.ReplicaPlacement) (*super_block.ReplicaPlacement, error) {
  748. for _, ecNode := range nodes {
  749. for _, diskInfo := range ecNode.info.DiskInfos {
  750. for _, volumeInfo := range diskInfo.VolumeInfos {
  751. if needle.VolumeId(volumeInfo.Id) == vid {
  752. return super_block.NewReplicaPlacementFromByte(byte(volumeInfo.ReplicaPlacement))
  753. }
  754. }
  755. for _, ecShardInfo := range diskInfo.EcShardInfos {
  756. if needle.VolumeId(ecShardInfo.Id) == vid {
  757. return ecReplicaPlacement, nil
  758. }
  759. }
  760. }
  761. }
  762. return nil, fmt.Errorf("failed to resolve replica placement for volume ID %d", vid)
  763. }
  764. func EcBalance(commandEnv *CommandEnv, collections []string, dc string, ecReplicaPlacement *super_block.ReplicaPlacement, applyBalancing bool) (err error) {
  765. if len(collections) == 0 {
  766. return fmt.Errorf("no collections to balance")
  767. }
  768. // collect all ec nodes
  769. allEcNodes, totalFreeEcSlots, err := collectEcNodes(commandEnv, dc)
  770. if err != nil {
  771. return err
  772. }
  773. if totalFreeEcSlots < 1 {
  774. return fmt.Errorf("no free ec shard slots. only %d left", totalFreeEcSlots)
  775. }
  776. racks := collectRacks(allEcNodes)
  777. for _, c := range collections {
  778. if err = balanceEcVolumes(commandEnv, c, allEcNodes, racks, applyBalancing); err != nil {
  779. return err
  780. }
  781. }
  782. if err := balanceEcRacks(commandEnv, racks, applyBalancing); err != nil {
  783. return fmt.Errorf("balance ec racks: %v", err)
  784. }
  785. return nil
  786. }