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.

rep_object_iterator.go 5.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. package iterator
  2. import (
  3. "fmt"
  4. "io"
  5. "math/rand"
  6. "github.com/samber/lo"
  7. distsvc "gitlink.org.cn/cloudream/common/pkgs/distlock/service"
  8. "gitlink.org.cn/cloudream/common/pkgs/logger"
  9. myio "gitlink.org.cn/cloudream/common/utils/io"
  10. "gitlink.org.cn/cloudream/storage-common/globals"
  11. "gitlink.org.cn/cloudream/storage-common/models"
  12. "gitlink.org.cn/cloudream/storage-common/pkgs/db/model"
  13. "gitlink.org.cn/cloudream/storage-common/pkgs/distlock/reqbuilder"
  14. coormq "gitlink.org.cn/cloudream/storage-common/pkgs/mq/coordinator"
  15. )
  16. type DownloadingObjectIterator = Iterator[*IterDownloadingObject]
  17. type RepObjectIterator struct {
  18. OnClosing func()
  19. objects []model.Object
  20. objectRepData []models.ObjectRepData
  21. currentIndex int
  22. inited bool
  23. downloadCtx *DownloadContext
  24. cliLocation model.Location
  25. }
  26. type IterDownloadingObject struct {
  27. Object model.Object
  28. File io.ReadCloser
  29. }
  30. type DownloadNodeInfo struct {
  31. Node model.Node
  32. IsSameLocation bool
  33. }
  34. type DownloadContext struct {
  35. Distlock *distsvc.Service
  36. }
  37. func NewRepObjectIterator(objects []model.Object, objectRepData []models.ObjectRepData, downloadCtx *DownloadContext) *RepObjectIterator {
  38. return &RepObjectIterator{
  39. objects: objects,
  40. objectRepData: objectRepData,
  41. downloadCtx: downloadCtx,
  42. }
  43. }
  44. func (i *RepObjectIterator) MoveNext() (*IterDownloadingObject, error) {
  45. // TODO 加锁
  46. coorCli, err := globals.CoordinatorMQPool.Acquire()
  47. if err != nil {
  48. return nil, fmt.Errorf("new coordinator client: %w", err)
  49. }
  50. defer coorCli.Close()
  51. if !i.inited {
  52. i.inited = true
  53. findCliLocResp, err := coorCli.FindClientLocation(coormq.NewFindClientLocation(globals.Local.ExternalIP))
  54. if err != nil {
  55. return nil, fmt.Errorf("finding client location: %w", err)
  56. }
  57. i.cliLocation = findCliLocResp.Location
  58. }
  59. if i.currentIndex >= len(i.objects) {
  60. return nil, ErrNoMoreItem
  61. }
  62. item, err := i.doMove(coorCli)
  63. i.currentIndex++
  64. return item, err
  65. }
  66. func (i *RepObjectIterator) doMove(coorCli *coormq.PoolClient) (*IterDownloadingObject, error) {
  67. repData := i.objectRepData[i.currentIndex]
  68. if len(repData.NodeIDs) == 0 {
  69. return nil, fmt.Errorf("no node has this file %s", repData.FileHash)
  70. }
  71. getNodesResp, err := coorCli.GetNodes(coormq.NewGetNodes(repData.NodeIDs))
  72. if err != nil {
  73. return nil, fmt.Errorf("getting nodes: %w", err)
  74. }
  75. downloadNodes := lo.Map(getNodesResp.Nodes, func(node model.Node, index int) DownloadNodeInfo {
  76. return DownloadNodeInfo{
  77. Node: node,
  78. IsSameLocation: node.LocationID == i.cliLocation.LocationID,
  79. }
  80. })
  81. // 选择下载节点
  82. downloadNode := i.chooseDownloadNode(downloadNodes)
  83. // 如果客户端与节点在同一个地域,则使用内网地址连接节点
  84. nodeIP := downloadNode.Node.ExternalIP
  85. if downloadNode.IsSameLocation {
  86. nodeIP = downloadNode.Node.LocalIP
  87. logger.Infof("client and node %d are at the same location, use local ip\n", downloadNode.Node.NodeID)
  88. }
  89. reader, err := downloadFile(i.downloadCtx, downloadNode.Node.NodeID, nodeIP, repData.FileHash)
  90. if err != nil {
  91. return nil, fmt.Errorf("rep read failed, err: %w", err)
  92. }
  93. return &IterDownloadingObject{
  94. Object: i.objects[i.currentIndex],
  95. File: reader,
  96. }, nil
  97. }
  98. func (i *RepObjectIterator) Close() {
  99. if i.OnClosing != nil {
  100. i.OnClosing()
  101. }
  102. }
  103. // chooseDownloadNode 选择一个下载节点
  104. // 1. 从与当前客户端相同地域的节点中随机选一个
  105. // 2. 没有用的话从所有节点中随机选一个
  106. func (i *RepObjectIterator) chooseDownloadNode(entries []DownloadNodeInfo) DownloadNodeInfo {
  107. sameLocationEntries := lo.Filter(entries, func(e DownloadNodeInfo, i int) bool { return e.IsSameLocation })
  108. if len(sameLocationEntries) > 0 {
  109. return sameLocationEntries[rand.Intn(len(sameLocationEntries))]
  110. }
  111. return entries[rand.Intn(len(entries))]
  112. }
  113. func downloadFile(ctx *DownloadContext, nodeID int64, nodeIP string, fileHash string) (io.ReadCloser, error) {
  114. if globals.IPFSPool != nil {
  115. logger.Infof("try to use local IPFS to download file")
  116. reader, err := downloadFromLocalIPFS(ctx, fileHash)
  117. if err == nil {
  118. return reader, nil
  119. }
  120. logger.Warnf("download from local IPFS failed, so try to download from node %s, err: %s", nodeIP, err.Error())
  121. }
  122. return downloadFromNode(ctx, nodeID, nodeIP, fileHash)
  123. }
  124. func downloadFromNode(ctx *DownloadContext, nodeID int64, nodeIP string, fileHash string) (io.ReadCloser, error) {
  125. // 二次获取锁
  126. mutex, err := reqbuilder.NewBuilder().
  127. // 用于从IPFS下载文件
  128. IPFS().ReadOneRep(nodeID, fileHash).
  129. MutexLock(ctx.Distlock)
  130. if err != nil {
  131. return nil, fmt.Errorf("acquire locks failed, err: %w", err)
  132. }
  133. // 连接grpc
  134. agtCli, err := globals.AgentRPCPool.Acquire(nodeIP)
  135. if err != nil {
  136. return nil, fmt.Errorf("new agent grpc client: %w", err)
  137. }
  138. reader, err := agtCli.GetIPFSFile(fileHash)
  139. if err != nil {
  140. return nil, fmt.Errorf("getting ipfs file: %w", err)
  141. }
  142. reader = myio.AfterReadClosed(reader, func(io.ReadCloser) {
  143. mutex.Unlock()
  144. })
  145. return reader, nil
  146. }
  147. func downloadFromLocalIPFS(ctx *DownloadContext, fileHash string) (io.ReadCloser, error) {
  148. onClosed := func() {}
  149. if globals.Local.NodeID != nil {
  150. // 二次获取锁
  151. mutex, err := reqbuilder.NewBuilder().
  152. // 用于从IPFS下载文件
  153. IPFS().ReadOneRep(*globals.Local.NodeID, fileHash).
  154. MutexLock(ctx.Distlock)
  155. if err != nil {
  156. return nil, fmt.Errorf("acquire locks failed, err: %w", err)
  157. }
  158. onClosed = func() {
  159. mutex.Unlock()
  160. }
  161. }
  162. ipfsCli, err := globals.IPFSPool.Acquire()
  163. if err != nil {
  164. return nil, fmt.Errorf("new ipfs client: %w", err)
  165. }
  166. reader, err := ipfsCli.OpenRead(fileHash)
  167. if err != nil {
  168. return nil, fmt.Errorf("read ipfs file failed, err: %w", err)
  169. }
  170. reader = myio.AfterReadClosed(reader, func(io.ReadCloser) {
  171. onClosed()
  172. })
  173. return reader, nil
  174. }

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