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

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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/pkg/distlock/reqbuilder"
  10. log "gitlink.org.cn/cloudream/common/pkg/logger"
  11. mygrpc "gitlink.org.cn/cloudream/common/utils/grpc"
  12. myio "gitlink.org.cn/cloudream/common/utils/io"
  13. "gitlink.org.cn/cloudream/db/model"
  14. agentcaller "gitlink.org.cn/cloudream/proto"
  15. ramsg "gitlink.org.cn/cloudream/rabbitmq/message"
  16. coormsg "gitlink.org.cn/cloudream/rabbitmq/message/coordinator"
  17. "google.golang.org/grpc"
  18. "google.golang.org/grpc/credentials/insecure"
  19. lo "github.com/samber/lo"
  20. )
  21. type ObjectService struct {
  22. *Service
  23. }
  24. type ResultDownloadObject struct {
  25. ObjectName string
  26. Reader io.ReadCloser
  27. Error error
  28. }
  29. func (svc *Service) ObjectSvc() *ObjectService {
  30. return &ObjectService{Service: svc}
  31. }
  32. func (svc *ObjectService) GetObject(userID int64, objectID int64) (model.Object, error) {
  33. // TODO
  34. panic("not implement yet")
  35. }
  36. func (svc *ObjectService) DownloadObjectDir(userID int64, dirName string) ([]ResultDownloadObject, error) {
  37. mutex, err := reqbuilder.NewBuilder().
  38. // 用于判断用户是否有对象权限
  39. Metadata().UserBucket().ReadAny().
  40. // 用于查询可用的下载节点
  41. Node().ReadAny().
  42. // 用于读取文件信息
  43. Object().ReadAny().
  44. // 用于查询Rep配置
  45. ObjectRep().ReadAny().
  46. // 用于查询Block配置
  47. ObjectBlock().ReadAny().
  48. // 用于查询包含了副本的节点
  49. Cache().ReadAny().
  50. MutexLock(svc.distlock)
  51. if err != nil {
  52. return nil, fmt.Errorf("acquire locks failed, err: %w", err)
  53. }
  54. // TODO 解锁时机需要优化,在所有文件都写入到本地后再解锁
  55. // 当前是所有文件流全部打开,处理完最后全部关闭,可以考虑加一个迭代器,将文件流逐个打开关闭
  56. defer mutex.Unlock()
  57. //根据dirName查询相关的所有文件
  58. objsResp, err := svc.coordinator.GetObjectsByDirName(coormsg.NewGetObjectsByDirName(userID, dirName))
  59. if err != nil {
  60. return nil, fmt.Errorf("get objectID by dirName failed: %w", err)
  61. }
  62. if len(objsResp.Objects) == 0 {
  63. return nil, fmt.Errorf("dirName %v is not exist", dirName)
  64. }
  65. resultDownloadObjects := []ResultDownloadObject{}
  66. for i := 0; i < len(objsResp.Objects); i++ {
  67. reader, err := svc.downloadSingleObject(objsResp.Objects[i].ObjectID, userID)
  68. resultDownloadObjects = append(resultDownloadObjects, ResultDownloadObject{
  69. ObjectName: objsResp.Objects[i].Name,
  70. Reader: reader,
  71. Error: err,
  72. })
  73. }
  74. return resultDownloadObjects, nil
  75. }
  76. func (svc *ObjectService) DownloadObject(userID int64, objectID int64) (io.ReadCloser, error) {
  77. mutex, err := reqbuilder.NewBuilder().
  78. // 用于判断用户是否有对象权限
  79. Metadata().UserBucket().ReadAny().
  80. // 用于查询可用的下载节点
  81. Node().ReadAny().
  82. // 用于读取文件信息
  83. Object().ReadOne(objectID).
  84. // 用于查询Rep配置
  85. ObjectRep().ReadOne(objectID).
  86. // 用于查询Block配置
  87. ObjectBlock().ReadAny().
  88. // 用于查询包含了副本的节点
  89. Cache().ReadAny().
  90. MutexLock(svc.distlock)
  91. if err != nil {
  92. return nil, fmt.Errorf("acquire locks failed, err: %w", err)
  93. }
  94. defer mutex.Unlock()
  95. reader, err := svc.downloadSingleObject(objectID, userID)
  96. // defer myio.AfterReadClosed(reader, func(closer io.ReadCloser) {
  97. // // TODO 可以考虑在打开了读取流之后就解锁,而不是要等外部读取完毕
  98. // mutex.Unlock()
  99. // })
  100. return reader, err
  101. }
  102. func (svc *ObjectService) downloadSingleObject(objectID int64, userID int64) (io.ReadCloser, error) {
  103. preDownloadResp, err := svc.coordinator.PreDownloadObject(coormsg.NewPreDownloadObject(objectID, userID, config.Cfg().ExternalIP))
  104. if err != nil {
  105. return nil, fmt.Errorf("pre download object: %w", err)
  106. }
  107. switch redundancy := preDownloadResp.Redundancy.(type) {
  108. case ramsg.RespRepRedundancyData:
  109. if len(redundancy.Nodes) == 0 {
  110. return nil, fmt.Errorf("no node has this file")
  111. }
  112. // 选择下载节点
  113. entry := svc.chooseDownloadNode(redundancy.Nodes)
  114. // 如果客户端与节点在同一个地域,则使用内网地址连接节点
  115. nodeIP := entry.ExternalIP
  116. if entry.IsSameLocation {
  117. nodeIP = entry.LocalIP
  118. log.Infof("client and node %d are at the same location, use local ip\n", entry.ID)
  119. }
  120. reader, err := svc.downloadRepObject(entry.ID, nodeIP, redundancy.FileHash)
  121. if err != nil {
  122. return nil, fmt.Errorf("rep read failed, err: %w", err)
  123. }
  124. return reader, nil
  125. //case consts.REDUNDANCY_EC:
  126. // TODO EC部分的代码要考虑重构
  127. // ecRead(readResp.FileSize, readResp.NodeIPs, readResp.Hashes, readResp.BlockIDs, *readResp.ECName)
  128. }
  129. return nil, fmt.Errorf("unsupported redundancy type: %s", preDownloadResp.Redundancy)
  130. }
  131. // chooseDownloadNode 选择一个下载节点
  132. // 1. 从与当前客户端相同地域的节点中随机选一个
  133. // 2. 没有用的话从所有节点中随机选一个
  134. func (svc *ObjectService) chooseDownloadNode(entries []ramsg.RespNode) ramsg.RespNode {
  135. sameLocationEntries := lo.Filter(entries, func(e ramsg.RespNode, i int) bool { return e.IsSameLocation })
  136. if len(sameLocationEntries) > 0 {
  137. return sameLocationEntries[rand.Intn(len(sameLocationEntries))]
  138. }
  139. return entries[rand.Intn(len(entries))]
  140. }
  141. func (svc *ObjectService) downloadRepObject(nodeID int64, nodeIP string, fileHash string) (io.ReadCloser, error) {
  142. if svc.ipfs != nil {
  143. log.Infof("try to use local IPFS to download file")
  144. reader, err := svc.downloadFromLocalIPFS(fileHash)
  145. if err == nil {
  146. return reader, nil
  147. }
  148. log.Warnf("download from local IPFS failed, so try to download from node %s, err: %s", nodeIP, err.Error())
  149. }
  150. return svc.downloadFromNode(nodeID, nodeIP, fileHash)
  151. }
  152. func (svc *ObjectService) downloadFromNode(nodeID int64, nodeIP string, fileHash string) (io.ReadCloser, error) {
  153. // 二次获取锁
  154. mutex, err := reqbuilder.NewBuilder().
  155. // 用于从IPFS下载文件
  156. IPFS().ReadOneRep(nodeID, fileHash).
  157. MutexLock(svc.distlock)
  158. if err != nil {
  159. return nil, fmt.Errorf("acquire locks failed, err: %w", err)
  160. }
  161. // 连接grpc
  162. grpcAddr := fmt.Sprintf("%s:%d", nodeIP, config.Cfg().GRPCPort)
  163. conn, err := grpc.Dial(grpcAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
  164. if err != nil {
  165. return nil, fmt.Errorf("connect to grpc server at %s failed, err: %w", grpcAddr, err)
  166. }
  167. // 下载文件
  168. client := agentcaller.NewFileTransportClient(conn)
  169. reader, err := mygrpc.GetFileAsStream(client, fileHash)
  170. if err != nil {
  171. conn.Close()
  172. return nil, fmt.Errorf("request to get file failed, err: %w", err)
  173. }
  174. reader = myio.AfterReadClosed(reader, func(io.ReadCloser) {
  175. conn.Close()
  176. mutex.Unlock()
  177. })
  178. return reader, nil
  179. }
  180. func (svc *ObjectService) downloadFromLocalIPFS(fileHash string) (io.ReadCloser, error) {
  181. reader, err := svc.ipfs.OpenRead(fileHash)
  182. if err != nil {
  183. return nil, fmt.Errorf("read ipfs file failed, err: %w", err)
  184. }
  185. return reader, nil
  186. }
  187. func (svc *ObjectService) StartUploadingRepObjects(userID int64, bucketID int64, uploadObjects []task.UploadObject, repCount int) (string, error) {
  188. tsk := svc.taskMgr.StartNew(task.NewUploadRepObjects(userID, bucketID, uploadObjects, repCount))
  189. return tsk.ID(), nil
  190. }
  191. func (svc *ObjectService) WaitUploadingRepObjects(taskID string, waitTimeout time.Duration) (bool, task.UploadRepObjectsResult, error) {
  192. tsk := svc.taskMgr.FindByID(taskID)
  193. if tsk.WaitTimeout(waitTimeout) {
  194. uploadTask := tsk.Body().(*task.UploadRepObjects)
  195. uploadObjectResult := task.UploadRepObjectsResult{
  196. Objects: uploadTask.Objects,
  197. Results: uploadTask.Results,
  198. IsUploading: uploadTask.IsUploading,
  199. }
  200. return true, uploadObjectResult, tsk.Error()
  201. }
  202. return false, task.UploadRepObjectsResult{}, nil
  203. }
  204. func (svc *ObjectService) UploadECObject(userID int64, file io.ReadCloser, fileSize int64, ecName string) error {
  205. // TODO
  206. panic("not implement yet")
  207. }
  208. func (svc *ObjectService) StartUpdatingRepObject(userID int64, objectID int64, file io.ReadCloser, fileSize int64) (string, error) {
  209. tsk := svc.taskMgr.StartNew(task.NewUpdateRepObject(userID, objectID, file, fileSize))
  210. return tsk.ID(), nil
  211. }
  212. func (svc *ObjectService) WaitUpdatingRepObject(taskID string, waitTimeout time.Duration) (bool, error) {
  213. tsk := svc.taskMgr.FindByID(taskID)
  214. if tsk.WaitTimeout(waitTimeout) {
  215. return true, tsk.Error()
  216. }
  217. return false, nil
  218. }
  219. func (svc *ObjectService) DeleteObject(userID int64, objectID int64) error {
  220. mutex, err := reqbuilder.NewBuilder().
  221. Metadata().
  222. // 用于判断用户是否有对象的权限
  223. UserBucket().ReadAny().
  224. // 用于读取、修改对象信息
  225. Object().WriteOne(objectID).
  226. // 用于删除Rep配置
  227. ObjectRep().WriteOne(objectID).
  228. // 用于删除Block配置
  229. ObjectBlock().WriteAny().
  230. // 用于修改Move此Object的记录的状态
  231. StorageObject().WriteAny().
  232. MutexLock(svc.distlock)
  233. if err != nil {
  234. return fmt.Errorf("acquire locks failed, err: %w", err)
  235. }
  236. defer mutex.Unlock()
  237. _, err = svc.coordinator.DeleteObject(coormsg.NewDeleteObject(userID, objectID))
  238. if err != nil {
  239. return fmt.Errorf("deleting object: %w", err)
  240. }
  241. return nil
  242. }

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