command_volume_balance.go 14 KB

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