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.

object.go 7.5 kB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. package services
  2. import (
  3. "fmt"
  4. "io"
  5. "math/rand"
  6. "time"
  7. "gitlink.org.cn/cloudream/client/internal/config"
  8. "gitlink.org.cn/cloudream/client/internal/task"
  9. "gitlink.org.cn/cloudream/common/consts"
  10. "gitlink.org.cn/cloudream/common/pkg/distlock/reqbuilder"
  11. log "gitlink.org.cn/cloudream/common/pkg/logger"
  12. mygrpc "gitlink.org.cn/cloudream/common/utils/grpc"
  13. myio "gitlink.org.cn/cloudream/common/utils/io"
  14. serder "gitlink.org.cn/cloudream/common/utils/serder"
  15. "gitlink.org.cn/cloudream/db/model"
  16. agentcaller "gitlink.org.cn/cloudream/proto"
  17. ramsg "gitlink.org.cn/cloudream/rabbitmq/message"
  18. coormsg "gitlink.org.cn/cloudream/rabbitmq/message/coordinator"
  19. "google.golang.org/grpc"
  20. "google.golang.org/grpc/credentials/insecure"
  21. lo "github.com/samber/lo"
  22. )
  23. type ObjectService struct {
  24. *Service
  25. }
  26. func (svc *Service) ObjectSvc() *ObjectService {
  27. return &ObjectService{Service: svc}
  28. }
  29. func (svc *ObjectService) GetObject(userID int, objectID int) (model.Object, error) {
  30. // TODO
  31. panic("not implement yet")
  32. }
  33. func (svc *ObjectService) DownloadObject(userID int, objectID int) (io.ReadCloser, error) {
  34. mutex, err := reqbuilder.NewBuilder().
  35. // 用于判断用户是否有对象权限
  36. Metadata().UserBucket().ReadAny().
  37. // 用于查询可用的下载节点
  38. Node().ReadAny().
  39. // 用于读取文件信息
  40. Object().ReadOne(objectID).
  41. // 用于查询Rep配置
  42. ObjectRep().ReadOne(objectID).
  43. // 用于查询Block配置
  44. ObjectBlock().ReadAny().
  45. // 用于查询包含了副本的节点
  46. Cache().ReadAny().
  47. MutexLock(svc.distlock)
  48. if err != nil {
  49. return nil, fmt.Errorf("acquire locks failed, err: %w", err)
  50. }
  51. preDownloadResp, err := svc.coordinator.PreDownloadObject(coormsg.NewPreDownloadObject(objectID, userID, config.Cfg().ExternalIP))
  52. if err != nil {
  53. mutex.Unlock()
  54. return nil, fmt.Errorf("pre download object: %w", err)
  55. }
  56. switch preDownloadResp.Redundancy {
  57. case consts.REDUNDANCY_REP:
  58. var repInfo ramsg.RespObjectRepInfo
  59. err := serder.MapToObject(preDownloadResp.RedundancyData.(map[string]any), &repInfo)
  60. if err != nil {
  61. mutex.Unlock()
  62. return nil, fmt.Errorf("redundancy data to rep info failed, err: %w", err)
  63. }
  64. if len(repInfo.Nodes) == 0 {
  65. mutex.Unlock()
  66. return nil, fmt.Errorf("no node has this file")
  67. }
  68. // 选择下载节点
  69. entry := svc.chooseDownloadNode(repInfo.Nodes)
  70. // 如果客户端与节点在同一个地域,则使用内网地址连接节点
  71. nodeIP := entry.ExternalIP
  72. if entry.IsSameLocation {
  73. nodeIP = entry.LocalIP
  74. log.Infof("client and node %d are at the same location, use local ip\n", entry.ID)
  75. }
  76. reader, err := svc.downloadRepObject(entry.ID, nodeIP, repInfo.FileHash)
  77. if err != nil {
  78. mutex.Unlock()
  79. return nil, fmt.Errorf("rep read failed, err: %w", err)
  80. }
  81. return myio.AfterReadClosed(reader, func(closer io.ReadCloser) {
  82. // TODO 可以考虑在打开了读取流之后就解锁,而不是要等外部读取完毕
  83. mutex.Unlock()
  84. }), nil
  85. //case consts.REDUNDANCY_EC:
  86. // TODO EC部分的代码要考虑重构
  87. // ecRead(readResp.FileSize, readResp.NodeIPs, readResp.Hashes, readResp.BlockIDs, *readResp.ECName)
  88. }
  89. mutex.Unlock()
  90. return nil, fmt.Errorf("unsupported redundancy type: %s", preDownloadResp.Redundancy)
  91. }
  92. // chooseDownloadNode 选择一个下载节点
  93. // 1. 从与当前客户端相同地域的节点中随机选一个
  94. // 2. 没有用的话从所有节点中随机选一个
  95. func (svc *ObjectService) chooseDownloadNode(entries []ramsg.RespNode) ramsg.RespNode {
  96. sameLocationEntries := lo.Filter(entries, func(e ramsg.RespNode, i int) bool { return e.IsSameLocation })
  97. if len(sameLocationEntries) > 0 {
  98. return sameLocationEntries[rand.Intn(len(sameLocationEntries))]
  99. }
  100. return entries[rand.Intn(len(entries))]
  101. }
  102. func (svc *ObjectService) downloadRepObject(nodeID int, nodeIP string, fileHash string) (io.ReadCloser, error) {
  103. if svc.ipfs != nil {
  104. log.Infof("try to use local IPFS to download file")
  105. reader, err := svc.downloadFromLocalIPFS(fileHash)
  106. if err == nil {
  107. return reader, nil
  108. }
  109. log.Warnf("download from local IPFS failed, so try to download from node %s, err: %s", nodeIP, err.Error())
  110. }
  111. return svc.downloadFromNode(nodeID, nodeIP, fileHash)
  112. }
  113. func (svc *ObjectService) downloadFromNode(nodeID int, nodeIP string, fileHash string) (io.ReadCloser, error) {
  114. // 二次获取锁
  115. mutex, err := reqbuilder.NewBuilder().
  116. // 用于从IPFS下载文件
  117. IPFS().ReadOneRep(nodeID, fileHash).
  118. MutexLock(svc.distlock)
  119. if err != nil {
  120. return nil, fmt.Errorf("acquire locks failed, err: %w", err)
  121. }
  122. // 连接grpc
  123. grpcAddr := fmt.Sprintf("%s:%d", nodeIP, config.Cfg().GRPCPort)
  124. conn, err := grpc.Dial(grpcAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
  125. if err != nil {
  126. return nil, fmt.Errorf("connect to grpc server at %s failed, err: %w", grpcAddr, err)
  127. }
  128. // 下载文件
  129. client := agentcaller.NewFileTransportClient(conn)
  130. reader, err := mygrpc.GetFileAsStream(client, fileHash)
  131. if err != nil {
  132. conn.Close()
  133. return nil, fmt.Errorf("request to get file failed, err: %w", err)
  134. }
  135. reader = myio.AfterReadClosed(reader, func(io.ReadCloser) {
  136. conn.Close()
  137. mutex.Unlock()
  138. })
  139. return reader, nil
  140. }
  141. func (svc *ObjectService) downloadFromLocalIPFS(fileHash string) (io.ReadCloser, error) {
  142. // TODO 这里也可以改成Task
  143. reader, err := svc.ipfs.OpenRead(fileHash)
  144. if err != nil {
  145. return nil, fmt.Errorf("read ipfs file failed, err: %w", err)
  146. }
  147. return reader, nil
  148. }
  149. func (svc *ObjectService) StartUploadingRepObjects(userID int, bucketID int, uploadObjects []task.UploadObject, repCount int) (string, error) {
  150. tsk := svc.taskMgr.StartNew(task.NewUploadRepObject(userID, bucketID, uploadObjects, repCount))
  151. return tsk.ID(), nil
  152. }
  153. func (svc *ObjectService) WaitUploadingRepObjects(taskID string, waitTimeout time.Duration) (bool, []task.UploadRepResult, error) {
  154. tsk := svc.taskMgr.FindByID(taskID)
  155. if tsk.WaitTimeout(waitTimeout) {
  156. return true, tsk.Body().(*task.UploadRepObject).UploadRepResults, tsk.Error()
  157. }
  158. return false, nil, nil
  159. }
  160. func (svc *ObjectService) UploadECObject(userID int, file io.ReadCloser, fileSize int64, ecName string) error {
  161. // TODO
  162. panic("not implement yet")
  163. }
  164. func (svc *ObjectService) StartUpdatingRepObject(userID int, objectID int, file io.ReadCloser, fileSize int64) (string, error) {
  165. tsk := svc.taskMgr.StartNew(task.NewUpdateRepObject(userID, objectID, file, fileSize))
  166. return tsk.ID(), nil
  167. }
  168. func (svc *ObjectService) WaitUpdatingRepObject(taskID string, waitTimeout time.Duration) (bool, error) {
  169. tsk := svc.taskMgr.FindByID(taskID)
  170. if tsk.WaitTimeout(waitTimeout) {
  171. return true, tsk.Error()
  172. }
  173. return false, nil
  174. }
  175. func (svc *ObjectService) DeleteObject(userID int, objectID int) error {
  176. mutex, err := reqbuilder.NewBuilder().
  177. Metadata().
  178. // 用于判断用户是否有对象的权限
  179. UserBucket().ReadAny().
  180. // 用于读取、修改对象信息
  181. Object().WriteOne(objectID).
  182. // 用于删除Rep配置
  183. ObjectRep().WriteOne(objectID).
  184. // 用于删除Block配置
  185. ObjectBlock().WriteAny().
  186. // 用于修改Move此Object的记录的状态
  187. StorageObject().WriteAny().
  188. MutexLock(svc.distlock)
  189. if err != nil {
  190. return fmt.Errorf("acquire locks failed, err: %w", err)
  191. }
  192. defer mutex.Unlock()
  193. _, err = svc.coordinator.DeleteObject(coormsg.NewDeleteObject(userID, objectID))
  194. if err != nil {
  195. return fmt.Errorf("deleting object: %w", err)
  196. }
  197. return nil
  198. }

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