command_volume_balance.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. package shell
  2. import (
  3. "cmp"
  4. "flag"
  5. "fmt"
  6. "io"
  7. "os"
  8. "regexp"
  9. "strings"
  10. "time"
  11. "slices"
  12. "github.com/seaweedfs/seaweedfs/weed/pb"
  13. "github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
  14. "github.com/seaweedfs/seaweedfs/weed/storage/super_block"
  15. "github.com/seaweedfs/seaweedfs/weed/storage/types"
  16. "github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
  17. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  18. )
  19. func init() {
  20. Commands = append(Commands, &commandVolumeBalance{})
  21. }
  22. type commandVolumeBalance struct {
  23. volumeSizeLimitMb uint64
  24. commandEnv *CommandEnv
  25. writable bool
  26. applyBalancing bool
  27. }
  28. func (c *commandVolumeBalance) Name() string {
  29. return "volume.balance"
  30. }
  31. func (c *commandVolumeBalance) Help() string {
  32. return `balance all volumes among volume servers
  33. volume.balance [-collection ALL_COLLECTIONS|EACH_COLLECTION|<collection_name>] [-force] [-dataCenter=<data_center_name>] [-racks=rack_name_one,rack_name_two] [-nodes=192.168.0.1:8080,192.168.0.2:8080]
  34. The -collection parameter supports:
  35. - ALL_COLLECTIONS: balance across all collections
  36. - EACH_COLLECTION: balance each collection separately
  37. - Regular expressions for pattern matching:
  38. * Use exact match: volume.balance -collection="^mybucket$"
  39. * Match multiple buckets: volume.balance -collection="bucket.*"
  40. * Match all user collections: volume.balance -collection="user-.*"
  41. Algorithm:
  42. For each type of volume server (different max volume count limit){
  43. for each collection {
  44. balanceWritableVolumes()
  45. balanceReadOnlyVolumes()
  46. }
  47. }
  48. func balanceWritableVolumes(){
  49. idealWritableVolumeRatio = totalWritableVolumes / totalNumberOfMaxVolumes
  50. for hasMovedOneVolume {
  51. sort all volume servers ordered by the localWritableVolumeRatio = localWritableVolumes to localVolumeMax
  52. pick the volume server B with the highest localWritableVolumeRatio y
  53. for any the volume server A with the number of writable volumes x + 1 <= idealWritableVolumeRatio * localVolumeMax {
  54. if y > localWritableVolumeRatio {
  55. if B has a writable volume id v that A does not have, and satisfy v replication requirements {
  56. move writable volume v from A to B
  57. }
  58. }
  59. }
  60. }
  61. }
  62. func balanceReadOnlyVolumes(){
  63. //similar to balanceWritableVolumes
  64. }
  65. `
  66. }
  67. func (c *commandVolumeBalance) HasTag(CommandTag) bool {
  68. return false
  69. }
  70. func (c *commandVolumeBalance) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  71. balanceCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
  72. collection := balanceCommand.String("collection", "ALL_COLLECTIONS", "collection name, or use \"ALL_COLLECTIONS\" across collections, \"EACH_COLLECTION\" for each collection")
  73. dc := balanceCommand.String("dataCenter", "", "only apply the balancing for this dataCenter")
  74. racks := balanceCommand.String("racks", "", "only apply the balancing for this racks")
  75. nodes := balanceCommand.String("nodes", "", "only apply the balancing for this nodes")
  76. writable := balanceCommand.Bool("writable", false, "only apply the balancing for writable volumes")
  77. noLock := balanceCommand.Bool("noLock", false, "do not lock the admin shell at one's own risk")
  78. applyBalancing := balanceCommand.Bool("force", false, "apply the balancing plan.")
  79. if err = balanceCommand.Parse(args); err != nil {
  80. return nil
  81. }
  82. c.writable = *writable
  83. c.applyBalancing = *applyBalancing
  84. infoAboutSimulationMode(writer, c.applyBalancing, "-force")
  85. if *noLock {
  86. commandEnv.noLock = true
  87. } else {
  88. if err = commandEnv.confirmIsLocked(args); err != nil {
  89. return
  90. }
  91. }
  92. c.commandEnv = commandEnv
  93. // collect topology information
  94. var topologyInfo *master_pb.TopologyInfo
  95. topologyInfo, c.volumeSizeLimitMb, err = collectTopologyInfo(commandEnv, 5*time.Second)
  96. if err != nil {
  97. return err
  98. }
  99. volumeServers := collectVolumeServersByDcRackNode(topologyInfo, *dc, *racks, *nodes)
  100. volumeReplicas, _ := collectVolumeReplicaLocations(topologyInfo)
  101. diskTypes := collectVolumeDiskTypes(topologyInfo)
  102. if *collection == "EACH_COLLECTION" {
  103. collections, err := ListCollectionNames(commandEnv, true, false)
  104. if err != nil {
  105. return err
  106. }
  107. for _, col := range collections {
  108. // Use direct string comparison for exact match (more efficient than regex)
  109. if err = c.balanceVolumeServers(diskTypes, volumeReplicas, volumeServers, nil, col); err != nil {
  110. return err
  111. }
  112. }
  113. } else if *collection == "ALL_COLLECTIONS" {
  114. // Pass nil pattern for all collections
  115. if err = c.balanceVolumeServers(diskTypes, volumeReplicas, volumeServers, nil, *collection); err != nil {
  116. return err
  117. }
  118. } else {
  119. // Compile user-provided pattern
  120. collectionPattern, err := compileCollectionPattern(*collection)
  121. if err != nil {
  122. return fmt.Errorf("invalid collection pattern '%s': %v", *collection, err)
  123. }
  124. if err = c.balanceVolumeServers(diskTypes, volumeReplicas, volumeServers, collectionPattern, *collection); err != nil {
  125. return err
  126. }
  127. }
  128. return nil
  129. }
  130. func (c *commandVolumeBalance) balanceVolumeServers(diskTypes []types.DiskType, volumeReplicas map[uint32][]*VolumeReplica, nodes []*Node, collectionPattern *regexp.Regexp, collectionName string) error {
  131. for _, diskType := range diskTypes {
  132. if err := c.balanceVolumeServersByDiskType(diskType, volumeReplicas, nodes, collectionPattern, collectionName); err != nil {
  133. return err
  134. }
  135. }
  136. return nil
  137. }
  138. func (c *commandVolumeBalance) balanceVolumeServersByDiskType(diskType types.DiskType, volumeReplicas map[uint32][]*VolumeReplica, nodes []*Node, collectionPattern *regexp.Regexp, collectionName string) error {
  139. for _, n := range nodes {
  140. n.selectVolumes(func(v *master_pb.VolumeInformationMessage) bool {
  141. if collectionName != "ALL_COLLECTIONS" {
  142. if collectionPattern != nil {
  143. // Use regex pattern matching
  144. if !collectionPattern.MatchString(v.Collection) {
  145. return false
  146. }
  147. } else {
  148. // Use exact string matching (for EACH_COLLECTION)
  149. if v.Collection != collectionName {
  150. return false
  151. }
  152. }
  153. }
  154. if v.DiskType != string(diskType) {
  155. return false
  156. }
  157. if c.writable && v.Size > c.volumeSizeLimitMb {
  158. return false
  159. }
  160. return true
  161. })
  162. }
  163. if err := balanceSelectedVolume(c.commandEnv, diskType, volumeReplicas, nodes, sortWritableVolumes, c.applyBalancing); err != nil {
  164. return err
  165. }
  166. return nil
  167. }
  168. func collectVolumeServersByDcRackNode(t *master_pb.TopologyInfo, selectedDataCenter string, selectedRacks string, selectedNodes string) (nodes []*Node) {
  169. for _, dc := range t.DataCenterInfos {
  170. if selectedDataCenter != "" && dc.Id != selectedDataCenter {
  171. continue
  172. }
  173. for _, r := range dc.RackInfos {
  174. if selectedRacks != "" && !strings.Contains(selectedRacks, r.Id) {
  175. continue
  176. }
  177. for _, dn := range r.DataNodeInfos {
  178. if selectedNodes != "" && !strings.Contains(selectedNodes, dn.Id) {
  179. continue
  180. }
  181. nodes = append(nodes, &Node{
  182. info: dn,
  183. dc: dc.Id,
  184. rack: r.Id,
  185. })
  186. }
  187. }
  188. }
  189. return
  190. }
  191. func collectVolumeDiskTypes(t *master_pb.TopologyInfo) (diskTypes []types.DiskType) {
  192. knownTypes := make(map[string]bool)
  193. for _, dc := range t.DataCenterInfos {
  194. for _, r := range dc.RackInfos {
  195. for _, dn := range r.DataNodeInfos {
  196. for diskType := range dn.DiskInfos {
  197. if _, found := knownTypes[diskType]; !found {
  198. knownTypes[diskType] = true
  199. }
  200. }
  201. }
  202. }
  203. }
  204. for diskType := range knownTypes {
  205. diskTypes = append(diskTypes, types.ToDiskType(diskType))
  206. }
  207. return
  208. }
  209. type Node struct {
  210. info *master_pb.DataNodeInfo
  211. selectedVolumes map[uint32]*master_pb.VolumeInformationMessage
  212. dc string
  213. rack string
  214. }
  215. type CapacityFunc func(*master_pb.DataNodeInfo) float64
  216. func capacityByMaxVolumeCount(diskType types.DiskType) CapacityFunc {
  217. return func(info *master_pb.DataNodeInfo) float64 {
  218. diskInfo, found := info.DiskInfos[string(diskType)]
  219. if !found {
  220. return 0
  221. }
  222. var ecShardCount int
  223. for _, ecShardInfo := range diskInfo.EcShardInfos {
  224. ecShardCount += erasure_coding.ShardBits(ecShardInfo.EcIndexBits).ShardIdCount()
  225. }
  226. return float64(diskInfo.MaxVolumeCount) - float64(ecShardCount)/erasure_coding.DataShardsCount
  227. }
  228. }
  229. func capacityByFreeVolumeCount(diskType types.DiskType) CapacityFunc {
  230. return func(info *master_pb.DataNodeInfo) float64 {
  231. diskInfo, found := info.DiskInfos[string(diskType)]
  232. if !found {
  233. return 0
  234. }
  235. var ecShardCount int
  236. for _, ecShardInfo := range diskInfo.EcShardInfos {
  237. ecShardCount += erasure_coding.ShardBits(ecShardInfo.EcIndexBits).ShardIdCount()
  238. }
  239. return float64(diskInfo.MaxVolumeCount-diskInfo.VolumeCount) - float64(ecShardCount)/erasure_coding.DataShardsCount
  240. }
  241. }
  242. func (n *Node) localVolumeRatio(capacityFunc CapacityFunc) float64 {
  243. return float64(len(n.selectedVolumes)) / capacityFunc(n.info)
  244. }
  245. func (n *Node) localVolumeNextRatio(capacityFunc CapacityFunc) float64 {
  246. return float64(len(n.selectedVolumes)+1) / capacityFunc(n.info)
  247. }
  248. func (n *Node) isOneVolumeOnly() bool {
  249. if len(n.selectedVolumes) != 1 {
  250. return false
  251. }
  252. for _, disk := range n.info.DiskInfos {
  253. if disk.VolumeCount == 1 && disk.MaxVolumeCount == 1 {
  254. return true
  255. }
  256. }
  257. return false
  258. }
  259. func (n *Node) selectVolumes(fn func(v *master_pb.VolumeInformationMessage) bool) {
  260. n.selectedVolumes = make(map[uint32]*master_pb.VolumeInformationMessage)
  261. for _, diskInfo := range n.info.DiskInfos {
  262. for _, v := range diskInfo.VolumeInfos {
  263. if fn(v) {
  264. n.selectedVolumes[v.Id] = v
  265. }
  266. }
  267. }
  268. }
  269. func sortWritableVolumes(volumes []*master_pb.VolumeInformationMessage) {
  270. slices.SortFunc(volumes, func(a, b *master_pb.VolumeInformationMessage) int {
  271. return cmp.Compare(a.Size, b.Size)
  272. })
  273. }
  274. func balanceSelectedVolume(commandEnv *CommandEnv, diskType types.DiskType, volumeReplicas map[uint32][]*VolumeReplica, nodes []*Node, sortCandidatesFn func(volumes []*master_pb.VolumeInformationMessage), applyBalancing bool) (err error) {
  275. selectedVolumeCount, volumeMaxCount := 0, float64(0)
  276. var nodesWithCapacity []*Node
  277. capacityFunc := capacityByMaxVolumeCount(diskType)
  278. for _, dn := range nodes {
  279. selectedVolumeCount += len(dn.selectedVolumes)
  280. capacity := capacityFunc(dn.info)
  281. if capacity > 0 {
  282. nodesWithCapacity = append(nodesWithCapacity, dn)
  283. }
  284. volumeMaxCount += capacity
  285. }
  286. idealVolumeRatio := float64(selectedVolumeCount) / volumeMaxCount
  287. hasMoved := true
  288. // fmt.Fprintf(os.Stdout, " total %d volumes, max %d volumes, idealVolumeRatio %f\n", selectedVolumeCount, volumeMaxCount, idealVolumeRatio)
  289. for hasMoved {
  290. hasMoved = false
  291. slices.SortFunc(nodesWithCapacity, func(a, b *Node) int {
  292. return cmp.Compare(a.localVolumeRatio(capacityFunc), b.localVolumeRatio(capacityFunc))
  293. })
  294. if len(nodesWithCapacity) == 0 {
  295. fmt.Printf("no volume server found with capacity for %s", diskType.ReadableString())
  296. return nil
  297. }
  298. var fullNode *Node
  299. var fullNodeIndex int
  300. for fullNodeIndex = len(nodesWithCapacity) - 1; fullNodeIndex >= 0; fullNodeIndex-- {
  301. fullNode = nodesWithCapacity[fullNodeIndex]
  302. if !fullNode.isOneVolumeOnly() {
  303. break
  304. }
  305. }
  306. var candidateVolumes []*master_pb.VolumeInformationMessage
  307. for _, v := range fullNode.selectedVolumes {
  308. candidateVolumes = append(candidateVolumes, v)
  309. }
  310. sortCandidatesFn(candidateVolumes)
  311. for _, emptyNode := range nodesWithCapacity[:fullNodeIndex] {
  312. if !(fullNode.localVolumeRatio(capacityFunc) > idealVolumeRatio && emptyNode.localVolumeNextRatio(capacityFunc) <= idealVolumeRatio) {
  313. // no more volume servers with empty slots
  314. break
  315. }
  316. fmt.Fprintf(os.Stdout, "%s %.2f %.2f:%.2f\t", diskType.ReadableString(), idealVolumeRatio, fullNode.localVolumeRatio(capacityFunc), emptyNode.localVolumeNextRatio(capacityFunc))
  317. hasMoved, err = attemptToMoveOneVolume(commandEnv, volumeReplicas, fullNode, candidateVolumes, emptyNode, applyBalancing)
  318. if err != nil {
  319. return
  320. }
  321. if hasMoved {
  322. // moved one volume
  323. break
  324. }
  325. }
  326. }
  327. return nil
  328. }
  329. func attemptToMoveOneVolume(commandEnv *CommandEnv, volumeReplicas map[uint32][]*VolumeReplica, fullNode *Node, candidateVolumes []*master_pb.VolumeInformationMessage, emptyNode *Node, applyBalancing bool) (hasMoved bool, err error) {
  330. for _, v := range candidateVolumes {
  331. hasMoved, err = maybeMoveOneVolume(commandEnv, volumeReplicas, fullNode, v, emptyNode, applyBalancing)
  332. if err != nil {
  333. return
  334. }
  335. if hasMoved {
  336. break
  337. }
  338. }
  339. return
  340. }
  341. func maybeMoveOneVolume(commandEnv *CommandEnv, volumeReplicas map[uint32][]*VolumeReplica, fullNode *Node, candidateVolume *master_pb.VolumeInformationMessage, emptyNode *Node, applyChange bool) (hasMoved bool, err error) {
  342. if !commandEnv.isLocked() {
  343. return false, fmt.Errorf("lock is lost")
  344. }
  345. if candidateVolume.RemoteStorageName != "" {
  346. return false, fmt.Errorf("does not move volume in remove storage")
  347. }
  348. if candidateVolume.ReplicaPlacement > 0 {
  349. replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(candidateVolume.ReplicaPlacement))
  350. if !isGoodMove(replicaPlacement, volumeReplicas[candidateVolume.Id], fullNode, emptyNode) {
  351. return false, nil
  352. }
  353. }
  354. if _, found := emptyNode.selectedVolumes[candidateVolume.Id]; !found {
  355. if err = moveVolume(commandEnv, candidateVolume, fullNode, emptyNode, applyChange); err == nil {
  356. adjustAfterMove(candidateVolume, volumeReplicas, fullNode, emptyNode)
  357. return true, nil
  358. } else {
  359. return
  360. }
  361. }
  362. return
  363. }
  364. func moveVolume(commandEnv *CommandEnv, v *master_pb.VolumeInformationMessage, fullNode *Node, emptyNode *Node, applyChange bool) error {
  365. collectionPrefix := v.Collection + "_"
  366. if v.Collection == "" {
  367. collectionPrefix = ""
  368. }
  369. fmt.Fprintf(os.Stdout, " moving %s volume %s%d %s => %s\n", v.DiskType, collectionPrefix, v.Id, fullNode.info.Id, emptyNode.info.Id)
  370. if applyChange {
  371. return LiveMoveVolume(commandEnv.option.GrpcDialOption, os.Stderr, needle.VolumeId(v.Id), pb.NewServerAddressFromDataNode(fullNode.info), pb.NewServerAddressFromDataNode(emptyNode.info), 5*time.Second, v.DiskType, 0, false)
  372. }
  373. return nil
  374. }
  375. func isGoodMove(placement *super_block.ReplicaPlacement, existingReplicas []*VolumeReplica, sourceNode, targetNode *Node) bool {
  376. for _, replica := range existingReplicas {
  377. if replica.location.dataNode.Id == targetNode.info.Id &&
  378. replica.location.rack == targetNode.rack &&
  379. replica.location.dc == targetNode.dc {
  380. // never move to existing nodes
  381. return false
  382. }
  383. }
  384. // existing replicas except the one on sourceNode
  385. existingReplicasExceptSourceNode := make([]*VolumeReplica, 0)
  386. for _, replica := range existingReplicas {
  387. if replica.location.dataNode.Id != sourceNode.info.Id {
  388. existingReplicasExceptSourceNode = append(existingReplicasExceptSourceNode, replica)
  389. }
  390. }
  391. // target location
  392. targetLocation := location{
  393. dc: targetNode.dc,
  394. rack: targetNode.rack,
  395. dataNode: targetNode.info,
  396. }
  397. // check if this satisfies replication requirements
  398. return satisfyReplicaPlacement(placement, existingReplicasExceptSourceNode, targetLocation)
  399. }
  400. func adjustAfterMove(v *master_pb.VolumeInformationMessage, volumeReplicas map[uint32][]*VolumeReplica, fullNode *Node, emptyNode *Node) {
  401. delete(fullNode.selectedVolumes, v.Id)
  402. if emptyNode.selectedVolumes != nil {
  403. emptyNode.selectedVolumes[v.Id] = v
  404. }
  405. existingReplicas := volumeReplicas[v.Id]
  406. for _, replica := range existingReplicas {
  407. if replica.location.dataNode.Id == fullNode.info.Id &&
  408. replica.location.rack == fullNode.rack &&
  409. replica.location.dc == fullNode.dc {
  410. loc := newLocation(emptyNode.dc, emptyNode.rack, emptyNode.info)
  411. replica.location = &loc
  412. for diskType, diskInfo := range fullNode.info.DiskInfos {
  413. if diskType == v.DiskType {
  414. addVolumeCount(diskInfo, -1)
  415. }
  416. }
  417. for diskType, diskInfo := range emptyNode.info.DiskInfos {
  418. if diskType == v.DiskType {
  419. addVolumeCount(diskInfo, 1)
  420. }
  421. }
  422. return
  423. }
  424. }
  425. }