command_volume_balance.go 14 KB

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