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.

463 lines
14 KiB

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