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 13 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
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. package services
  2. import (
  3. "fmt"
  4. "io"
  5. "math/rand"
  6. "gitlink.org.cn/cloudream/client/internal/config"
  7. "gitlink.org.cn/cloudream/common/consts"
  8. log "gitlink.org.cn/cloudream/common/pkg/logger"
  9. mygrpc "gitlink.org.cn/cloudream/common/utils/grpc"
  10. myio "gitlink.org.cn/cloudream/common/utils/io"
  11. serder "gitlink.org.cn/cloudream/common/utils/serder"
  12. mysort "gitlink.org.cn/cloudream/common/utils/sort"
  13. "gitlink.org.cn/cloudream/db/model"
  14. agentcaller "gitlink.org.cn/cloudream/proto"
  15. agtcli "gitlink.org.cn/cloudream/rabbitmq/client/agent"
  16. ramsg "gitlink.org.cn/cloudream/rabbitmq/message"
  17. agtmsg "gitlink.org.cn/cloudream/rabbitmq/message/agent"
  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. preDownloadResp, err := svc.coordinator.PreDownloadObject(coormsg.NewPreDownloadObjectBody(objectID, userID, config.Cfg().ExternalIP))
  35. if err != nil {
  36. return nil, fmt.Errorf("request to coordinator failed, err: %w", err)
  37. }
  38. if preDownloadResp.IsFailed() {
  39. return nil, fmt.Errorf("coordinator operation failed, code: %s, message: %s", preDownloadResp.ErrorCode, preDownloadResp.ErrorMessage)
  40. }
  41. switch preDownloadResp.Body.Redundancy {
  42. case consts.REDUNDANCY_REP:
  43. var repInfo ramsg.RespObjectRepInfo
  44. err := serder.MapToObject(preDownloadResp.Body.RedundancyData.(map[string]any), &repInfo)
  45. if err != nil {
  46. return nil, fmt.Errorf("redundancy data to rep info failed, err: %w", err)
  47. }
  48. if len(repInfo.Nodes) == 0 {
  49. return nil, fmt.Errorf("no node has this file")
  50. }
  51. // 选择下载节点
  52. entry := svc.chooseDownloadNode(repInfo.Nodes)
  53. // 如果客户端与节点在同一个地域,则使用内网地址连接节点
  54. nodeIP := entry.ExternalIP
  55. if entry.IsSameLocation {
  56. nodeIP = entry.LocalIP
  57. log.Infof("client and node %d are at the same location, use local ip\n", entry.ID)
  58. }
  59. reader, err := svc.downloadRepObject(nodeIP, repInfo.FileHash)
  60. if err != nil {
  61. return nil, fmt.Errorf("rep read failed, err: %w", err)
  62. }
  63. return reader, nil
  64. //case consts.REDUNDANCY_EC:
  65. // TODO EC部分的代码要考虑重构
  66. // ecRead(readResp.FileSize, readResp.NodeIPs, readResp.Hashes, readResp.BlockIDs, *readResp.ECName)
  67. }
  68. return nil, fmt.Errorf("unsupported redundancy type: %s", preDownloadResp.Body.Redundancy)
  69. }
  70. // chooseDownloadNode 选择一个下载节点
  71. // 1. 从与当前客户端相同地域的节点中随机选一个
  72. // 2. 没有用的话从所有节点中随机选一个
  73. func (svc *ObjectService) chooseDownloadNode(entries []ramsg.RespNode) ramsg.RespNode {
  74. sameLocationEntries := lo.Filter(entries, func(e ramsg.RespNode, i int) bool { return e.IsSameLocation })
  75. if len(sameLocationEntries) > 0 {
  76. return sameLocationEntries[rand.Intn(len(sameLocationEntries))]
  77. }
  78. return entries[rand.Intn(len(entries))]
  79. }
  80. func (svc *ObjectService) downloadRepObject(nodeIP string, fileHash string) (io.ReadCloser, error) {
  81. if svc.ipfs != nil {
  82. log.Infof("try to use local IPFS to download file")
  83. reader, err := svc.downloadFromLocalIPFS(fileHash)
  84. if err == nil {
  85. return reader, nil
  86. }
  87. log.Warnf("download from local IPFS failed, so try to download from node %s, err: %s", nodeIP, err.Error())
  88. }
  89. return svc.downloadFromNode(nodeIP, fileHash)
  90. }
  91. func (svc *ObjectService) downloadFromNode(nodeIP string, fileHash string) (io.ReadCloser, error) {
  92. // 连接grpc
  93. grpcAddr := fmt.Sprintf("%s:%d", nodeIP, config.Cfg().GRPCPort)
  94. conn, err := grpc.Dial(grpcAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
  95. if err != nil {
  96. return nil, fmt.Errorf("connect to grpc server at %s failed, err: %w", grpcAddr, err)
  97. }
  98. // 下载文件
  99. client := agentcaller.NewFileTransportClient(conn)
  100. reader, err := mygrpc.GetFileAsStream(client, fileHash)
  101. if err != nil {
  102. conn.Close()
  103. return nil, fmt.Errorf("request to get file failed, err: %w", err)
  104. }
  105. reader = myio.AfterReadClosed(reader, func(io.ReadCloser) { conn.Close() })
  106. return reader, nil
  107. }
  108. func (svc *ObjectService) downloadFromLocalIPFS(fileHash string) (io.ReadCloser, error) {
  109. // TODO 这里也可以改成Task
  110. reader, err := svc.ipfs.OpenRead(fileHash)
  111. if err != nil {
  112. return nil, fmt.Errorf("read ipfs file failed, err: %w", err)
  113. }
  114. return reader, nil
  115. }
  116. func (svc *ObjectService) UploadRepObject(userID int, bucketID int, objectName string, file io.ReadCloser, fileSize int64, repCount int) error {
  117. //发送写请求,请求Coor分配写入节点Ip
  118. repWriteResp, err := svc.coordinator.PreUploadRepObject(coormsg.NewPreUploadRepObjectBody(bucketID, objectName, fileSize, userID, config.Cfg().ExternalIP))
  119. if err != nil {
  120. return fmt.Errorf("request to coordinator failed, err: %w", err)
  121. }
  122. if repWriteResp.IsFailed() {
  123. return fmt.Errorf("coordinator RepWrite failed, code: %s, message: %s", repWriteResp.ErrorCode, repWriteResp.ErrorMessage)
  124. }
  125. if len(repWriteResp.Body.Nodes) == 0 {
  126. return fmt.Errorf("no node to upload file")
  127. }
  128. uploadNode := svc.chooseUploadNode(repWriteResp.Body.Nodes)
  129. var fileHash string
  130. uploadedNodeIDs := []int{}
  131. uploadToNode := true
  132. // 本地有IPFS,则直接从本地IPFS上传
  133. if svc.ipfs != nil {
  134. log.Infof("try to use local IPFS to upload file")
  135. fileHash, err = svc.uploadToLocalIPFS(file, uploadNode.ID)
  136. if err != nil {
  137. log.Warnf("upload to local IPFS failed, so try to upload to node %d, err: %s", uploadNode.ID, err.Error())
  138. } else {
  139. uploadToNode = false
  140. }
  141. }
  142. // 否则发送到agent上传
  143. if uploadToNode {
  144. // 如果客户端与节点在同一个地域,则使用内网地址连接节点
  145. nodeIP := uploadNode.ExternalIP
  146. if uploadNode.IsSameLocation {
  147. nodeIP = uploadNode.LocalIP
  148. log.Infof("client and node %d are at the same location, use local ip\n", uploadNode.ID)
  149. }
  150. fileHash, err = svc.uploadToNode(file, nodeIP)
  151. if err != nil {
  152. return fmt.Errorf("upload to node %s failed, err: %w", nodeIP, err)
  153. }
  154. uploadedNodeIDs = append(uploadedNodeIDs, uploadNode.ID)
  155. }
  156. // 记录写入的文件的Hash
  157. createObjectResp, err := svc.coordinator.CreateRepObject(coormsg.NewCreateRepObjectBody(bucketID, objectName, fileSize, repCount, userID, uploadedNodeIDs, fileHash))
  158. if err != nil {
  159. return fmt.Errorf("request to coordinator failed, err: %w", err)
  160. }
  161. if createObjectResp.IsFailed() {
  162. return fmt.Errorf("coordinator CreateRepObject failed, code: %s, message: %s", createObjectResp.ErrorCode, createObjectResp.ErrorMessage)
  163. }
  164. return nil
  165. }
  166. func (svc *ObjectService) uploadToNode(file io.ReadCloser, nodeIP string) (string, error) {
  167. // 建立grpc连接,发送请求
  168. grpcAddr := fmt.Sprintf("%s:%d", nodeIP, config.Cfg().GRPCPort)
  169. grpcCon, err := grpc.Dial(grpcAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
  170. if err != nil {
  171. return "", fmt.Errorf("connect to grpc server at %s failed, err: %w", grpcAddr, err)
  172. }
  173. defer grpcCon.Close()
  174. client := agentcaller.NewFileTransportClient(grpcCon)
  175. upload, err := mygrpc.SendFileAsStream(client)
  176. if err != nil {
  177. return "", fmt.Errorf("request to send file failed, err: %w", err)
  178. }
  179. // 发送文件数据
  180. _, err = io.Copy(upload, file)
  181. if err != nil {
  182. // 发生错误则关闭连接
  183. upload.Abort(io.ErrClosedPipe)
  184. return "", fmt.Errorf("copy file date to upload stream failed, err: %w", err)
  185. }
  186. // 发送EOF消息,并获得FileHash
  187. fileHash, err := upload.Finish()
  188. if err != nil {
  189. upload.Abort(io.ErrClosedPipe)
  190. return "", fmt.Errorf("send EOF failed, err: %w", err)
  191. }
  192. return fileHash, nil
  193. }
  194. func (svc *ObjectService) uploadToLocalIPFS(file io.ReadCloser, nodeID int) (string, error) {
  195. // 从本地IPFS上传文件
  196. writer, err := svc.ipfs.CreateFile()
  197. if err != nil {
  198. return "", fmt.Errorf("create IPFS file failed, err: %w", err)
  199. }
  200. _, err = io.Copy(writer, file)
  201. if err != nil {
  202. return "", fmt.Errorf("copy file data to IPFS failed, err: %w", err)
  203. }
  204. fileHash, err := writer.Finish()
  205. if err != nil {
  206. return "", fmt.Errorf("finish writing IPFS failed, err: %w", err)
  207. }
  208. // 然后让最近节点pin本地上传的文件
  209. agentClient, err := agtcli.NewClient(nodeID, &config.Cfg().RabbitMQ)
  210. if err != nil {
  211. return "", fmt.Errorf("create agent client to %d failed, err: %w", nodeID, err)
  212. }
  213. defer agentClient.Close()
  214. pinObjResp, err := agentClient.PinObject(agtmsg.NewPinObjectBody(fileHash))
  215. if err != nil {
  216. return "", fmt.Errorf("request to agent %d failed, err: %w", nodeID, err)
  217. }
  218. if pinObjResp.IsFailed() {
  219. return "", fmt.Errorf("agent %d PinObject failed, code: %s, message: %s", nodeID, pinObjResp.ErrorCode, pinObjResp.ErrorMessage)
  220. }
  221. return fileHash, nil
  222. }
  223. // chooseUploadNode 选择一个上传文件的节点
  224. // 1. 从与当前客户端相同地域的节点中随机选一个
  225. // 2. 没有用的话从所有节点中随机选一个
  226. func (svc *ObjectService) chooseUploadNode(nodes []ramsg.RespNode) ramsg.RespNode {
  227. sameLocationNodes := lo.Filter(nodes, func(e ramsg.RespNode, i int) bool { return e.IsSameLocation })
  228. if len(sameLocationNodes) > 0 {
  229. return sameLocationNodes[rand.Intn(len(sameLocationNodes))]
  230. }
  231. return nodes[rand.Intn(len(nodes))]
  232. }
  233. func (svc *ObjectService) UploadECObject(userID int, file io.ReadCloser, fileSize int64, ecName string) error {
  234. // TODO
  235. panic("not implement yet")
  236. }
  237. func (svc *ObjectService) UpdateRepObject(userID int, objectID int, file io.ReadCloser, fileSize int64) error {
  238. preResp, err := svc.coordinator.PreUpdateRepObject(coormsg.NewPreUpdateRepObjectBody(
  239. objectID,
  240. fileSize,
  241. userID,
  242. config.Cfg().ExternalIP,
  243. ))
  244. if err != nil {
  245. return fmt.Errorf("request to coordinator failed, err: %w", err)
  246. }
  247. if preResp.IsFailed() {
  248. return fmt.Errorf("coordinator PreUpdateRepObject failed, code: %s, message: %s", preResp.ErrorCode, preResp.ErrorMessage)
  249. }
  250. if len(preResp.Body.Nodes) == 0 {
  251. return fmt.Errorf("no node to upload file")
  252. }
  253. // 上传文件的方式优先级:
  254. // 1. 本地IPFS
  255. // 2. 包含了旧文件,且与客户端在同地域的节点
  256. // 3. 不在同地域,但包含了旧文件的节点
  257. // 4. 同地域节点
  258. uploadNode := svc.chooseUpdateRepObjectNode(preResp.Body.Nodes)
  259. var fileHash string
  260. uploadedNodeIDs := []int{}
  261. uploadToNode := true
  262. // 本地有IPFS,则直接从本地IPFS上传
  263. if svc.ipfs != nil {
  264. log.Infof("try to use local IPFS to upload file")
  265. fileHash, err = svc.uploadToLocalIPFS(file, uploadNode.ID)
  266. if err != nil {
  267. log.Warnf("upload to local IPFS failed, so try to upload to node %d, err: %s", uploadNode.ID, err.Error())
  268. } else {
  269. uploadToNode = false
  270. }
  271. }
  272. // 否则发送到agent上传
  273. if uploadToNode {
  274. // 如果客户端与节点在同一个地域,则使用内网地址连接节点
  275. nodeIP := uploadNode.ExternalIP
  276. if uploadNode.IsSameLocation {
  277. nodeIP = uploadNode.LocalIP
  278. log.Infof("client and node %d are at the same location, use local ip\n", uploadNode.ID)
  279. }
  280. fileHash, err = svc.uploadToNode(file, nodeIP)
  281. if err != nil {
  282. return fmt.Errorf("upload to node %s failed, err: %w", nodeIP, err)
  283. }
  284. uploadedNodeIDs = append(uploadedNodeIDs, uploadNode.ID)
  285. }
  286. // 更新Object
  287. updateResp, err := svc.coordinator.UpdateRepObject(coormsg.NewUpdateRepObjectBody(objectID, fileHash, fileSize, uploadedNodeIDs, userID))
  288. if err != nil {
  289. return fmt.Errorf("request to coordinator failed, err: %w", err)
  290. }
  291. if updateResp.IsFailed() {
  292. return fmt.Errorf("coordinator UpdateRepObject failed, code: %s, message: %s", updateResp.ErrorCode, updateResp.ErrorMessage)
  293. }
  294. return nil
  295. }
  296. func (svc *ObjectService) chooseUpdateRepObjectNode(nodes []coormsg.PreUpdateRepObjectRespNode) coormsg.PreUpdateRepObjectRespNode {
  297. mysort.Sort(nodes, func(left, right coormsg.PreUpdateRepObjectRespNode) int {
  298. v := -mysort.CmpBool(left.HasOldObject, right.HasOldObject)
  299. if v != 0 {
  300. return v
  301. }
  302. return -mysort.CmpBool(left.IsSameLocation, right.IsSameLocation)
  303. })
  304. return nodes[0]
  305. }
  306. func (svc *ObjectService) DeleteObject(userID int, objectID int) error {
  307. resp, err := svc.coordinator.DeleteObject(coormsg.NewDeleteObjectBody(userID, objectID))
  308. if err != nil {
  309. return fmt.Errorf("request to coordinator failed, err: %w", err)
  310. }
  311. if resp.IsFailed() {
  312. return fmt.Errorf("create bucket objects failed, code: %s, message: %s", resp.ErrorCode, resp.ErrorMessage)
  313. }
  314. return nil
  315. }

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