You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

check_rep_count.go 6.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. package event
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "math"
  6. "github.com/jmoiron/sqlx"
  7. "github.com/samber/lo"
  8. "gitlink.org.cn/cloudream/common/consts"
  9. log "gitlink.org.cn/cloudream/common/utils/logger"
  10. mymath "gitlink.org.cn/cloudream/common/utils/math"
  11. mysort "gitlink.org.cn/cloudream/common/utils/sort"
  12. "gitlink.org.cn/cloudream/scanner/internal/config"
  13. "gitlink.org.cn/cloudream/db/model"
  14. mysql "gitlink.org.cn/cloudream/db/sql"
  15. scevt "gitlink.org.cn/cloudream/rabbitmq/message/scanner/event"
  16. )
  17. type CheckRepCount struct {
  18. scevt.CheckRepCount
  19. }
  20. func NewCheckRepCount(fileHashes []string) *CheckRepCount {
  21. return &CheckRepCount{
  22. CheckRepCount: scevt.NewCheckRepCount(fileHashes),
  23. }
  24. }
  25. func (t *CheckRepCount) TryMerge(other Event) bool {
  26. event, ok := other.(*CheckRepCount)
  27. if !ok {
  28. return false
  29. }
  30. t.FileHashes = lo.Union(t.FileHashes, event.FileHashes)
  31. return true
  32. }
  33. func (t *CheckRepCount) Execute(execCtx ExecuteContext) {
  34. updatedNodeAndHashes := make(map[int][]string)
  35. for _, fileHash := range t.FileHashes {
  36. updatedNodeIDs, err := t.checkOneRepCount(fileHash, execCtx)
  37. if err != nil {
  38. log.WithField("FileHash", fileHash).Warnf("check file rep count failed, err: %s", err.Error())
  39. continue
  40. }
  41. for _, id := range updatedNodeIDs {
  42. hashes := updatedNodeAndHashes[id]
  43. updatedNodeAndHashes[id] = append(hashes, fileHash)
  44. }
  45. }
  46. for nodeID, hashes := range updatedNodeAndHashes {
  47. // 新任务继承本任务的执行设定(紧急任务依然保持紧急任务)
  48. execCtx.Executor.Post(NewAgentCheckCache(nodeID, hashes), execCtx.Option)
  49. }
  50. }
  51. func (t *CheckRepCount) checkOneRepCount(fileHash string, execCtx ExecuteContext) ([]int, error) {
  52. var updatedNodeIDs []int
  53. err := execCtx.Args.DB.DoTx(sql.LevelSerializable, func(tx *sqlx.Tx) error {
  54. repMaxCnt, err := mysql.ObjectRep.GetFileMaxRepCount(tx, fileHash)
  55. if err != nil {
  56. return fmt.Errorf("get file max rep count failed, err: %w", err)
  57. }
  58. blkCnt, err := mysql.ObjectBlock.CountBlockWithHash(tx, fileHash)
  59. if err != nil {
  60. return fmt.Errorf("count block with hash failed, err: %w", err)
  61. }
  62. // 计算所需的最少备份数:
  63. // ObjectRep中期望备份数的最大值
  64. // 如果ObjectBlock存在对此文件的引用,则至少为1
  65. needRepCount := mymath.Max(repMaxCnt, mymath.Max(1, blkCnt))
  66. repNodes, err := mysql.Cache.GetCachingFileNodes(tx, fileHash)
  67. if err != nil {
  68. return fmt.Errorf("get caching file nodes failed, err: %w", err)
  69. }
  70. allNodes, err := mysql.Node.GetAllNodes(tx)
  71. if err != nil {
  72. return fmt.Errorf("get all nodes failed, err: %w", err)
  73. }
  74. var normalNodes, unavaiNodes []model.Node
  75. for _, node := range repNodes {
  76. if node.State == consts.NODE_STATE_NORMAL {
  77. normalNodes = append(normalNodes, node)
  78. } else if node.State == consts.NODE_STATE_UNAVAILABLE {
  79. unavaiNodes = append(unavaiNodes, node)
  80. }
  81. }
  82. // 如果Available的备份数超过期望备份数,则让一些节点退出
  83. if len(normalNodes) > needRepCount {
  84. delNodes := chooseDeleteAvaiRepNodes(allNodes, normalNodes, needRepCount-len(normalNodes))
  85. for _, node := range delNodes {
  86. err := mysql.Cache.ChangeState(tx, fileHash, node.NodeID, consts.CACHE_STATE_TEMP)
  87. if err != nil {
  88. return fmt.Errorf("change cache state failed, err: %w", err)
  89. }
  90. updatedNodeIDs = append(updatedNodeIDs, node.NodeID)
  91. }
  92. return nil
  93. }
  94. minAvaiNodeCnt := int(math.Ceil(float64(config.Cfg().MinAvailableRepProportion) * float64(needRepCount)))
  95. // 因为总备份数不够,而需要增加的备份数
  96. add1 := mymath.Max(0, needRepCount-len(repNodes))
  97. // 因为Available的备份数占比过少,而需要增加的备份数
  98. add2 := mymath.Max(0, minAvaiNodeCnt-len(normalNodes))
  99. // 最终需要增加的备份数,是以上两种情况的最大值
  100. finalAddCount := mymath.Max(add1, add2)
  101. if finalAddCount > 0 {
  102. newNodes := chooseNewRepNodes(allNodes, repNodes, finalAddCount)
  103. if len(newNodes) < finalAddCount {
  104. log.WithField("FileHash", fileHash).Warnf("need %d more rep nodes, but get only %d nodes", finalAddCount, len(newNodes))
  105. // TODO 节点数不够,进行一个告警
  106. }
  107. for _, node := range newNodes {
  108. err := mysql.Cache.Create(tx, fileHash, node.NodeID)
  109. if err != nil {
  110. return fmt.Errorf("create cache failed, err: %w", err)
  111. }
  112. updatedNodeIDs = append(updatedNodeIDs, node.NodeID)
  113. }
  114. }
  115. return nil
  116. })
  117. if err != nil {
  118. return nil, err
  119. }
  120. return updatedNodeIDs, nil
  121. }
  122. func chooseNewRepNodes(allNodes []model.Node, curRepNodes []model.Node, newCount int) []model.Node {
  123. noRepNodes := lo.Reject(allNodes, func(node model.Node, index int) bool {
  124. return lo.ContainsBy(curRepNodes, func(n model.Node) bool { return node.NodeID == n.NodeID }) ||
  125. node.State != consts.NODE_STATE_NORMAL
  126. })
  127. repNodeLocationIDs := make(map[int]bool)
  128. for _, node := range curRepNodes {
  129. repNodeLocationIDs[node.LocationID] = true
  130. }
  131. mysort.Sort(noRepNodes, func(l, r model.Node) int {
  132. // LocationID不存在时为false,false - true < 0,所以LocationID不存在的会排在前面
  133. return mysort.CmpBool(repNodeLocationIDs[l.LocationID], repNodeLocationIDs[r.LocationID])
  134. })
  135. return noRepNodes[:mymath.Min(newCount, len(noRepNodes))]
  136. }
  137. func chooseDeleteAvaiRepNodes(allNodes []model.Node, curAvaiRepNodes []model.Node, delCount int) []model.Node {
  138. // 按照地域ID分组
  139. locationGroupedNodes := make(map[int][]model.Node)
  140. for _, node := range curAvaiRepNodes {
  141. nodes := locationGroupedNodes[node.LocationID]
  142. nodes = append(nodes, node)
  143. locationGroupedNodes[node.LocationID] = nodes
  144. }
  145. // 每次从每个分组中取出一个元素放入结果数组,并将这个元素从分组中删除
  146. // 最后结果数组中的元素会按照地域交错循环排列,比如:ABCABCBCC。同时还有一个特征:靠后的循环节中的元素都来自于元素数多的分组
  147. // 将结果数组反转(此处是用存放时就逆序的形式实现),就把元素数多的分组提前了,此时从头部取出要删除的节点即可
  148. alternatedNodes := make([]model.Node, len(curAvaiRepNodes))
  149. for i := len(curAvaiRepNodes) - 1; i >= 0; {
  150. for id, nodes := range locationGroupedNodes {
  151. alternatedNodes[i] = nodes[0]
  152. if len(nodes) == 1 {
  153. delete(locationGroupedNodes, id)
  154. } else {
  155. locationGroupedNodes[id] = nodes[1:]
  156. }
  157. // 放置一个元素就移动一下下一个存放点
  158. i--
  159. }
  160. }
  161. return alternatedNodes[:mymath.Min(delCount, len(alternatedNodes))]
  162. }

本项目旨在将云际存储公共基础设施化,使个人及企业可低门槛使用高效的云际存储服务(安装开箱即用云际存储客户端即可,无需关注其他组件的部署),同时支持用户灵活便捷定制云际存储的功能细节。