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.8 kB

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

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