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.

394 lines
12 KiB

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