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.

clean_pinned.go 27 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  1. package event
  2. import (
  3. "fmt"
  4. "math"
  5. "math/rand"
  6. "sync"
  7. "github.com/samber/lo"
  8. "gitlink.org.cn/cloudream/common/pkgs/bitmap"
  9. "gitlink.org.cn/cloudream/common/pkgs/logger"
  10. cdssdk "gitlink.org.cn/cloudream/common/sdks/storage"
  11. "gitlink.org.cn/cloudream/common/utils/lo2"
  12. mymath "gitlink.org.cn/cloudream/common/utils/math"
  13. "gitlink.org.cn/cloudream/common/utils/sort2"
  14. "gitlink.org.cn/cloudream/storage/common/consts"
  15. stgglb "gitlink.org.cn/cloudream/storage/common/globals"
  16. stgmod "gitlink.org.cn/cloudream/storage/common/models"
  17. "gitlink.org.cn/cloudream/storage/common/pkgs/distlock/reqbuilder"
  18. "gitlink.org.cn/cloudream/storage/common/pkgs/ioswitch/plans"
  19. agtmq "gitlink.org.cn/cloudream/storage/common/pkgs/mq/agent"
  20. coormq "gitlink.org.cn/cloudream/storage/common/pkgs/mq/coordinator"
  21. scevt "gitlink.org.cn/cloudream/storage/common/pkgs/mq/scanner/event"
  22. )
  23. type CleanPinned struct {
  24. *scevt.CleanPinned
  25. }
  26. func NewCleanPinned(evt *scevt.CleanPinned) *CleanPinned {
  27. return &CleanPinned{
  28. CleanPinned: evt,
  29. }
  30. }
  31. func (t *CleanPinned) TryMerge(other Event) bool {
  32. event, ok := other.(*CleanPinned)
  33. if !ok {
  34. return false
  35. }
  36. return t.PackageID == event.PackageID
  37. }
  38. func (t *CleanPinned) Execute(execCtx ExecuteContext) {
  39. log := logger.WithType[CleanPinned]("Event")
  40. log.Debugf("begin with %v", logger.FormatStruct(t.CleanPinned))
  41. defer log.Debugf("end")
  42. coorCli, err := stgglb.CoordinatorMQPool.Acquire()
  43. if err != nil {
  44. log.Warnf("new coordinator client: %s", err.Error())
  45. return
  46. }
  47. defer stgglb.CoordinatorMQPool.Release(coorCli)
  48. getObjs, err := coorCli.GetPackageObjectDetails(coormq.NewGetPackageObjectDetails(t.PackageID))
  49. if err != nil {
  50. log.Warnf("getting package objects: %s", err.Error())
  51. return
  52. }
  53. getLoadLog, err := coorCli.GetPackageLoadLogDetails(coormq.ReqGetPackageLoadLogDetails(t.PackageID))
  54. if err != nil {
  55. log.Warnf("getting package load log details: %s", err.Error())
  56. return
  57. }
  58. readerNodeIDs := lo.Map(getLoadLog.Logs, func(item coormq.PackageLoadLogDetail, idx int) cdssdk.NodeID { return item.Storage.NodeID })
  59. // 注意!需要保证allNodeID包含所有之后可能用到的节点ID
  60. // TOOD 可以考虑设计Cache机制
  61. var allNodeID []cdssdk.NodeID
  62. for _, obj := range getObjs.Objects {
  63. for _, block := range obj.Blocks {
  64. allNodeID = append(allNodeID, block.NodeID)
  65. }
  66. allNodeID = append(allNodeID, obj.PinnedAt...)
  67. }
  68. allNodeID = append(allNodeID, readerNodeIDs...)
  69. getNodeResp, err := coorCli.GetNodes(coormq.NewGetNodes(lo.Union(allNodeID)))
  70. if err != nil {
  71. log.Warnf("getting nodes: %s", err.Error())
  72. return
  73. }
  74. allNodeInfos := make(map[cdssdk.NodeID]*cdssdk.Node)
  75. for _, node := range getNodeResp.Nodes {
  76. n := node
  77. allNodeInfos[node.NodeID] = &n
  78. }
  79. // 只对ec和rep对象进行处理
  80. var ecObjects []stgmod.ObjectDetail
  81. var repObjects []stgmod.ObjectDetail
  82. for _, obj := range getObjs.Objects {
  83. if _, ok := obj.Object.Redundancy.(*cdssdk.ECRedundancy); ok {
  84. ecObjects = append(ecObjects, obj)
  85. } else if _, ok := obj.Object.Redundancy.(*cdssdk.RepRedundancy); ok {
  86. repObjects = append(repObjects, obj)
  87. }
  88. }
  89. planBld := plans.NewPlanBuilder()
  90. pinPlans := make(map[cdssdk.NodeID]*[]string)
  91. // 对于rep对象,统计出所有对象块分布最多的两个节点,用这两个节点代表所有rep对象块的分布,去进行退火算法
  92. var repObjectsUpdateEntries []coormq.ChangeObjectRedundancyEntry
  93. repMostNodeIDs := t.summaryRepObjectBlockNodes(repObjects)
  94. solu := t.startAnnealing(allNodeInfos, readerNodeIDs, annealingObject{
  95. totalBlockCount: 1,
  96. minBlockCnt: 1,
  97. pinnedAt: repMostNodeIDs,
  98. blocks: nil,
  99. })
  100. for _, obj := range repObjects {
  101. repObjectsUpdateEntries = append(repObjectsUpdateEntries, t.makePlansForRepObject(solu, obj, pinPlans))
  102. }
  103. // 对于ec对象,则每个对象单独进行退火算法
  104. var ecObjectsUpdateEntries []coormq.ChangeObjectRedundancyEntry
  105. for _, obj := range ecObjects {
  106. ecRed := obj.Object.Redundancy.(*cdssdk.ECRedundancy)
  107. solu := t.startAnnealing(allNodeInfos, readerNodeIDs, annealingObject{
  108. totalBlockCount: ecRed.N,
  109. minBlockCnt: ecRed.K,
  110. pinnedAt: obj.PinnedAt,
  111. blocks: obj.Blocks,
  112. })
  113. ecObjectsUpdateEntries = append(ecObjectsUpdateEntries, t.makePlansForECObject(allNodeInfos, solu, obj, &planBld))
  114. }
  115. ioSwRets, err := t.executePlans(execCtx, pinPlans, &planBld)
  116. if err != nil {
  117. log.Warn(err.Error())
  118. return
  119. }
  120. // 根据按照方案进行调整的结果,填充更新元数据的命令
  121. for i := range ecObjectsUpdateEntries {
  122. t.populateECObjectEntry(&ecObjectsUpdateEntries[i], ecObjects[i], ioSwRets)
  123. }
  124. finalEntries := append(repObjectsUpdateEntries, ecObjectsUpdateEntries...)
  125. if len(finalEntries) > 0 {
  126. _, err = coorCli.ChangeObjectRedundancy(coormq.ReqChangeObjectRedundancy(finalEntries))
  127. if err != nil {
  128. log.Warnf("changing object redundancy: %s", err.Error())
  129. return
  130. }
  131. }
  132. }
  133. func (t *CleanPinned) summaryRepObjectBlockNodes(objs []stgmod.ObjectDetail) []cdssdk.NodeID {
  134. type nodeBlocks struct {
  135. NodeID cdssdk.NodeID
  136. Count int
  137. }
  138. nodeBlocksMap := make(map[cdssdk.NodeID]*nodeBlocks)
  139. for _, obj := range objs {
  140. cacheBlockNodes := make(map[cdssdk.NodeID]bool)
  141. for _, block := range obj.Blocks {
  142. if _, ok := nodeBlocksMap[block.NodeID]; !ok {
  143. nodeBlocksMap[block.NodeID] = &nodeBlocks{
  144. NodeID: block.NodeID,
  145. Count: 0,
  146. }
  147. }
  148. nodeBlocksMap[block.NodeID].Count++
  149. cacheBlockNodes[block.NodeID] = true
  150. }
  151. for _, nodeID := range obj.PinnedAt {
  152. if cacheBlockNodes[nodeID] {
  153. continue
  154. }
  155. if _, ok := nodeBlocksMap[nodeID]; !ok {
  156. nodeBlocksMap[nodeID] = &nodeBlocks{
  157. NodeID: nodeID,
  158. Count: 0,
  159. }
  160. }
  161. nodeBlocksMap[nodeID].Count++
  162. }
  163. }
  164. nodes := lo.Values(nodeBlocksMap)
  165. sort2.Sort(nodes, func(left *nodeBlocks, right *nodeBlocks) int {
  166. return right.Count - left.Count
  167. })
  168. // 只选出块数超过一半的节点,但要保证至少有两个节点
  169. for i := 2; i < len(nodes); i++ {
  170. if nodes[i].Count < len(objs)/2 {
  171. nodes = nodes[:i]
  172. break
  173. }
  174. }
  175. return lo.Map(nodes, func(item *nodeBlocks, idx int) cdssdk.NodeID { return item.NodeID })
  176. }
  177. type annealingState struct {
  178. allNodeInfos map[cdssdk.NodeID]*cdssdk.Node // 所有节点的信息
  179. readerNodeIDs []cdssdk.NodeID // 近期可能访问此对象的节点
  180. nodesSortedByReader map[cdssdk.NodeID][]nodeDist // 拥有数据的节点到每个可能访问对象的节点按距离排序
  181. object annealingObject // 进行退火的对象
  182. blockList []objectBlock // 排序后的块分布情况
  183. nodeBlockBitmaps map[cdssdk.NodeID]*bitmap.Bitmap64 // 用位图的形式表示每一个节点上有哪些块
  184. nodeCombTree combinatorialTree // 节点组合树,用于加速计算容灾度
  185. maxScore float64 // 搜索过程中得到过的最大分数
  186. maxScoreRmBlocks []bool // 最大分数对应的删除方案
  187. rmBlocks []bool // 当前删除方案
  188. inversedIndex int // 当前删除方案是从上一次的方案改动哪个flag而来的
  189. lastScore float64 // 上一次方案的分数
  190. }
  191. type objectBlock struct {
  192. Index int
  193. NodeID cdssdk.NodeID
  194. HasEntity bool // 节点拥有实际的文件数据块
  195. HasShadow bool // 如果节点拥有完整文件数据,那么认为这个节点拥有所有块,这些块被称为影子块
  196. FileHash string // 只有在拥有实际文件数据块时,这个字段才有值
  197. }
  198. type nodeDist struct {
  199. NodeID cdssdk.NodeID
  200. Distance float64
  201. }
  202. type combinatorialTree struct {
  203. nodes []combinatorialTreeNode
  204. blocksMaps map[int]bitmap.Bitmap64
  205. nodeIDToLocalNodeID map[cdssdk.NodeID]int
  206. localNodeIDToNodeID []cdssdk.NodeID
  207. }
  208. type annealingObject struct {
  209. totalBlockCount int
  210. minBlockCnt int
  211. pinnedAt []cdssdk.NodeID
  212. blocks []stgmod.ObjectBlock
  213. }
  214. const (
  215. iterActionNone = 0
  216. iterActionSkip = 1
  217. iterActionBreak = 2
  218. )
  219. func newCombinatorialTree(nodeBlocksMaps map[cdssdk.NodeID]*bitmap.Bitmap64) combinatorialTree {
  220. tree := combinatorialTree{
  221. blocksMaps: make(map[int]bitmap.Bitmap64),
  222. nodeIDToLocalNodeID: make(map[cdssdk.NodeID]int),
  223. }
  224. tree.nodes = make([]combinatorialTreeNode, (1 << len(nodeBlocksMaps)))
  225. for id, mp := range nodeBlocksMaps {
  226. tree.nodeIDToLocalNodeID[id] = len(tree.localNodeIDToNodeID)
  227. tree.blocksMaps[len(tree.localNodeIDToNodeID)] = *mp
  228. tree.localNodeIDToNodeID = append(tree.localNodeIDToNodeID, id)
  229. }
  230. tree.nodes[0].localNodeID = -1
  231. index := 1
  232. tree.initNode(0, &tree.nodes[0], &index)
  233. return tree
  234. }
  235. func (t *combinatorialTree) initNode(minAvaiLocalNodeID int, parent *combinatorialTreeNode, index *int) {
  236. for i := minAvaiLocalNodeID; i < len(t.nodeIDToLocalNodeID); i++ {
  237. curIndex := *index
  238. *index++
  239. bitMp := t.blocksMaps[i]
  240. bitMp.Or(&parent.blocksBitmap)
  241. t.nodes[curIndex] = combinatorialTreeNode{
  242. localNodeID: i,
  243. parent: parent,
  244. blocksBitmap: bitMp,
  245. }
  246. t.initNode(i+1, &t.nodes[curIndex], index)
  247. }
  248. }
  249. // 获得索引指定的节点所在的层
  250. func (t *combinatorialTree) GetDepth(index int) int {
  251. depth := 0
  252. // 反复判断节点在哪个子树。从左到右,子树节点的数量呈现8 4 2的变化,由此可以得到每个子树的索引值的范围
  253. subTreeCount := 1 << len(t.nodeIDToLocalNodeID)
  254. for index > 0 {
  255. if index < subTreeCount {
  256. // 定位到一个子树后,深度+1,然后进入这个子树,使用同样的方法再进行定位。
  257. // 进入子树后需要将索引值-1,因为要去掉子树的根节点
  258. index--
  259. depth++
  260. } else {
  261. // 如果索引值不在这个子树范围内,则将值减去子树的节点数量,
  262. // 这样每一次都可以视为使用同样的逻辑对不同大小的树进行判断。
  263. index -= subTreeCount
  264. }
  265. subTreeCount >>= 1
  266. }
  267. return depth
  268. }
  269. // 更新某一个算力中心节点的块分布位图,同时更新它对应组合树节点的所有子节点。
  270. // 如果更新到某个节点时,已有K个块,那么就不会再更新它的子节点
  271. func (t *combinatorialTree) UpdateBitmap(nodeID cdssdk.NodeID, mp bitmap.Bitmap64, k int) {
  272. t.blocksMaps[t.nodeIDToLocalNodeID[nodeID]] = mp
  273. // 首先定义两种遍历树节点时的移动方式:
  274. // 1. 竖直移动(深度增加):从一个节点移动到它最左边的子节点。每移动一步,index+1
  275. // 2. 水平移动:从一个节点移动到它右边的兄弟节点。每移动一步,根据它所在的深度,index+8,+4,+2
  276. // LocalNodeID从0开始,将其+1后得到移动步数steps。
  277. // 将移动步数拆成多部分,分配到上述的两种移动方式上,并进行任意组合,且保证第一次为至少进行一次的竖直移动,移动之后的节点都会是同一个计算中心节点。
  278. steps := t.nodeIDToLocalNodeID[nodeID] + 1
  279. for d := 1; d <= steps; d++ {
  280. t.iterCombBits(len(t.nodeIDToLocalNodeID)-1, steps-d, 0, func(i int) {
  281. index := d + i
  282. node := &t.nodes[index]
  283. newMp := t.blocksMaps[node.localNodeID]
  284. newMp.Or(&node.parent.blocksBitmap)
  285. node.blocksBitmap = newMp
  286. if newMp.Weight() >= k {
  287. return
  288. }
  289. t.iterChildren(index, func(index, parentIndex, depth int) int {
  290. curNode := &t.nodes[index]
  291. parentNode := t.nodes[parentIndex]
  292. newMp := t.blocksMaps[curNode.localNodeID]
  293. newMp.Or(&parentNode.blocksBitmap)
  294. curNode.blocksBitmap = newMp
  295. if newMp.Weight() >= k {
  296. return iterActionSkip
  297. }
  298. return iterActionNone
  299. })
  300. })
  301. }
  302. }
  303. // 遍历树,找到至少拥有K个块的树节点的最大深度
  304. func (t *combinatorialTree) FindKBlocksMaxDepth(k int) int {
  305. maxDepth := -1
  306. t.iterChildren(0, func(index, parentIndex, depth int) int {
  307. if t.nodes[index].blocksBitmap.Weight() >= k {
  308. if maxDepth < depth {
  309. maxDepth = depth
  310. }
  311. return iterActionSkip
  312. }
  313. // 如果到了叶子节点,还没有找到K个块,那就认为要满足K个块,至少需要再多一个节点,即深度+1。
  314. // 由于遍历时采用的是深度优先的算法,因此遍历到这个叶子节点时,叶子节点再加一个节点的组合已经在前面搜索过,
  315. // 所以用当前叶子节点深度+1来作为当前分支的结果就可以,即使当前情况下增加任意一个节点依然不够K块,
  316. // 可以使用同样的思路去递推到当前叶子节点增加两个块的情况。
  317. if t.nodes[index].localNodeID == len(t.nodeIDToLocalNodeID)-1 {
  318. if maxDepth < depth+1 {
  319. maxDepth = depth + 1
  320. }
  321. }
  322. return iterActionNone
  323. })
  324. if maxDepth == -1 || maxDepth > len(t.nodeIDToLocalNodeID) {
  325. return len(t.nodeIDToLocalNodeID)
  326. }
  327. return maxDepth
  328. }
  329. func (t *combinatorialTree) iterCombBits(width int, count int, offset int, callback func(int)) {
  330. if count == 0 {
  331. callback(offset)
  332. return
  333. }
  334. for b := width; b >= count; b-- {
  335. t.iterCombBits(b-1, count-1, offset+(1<<b), callback)
  336. }
  337. }
  338. func (t *combinatorialTree) iterChildren(index int, do func(index int, parentIndex int, depth int) int) {
  339. curNode := &t.nodes[index]
  340. childIndex := index + 1
  341. curDepth := t.GetDepth(index)
  342. childCounts := len(t.nodeIDToLocalNodeID) - 1 - curNode.localNodeID
  343. if childCounts == 0 {
  344. return
  345. }
  346. childTreeNodeCnt := 1 << (childCounts - 1)
  347. for c := 0; c < childCounts; c++ {
  348. act := t.itering(childIndex, index, curDepth+1, do)
  349. if act == iterActionBreak {
  350. return
  351. }
  352. childIndex += childTreeNodeCnt
  353. childTreeNodeCnt >>= 1
  354. }
  355. }
  356. func (t *combinatorialTree) itering(index int, parentIndex int, depth int, do func(index int, parentIndex int, depth int) int) int {
  357. act := do(index, parentIndex, depth)
  358. if act == iterActionBreak {
  359. return act
  360. }
  361. if act == iterActionSkip {
  362. return iterActionNone
  363. }
  364. curNode := &t.nodes[index]
  365. childIndex := index + 1
  366. childCounts := len(t.nodeIDToLocalNodeID) - 1 - curNode.localNodeID
  367. if childCounts == 0 {
  368. return iterActionNone
  369. }
  370. childTreeNodeCnt := 1 << (childCounts - 1)
  371. for c := 0; c < childCounts; c++ {
  372. act = t.itering(childIndex, index, depth+1, do)
  373. if act == iterActionBreak {
  374. return act
  375. }
  376. childIndex += childTreeNodeCnt
  377. childTreeNodeCnt >>= 1
  378. }
  379. return iterActionNone
  380. }
  381. type combinatorialTreeNode struct {
  382. localNodeID int
  383. parent *combinatorialTreeNode
  384. blocksBitmap bitmap.Bitmap64 // 选择了这个中心之后,所有中心一共包含多少种块
  385. }
  386. type annealingSolution struct {
  387. blockList []objectBlock // 所有节点的块分布情况
  388. rmBlocks []bool // 要删除哪些块
  389. }
  390. func (t *CleanPinned) startAnnealing(allNodeInfos map[cdssdk.NodeID]*cdssdk.Node, readerNodeIDs []cdssdk.NodeID, object annealingObject) annealingSolution {
  391. state := &annealingState{
  392. allNodeInfos: allNodeInfos,
  393. readerNodeIDs: readerNodeIDs,
  394. nodesSortedByReader: make(map[cdssdk.NodeID][]nodeDist),
  395. object: object,
  396. nodeBlockBitmaps: make(map[cdssdk.NodeID]*bitmap.Bitmap64),
  397. }
  398. t.initBlockList(state)
  399. if state.blockList == nil {
  400. return annealingSolution{}
  401. }
  402. t.initNodeBlockBitmap(state)
  403. t.sortNodeByReaderDistance(state)
  404. state.rmBlocks = make([]bool, len(state.blockList))
  405. state.inversedIndex = -1
  406. state.nodeCombTree = newCombinatorialTree(state.nodeBlockBitmaps)
  407. state.lastScore = t.calcScore(state)
  408. state.maxScore = state.lastScore
  409. state.maxScoreRmBlocks = lo2.ArrayClone(state.rmBlocks)
  410. // 模拟退火算法的温度
  411. curTemp := state.lastScore
  412. // 结束温度
  413. finalTemp := curTemp * 0.2
  414. // 冷却率
  415. coolingRate := 0.95
  416. for curTemp > finalTemp {
  417. state.inversedIndex = rand.Intn(len(state.rmBlocks))
  418. block := state.blockList[state.inversedIndex]
  419. state.rmBlocks[state.inversedIndex] = !state.rmBlocks[state.inversedIndex]
  420. state.nodeBlockBitmaps[block.NodeID].Set(block.Index, !state.rmBlocks[state.inversedIndex])
  421. state.nodeCombTree.UpdateBitmap(block.NodeID, *state.nodeBlockBitmaps[block.NodeID], state.object.minBlockCnt)
  422. curScore := t.calcScore(state)
  423. dScore := curScore - state.lastScore
  424. // 如果新方案比旧方案得分低,且没有要求强制接受新方案,那么就将变化改回去
  425. if curScore == 0 || (dScore < 0 && !t.alwaysAccept(curTemp, dScore, coolingRate)) {
  426. state.rmBlocks[state.inversedIndex] = !state.rmBlocks[state.inversedIndex]
  427. state.nodeBlockBitmaps[block.NodeID].Set(block.Index, !state.rmBlocks[state.inversedIndex])
  428. state.nodeCombTree.UpdateBitmap(block.NodeID, *state.nodeBlockBitmaps[block.NodeID], state.object.minBlockCnt)
  429. // fmt.Printf("\n")
  430. } else {
  431. // fmt.Printf(" accept!\n")
  432. state.lastScore = curScore
  433. if state.maxScore < curScore {
  434. state.maxScore = state.lastScore
  435. state.maxScoreRmBlocks = lo2.ArrayClone(state.rmBlocks)
  436. }
  437. }
  438. curTemp *= coolingRate
  439. }
  440. // fmt.Printf("final: %v\n", state.maxScoreRmBlocks)
  441. return annealingSolution{
  442. blockList: state.blockList,
  443. rmBlocks: state.maxScoreRmBlocks,
  444. }
  445. }
  446. func (t *CleanPinned) initBlockList(ctx *annealingState) {
  447. blocksMap := make(map[cdssdk.NodeID][]objectBlock)
  448. // 先生成所有的影子块
  449. for _, pinned := range ctx.object.pinnedAt {
  450. blocks := make([]objectBlock, 0, ctx.object.totalBlockCount)
  451. for i := 0; i < ctx.object.totalBlockCount; i++ {
  452. blocks = append(blocks, objectBlock{
  453. Index: i,
  454. NodeID: pinned,
  455. HasShadow: true,
  456. })
  457. }
  458. blocksMap[pinned] = blocks
  459. }
  460. // 再填充实际块
  461. for _, b := range ctx.object.blocks {
  462. blocks := blocksMap[b.NodeID]
  463. has := false
  464. for i := range blocks {
  465. if blocks[i].Index == b.Index {
  466. blocks[i].HasEntity = true
  467. blocks[i].FileHash = b.FileHash
  468. has = true
  469. break
  470. }
  471. }
  472. if has {
  473. continue
  474. }
  475. blocks = append(blocks, objectBlock{
  476. Index: b.Index,
  477. NodeID: b.NodeID,
  478. HasEntity: true,
  479. FileHash: b.FileHash,
  480. })
  481. blocksMap[b.NodeID] = blocks
  482. }
  483. var sortedBlocks []objectBlock
  484. for _, bs := range blocksMap {
  485. sortedBlocks = append(sortedBlocks, bs...)
  486. }
  487. sortedBlocks = sort2.Sort(sortedBlocks, func(left objectBlock, right objectBlock) int {
  488. d := left.NodeID - right.NodeID
  489. if d != 0 {
  490. return int(d)
  491. }
  492. return left.Index - right.Index
  493. })
  494. ctx.blockList = sortedBlocks
  495. }
  496. func (t *CleanPinned) initNodeBlockBitmap(state *annealingState) {
  497. for _, b := range state.blockList {
  498. mp, ok := state.nodeBlockBitmaps[b.NodeID]
  499. if !ok {
  500. nb := bitmap.Bitmap64(0)
  501. mp = &nb
  502. state.nodeBlockBitmaps[b.NodeID] = mp
  503. }
  504. mp.Set(b.Index, true)
  505. }
  506. }
  507. func (t *CleanPinned) sortNodeByReaderDistance(state *annealingState) {
  508. for _, r := range state.readerNodeIDs {
  509. var nodeDists []nodeDist
  510. for n := range state.nodeBlockBitmaps {
  511. if r == n {
  512. // 同节点时距离视为0.1
  513. nodeDists = append(nodeDists, nodeDist{
  514. NodeID: n,
  515. Distance: consts.NodeDistanceSameNode,
  516. })
  517. } else if state.allNodeInfos[r].LocationID == state.allNodeInfos[n].LocationID {
  518. // 同地区时距离视为1
  519. nodeDists = append(nodeDists, nodeDist{
  520. NodeID: n,
  521. Distance: consts.NodeDistanceSameLocation,
  522. })
  523. } else {
  524. // 不同地区时距离视为5
  525. nodeDists = append(nodeDists, nodeDist{
  526. NodeID: n,
  527. Distance: consts.NodeDistanceOther,
  528. })
  529. }
  530. }
  531. state.nodesSortedByReader[r] = sort2.Sort(nodeDists, func(left, right nodeDist) int { return sort2.Cmp(left.Distance, right.Distance) })
  532. }
  533. }
  534. func (t *CleanPinned) calcScore(state *annealingState) float64 {
  535. dt := t.calcDisasterTolerance(state)
  536. ac := t.calcMinAccessCost(state)
  537. sc := t.calcSpaceCost(state)
  538. dtSc := 1.0
  539. if dt < 1 {
  540. dtSc = 0
  541. } else if dt >= 2 {
  542. dtSc = 1.5
  543. }
  544. newSc := 0.0
  545. if dt == 0 || ac == 0 {
  546. newSc = 0
  547. } else {
  548. newSc = dtSc / (sc * ac)
  549. }
  550. // fmt.Printf("solu: %v, cur: %v, dt: %v, ac: %v, sc: %v \n", state.rmBlocks, newSc, dt, ac, sc)
  551. return newSc
  552. }
  553. // 计算容灾度
  554. func (t *CleanPinned) calcDisasterTolerance(state *annealingState) float64 {
  555. if state.inversedIndex != -1 {
  556. node := state.blockList[state.inversedIndex]
  557. state.nodeCombTree.UpdateBitmap(node.NodeID, *state.nodeBlockBitmaps[node.NodeID], state.object.minBlockCnt)
  558. }
  559. return float64(len(state.nodeBlockBitmaps) - state.nodeCombTree.FindKBlocksMaxDepth(state.object.minBlockCnt))
  560. }
  561. // 计算最小访问数据的代价
  562. func (t *CleanPinned) calcMinAccessCost(state *annealingState) float64 {
  563. cost := math.MaxFloat64
  564. for _, reader := range state.readerNodeIDs {
  565. tarNodes := state.nodesSortedByReader[reader]
  566. gotBlocks := bitmap.Bitmap64(0)
  567. thisCost := 0.0
  568. for _, tar := range tarNodes {
  569. tarNodeMp := state.nodeBlockBitmaps[tar.NodeID]
  570. // 只需要从目的节点上获得缺少的块
  571. curWeigth := gotBlocks.Weight()
  572. // 下面的if会在拿到k个块之后跳出循环,所以or多了块也没关系
  573. gotBlocks.Or(tarNodeMp)
  574. // 但是算读取块的消耗时,不能多算,最多算读了k个块的消耗
  575. willGetBlocks := mymath.Min(gotBlocks.Weight()-curWeigth, state.object.minBlockCnt-curWeigth)
  576. thisCost += float64(willGetBlocks) * float64(tar.Distance)
  577. if gotBlocks.Weight() >= state.object.minBlockCnt {
  578. break
  579. }
  580. }
  581. if gotBlocks.Weight() >= state.object.minBlockCnt {
  582. cost = math.Min(cost, thisCost)
  583. }
  584. }
  585. return cost
  586. }
  587. // 计算冗余度
  588. func (t *CleanPinned) calcSpaceCost(ctx *annealingState) float64 {
  589. blockCount := 0
  590. for i, b := range ctx.blockList {
  591. if ctx.rmBlocks[i] {
  592. continue
  593. }
  594. if b.HasEntity {
  595. blockCount++
  596. }
  597. if b.HasShadow {
  598. blockCount++
  599. }
  600. }
  601. // 所有算力中心上拥有的块的总数 / 一个对象被分成了几个块
  602. return float64(blockCount) / float64(ctx.object.minBlockCnt)
  603. }
  604. // 如果新方案得分比旧方案小,那么在一定概率内也接受新方案
  605. func (t *CleanPinned) alwaysAccept(curTemp float64, dScore float64, coolingRate float64) bool {
  606. v := math.Exp(dScore / curTemp / coolingRate)
  607. // fmt.Printf(" -- chance: %v, temp: %v", v, curTemp)
  608. return v > rand.Float64()
  609. }
  610. func (t *CleanPinned) makePlansForRepObject(solu annealingSolution, obj stgmod.ObjectDetail, pinPlans map[cdssdk.NodeID]*[]string) coormq.ChangeObjectRedundancyEntry {
  611. entry := coormq.ChangeObjectRedundancyEntry{
  612. ObjectID: obj.Object.ObjectID,
  613. Redundancy: obj.Object.Redundancy,
  614. }
  615. for i, f := range solu.rmBlocks {
  616. hasCache := lo.ContainsBy(obj.Blocks, func(b stgmod.ObjectBlock) bool { return b.NodeID == solu.blockList[i].NodeID }) ||
  617. lo.ContainsBy(obj.PinnedAt, func(n cdssdk.NodeID) bool { return n == solu.blockList[i].NodeID })
  618. willRm := f
  619. if !willRm {
  620. // 如果对象在退火后要保留副本的节点没有副本,则需要在这个节点创建副本
  621. if !hasCache {
  622. pinPlan, ok := pinPlans[solu.blockList[i].NodeID]
  623. if !ok {
  624. pinPlan = &[]string{}
  625. pinPlans[solu.blockList[i].NodeID] = pinPlan
  626. }
  627. *pinPlan = append(*pinPlan, obj.Object.FileHash)
  628. }
  629. entry.Blocks = append(entry.Blocks, stgmod.ObjectBlock{
  630. ObjectID: obj.Object.ObjectID,
  631. Index: solu.blockList[i].Index,
  632. NodeID: solu.blockList[i].NodeID,
  633. FileHash: obj.Object.FileHash,
  634. })
  635. }
  636. }
  637. return entry
  638. }
  639. func (t *CleanPinned) makePlansForECObject(allNodeInfos map[cdssdk.NodeID]*cdssdk.Node, solu annealingSolution, obj stgmod.ObjectDetail, planBld *plans.PlanBuilder) coormq.ChangeObjectRedundancyEntry {
  640. entry := coormq.ChangeObjectRedundancyEntry{
  641. ObjectID: obj.Object.ObjectID,
  642. Redundancy: obj.Object.Redundancy,
  643. }
  644. reconstrct := make(map[cdssdk.NodeID]*[]int)
  645. for i, f := range solu.rmBlocks {
  646. block := solu.blockList[i]
  647. if !f {
  648. entry.Blocks = append(entry.Blocks, stgmod.ObjectBlock{
  649. ObjectID: obj.Object.ObjectID,
  650. Index: block.Index,
  651. NodeID: block.NodeID,
  652. FileHash: block.FileHash,
  653. })
  654. // 如果这个块是影子块,那么就要从完整对象里重建这个块
  655. if !block.HasEntity {
  656. re, ok := reconstrct[block.NodeID]
  657. if !ok {
  658. re = &[]int{}
  659. reconstrct[block.NodeID] = re
  660. }
  661. *re = append(*re, block.Index)
  662. }
  663. }
  664. }
  665. ecRed := obj.Object.Redundancy.(*cdssdk.ECRedundancy)
  666. for id, idxs := range reconstrct {
  667. agt := planBld.AtAgent(*allNodeInfos[id])
  668. strs := agt.IPFSRead(obj.Object.FileHash).ChunkedSplit(ecRed.ChunkSize, ecRed.K, true)
  669. ss := agt.ECReconstructAny(*ecRed, lo.Range(ecRed.K), *idxs, strs.Streams...)
  670. for i, s := range ss.Streams {
  671. s.IPFSWrite(fmt.Sprintf("%d.%d", obj.Object.ObjectID, (*idxs)[i]))
  672. }
  673. }
  674. return entry
  675. }
  676. func (t *CleanPinned) executePlans(execCtx ExecuteContext, pinPlans map[cdssdk.NodeID]*[]string, planBld *plans.PlanBuilder) (map[string]any, error) {
  677. log := logger.WithType[CleanPinned]("Event")
  678. ioPlan, err := planBld.Build()
  679. if err != nil {
  680. return nil, fmt.Errorf("building io switch plan: %w", err)
  681. }
  682. // 统一加锁,有重复也没关系
  683. lockBld := reqbuilder.NewBuilder()
  684. for nodeID := range pinPlans {
  685. lockBld.IPFS().Buzy(nodeID)
  686. }
  687. for _, plan := range ioPlan.AgentPlans {
  688. lockBld.IPFS().Buzy(plan.Node.NodeID)
  689. }
  690. lock, err := lockBld.MutexLock(execCtx.Args.DistLock)
  691. if err != nil {
  692. return nil, fmt.Errorf("acquiring distlock: %w", err)
  693. }
  694. defer lock.Unlock()
  695. wg := sync.WaitGroup{}
  696. // 执行pin操作
  697. var anyPinErr error
  698. for nodeID, pin := range pinPlans {
  699. wg.Add(1)
  700. go func(nodeID cdssdk.NodeID, pin *[]string) {
  701. defer wg.Done()
  702. agtCli, err := stgglb.AgentMQPool.Acquire(nodeID)
  703. if err != nil {
  704. log.Warnf("new agent client: %s", err.Error())
  705. return
  706. }
  707. defer stgglb.AgentMQPool.Release(agtCli)
  708. _, err = agtCli.PinObject(agtmq.ReqPinObject(*pin, false))
  709. if err != nil {
  710. log.Warnf("pinning object: %s", err.Error())
  711. anyPinErr = err
  712. }
  713. }(nodeID, pin)
  714. }
  715. // 执行IO计划
  716. var ioSwRets map[string]any
  717. var ioSwErr error
  718. wg.Add(1)
  719. go func() {
  720. defer wg.Done()
  721. exec, err := plans.Execute(*ioPlan)
  722. if err != nil {
  723. ioSwErr = fmt.Errorf("executing io switch plan: %w", err)
  724. return
  725. }
  726. ret, err := exec.Wait()
  727. if err != nil {
  728. ioSwErr = fmt.Errorf("waiting io switch plan: %w", err)
  729. return
  730. }
  731. ioSwRets = ret.ResultValues
  732. }()
  733. wg.Wait()
  734. if anyPinErr != nil {
  735. return nil, anyPinErr
  736. }
  737. if ioSwErr != nil {
  738. return nil, ioSwErr
  739. }
  740. return ioSwRets, nil
  741. }
  742. func (t *CleanPinned) populateECObjectEntry(entry *coormq.ChangeObjectRedundancyEntry, obj stgmod.ObjectDetail, ioRets map[string]any) {
  743. for i := range entry.Blocks {
  744. if entry.Blocks[i].FileHash != "" {
  745. continue
  746. }
  747. key := fmt.Sprintf("%d.%d", obj.Object.ObjectID, entry.Blocks[i].Index)
  748. // 不应该出现key不存在的情况
  749. entry.Blocks[i].FileHash = ioRets[key].(string)
  750. }
  751. }
  752. func init() {
  753. RegisterMessageConvertor(NewCleanPinned)
  754. }

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