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.

428 lines
14 KiB

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