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

2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. package iterator
  2. import (
  3. "fmt"
  4. "io"
  5. "math/rand"
  6. "github.com/samber/lo"
  7. "gitlink.org.cn/cloudream/common/pkgs/distlock"
  8. "gitlink.org.cn/cloudream/common/pkgs/logger"
  9. myio "gitlink.org.cn/cloudream/common/utils/io"
  10. stgglb "gitlink.org.cn/cloudream/storage/common/globals"
  11. stgmod "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 []stgmod.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 *distlock.Service
  36. }
  37. func NewRepObjectIterator(objects []model.Object, objectRepData []stgmod.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 := stgglb.CoordinatorMQPool.Acquire()
  47. if err != nil {
  48. return nil, fmt.Errorf("new coordinator client: %w", err)
  49. }
  50. defer stgglb.CoordinatorMQPool.Release(coorCli)
  51. if !i.inited {
  52. i.inited = true
  53. findCliLocResp, err := coorCli.FindClientLocation(coormq.NewFindClientLocation(stgglb.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.Client) (*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. reader, err := downloadFile(i.downloadCtx, i.chooseDownloadNode(downloadNodes), repData.FileHash)
  82. if err != nil {
  83. return nil, fmt.Errorf("rep read failed, err: %w", err)
  84. }
  85. return &IterDownloadingObject{
  86. Object: i.objects[i.currentIndex],
  87. File: reader,
  88. }, nil
  89. }
  90. func (i *RepObjectIterator) Close() {
  91. if i.OnClosing != nil {
  92. i.OnClosing()
  93. }
  94. }
  95. // chooseDownloadNode 选择一个下载节点
  96. // 1. 从与当前客户端相同地域的节点中随机选一个
  97. // 2. 没有用的话从所有节点中随机选一个
  98. func (i *RepObjectIterator) chooseDownloadNode(entries []DownloadNodeInfo) DownloadNodeInfo {
  99. sameLocationEntries := lo.Filter(entries, func(e DownloadNodeInfo, i int) bool { return e.IsSameLocation })
  100. if len(sameLocationEntries) > 0 {
  101. return sameLocationEntries[rand.Intn(len(sameLocationEntries))]
  102. }
  103. return entries[rand.Intn(len(entries))]
  104. }
  105. func downloadFile(ctx *DownloadContext, node DownloadNodeInfo, fileHash string) (io.ReadCloser, error) {
  106. // 如果客户端与节点在同一个地域,则使用内网地址连接节点
  107. nodeIP := node.Node.ExternalIP
  108. grpcPort := node.Node.ExternalGRPCPort
  109. if node.IsSameLocation {
  110. nodeIP = node.Node.LocalIP
  111. grpcPort = node.Node.LocalGRPCPort
  112. logger.Infof("client and node %d are at the same location, use local ip", node.Node.NodeID)
  113. }
  114. if stgglb.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, node.Node.NodeID, nodeIP, grpcPort, fileHash)
  123. }
  124. func downloadFromNode(ctx *DownloadContext, nodeID int64, nodeIP string, grpcPort int, 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 := stgglb.AgentRPCPool.Acquire(nodeIP, grpcPort)
  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 stgglb.Local.NodeID != nil {
  150. // 二次获取锁
  151. mutex, err := reqbuilder.NewBuilder().
  152. // 用于从IPFS下载文件
  153. IPFS().ReadOneRep(*stgglb.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 := stgglb.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. }

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