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.

818 lines
26 KiB

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