command_volume_balance.go 13 KB

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