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 26 kB

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

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