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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. mygrpc "gitlink.org.cn/cloudream/common/utils/grpc"
  9. myio "gitlink.org.cn/cloudream/common/utils/io"
  10. log "gitlink.org.cn/cloudream/common/utils/logger"
  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 ObjectSvc(svc *Service) *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. reader, err := svc.ipfs.OpenRead(fileHash)
  110. if err != nil {
  111. return nil, fmt.Errorf("read ipfs file failed, err: %w", err)
  112. }
  113. return reader, nil
  114. }
  115. func (svc *ObjectService) UploadRepObject(userID int, bucketID int, objectName string, file io.ReadCloser, fileSize int64, repCount int) error {
  116. //发送写请求,请求Coor分配写入节点Ip
  117. repWriteResp, err := svc.coordinator.PreUploadRepObject(coormsg.NewPreUploadRepObjectBody(bucketID, objectName, fileSize, userID, config.Cfg().ExternalIP))
  118. if err != nil {
  119. return fmt.Errorf("request to coordinator failed, err: %w", err)
  120. }
  121. if repWriteResp.IsFailed() {
  122. return fmt.Errorf("coordinator RepWrite failed, code: %s, message: %s", repWriteResp.ErrorCode, repWriteResp.ErrorMessage)
  123. }
  124. if len(repWriteResp.Body.Nodes) == 0 {
  125. return fmt.Errorf("no node to upload file")
  126. }
  127. uploadNode := svc.chooseUploadNode(repWriteResp.Body.Nodes)
  128. var fileHash string
  129. uploadedNodeIDs := []int{}
  130. uploadToNode := true
  131. // 本地有IPFS,则直接从本地IPFS上传
  132. if svc.ipfs != nil {
  133. log.Infof("try to use local IPFS to upload file")
  134. fileHash, err = svc.uploadToLocalIPFS(file, uploadNode.ID)
  135. if err != nil {
  136. log.Warnf("upload to local IPFS failed, so try to upload to node %d, err: %s", uploadNode.ID, err.Error())
  137. } else {
  138. uploadToNode = false
  139. }
  140. }
  141. // 否则发送到agent上传
  142. if uploadToNode {
  143. // 如果客户端与节点在同一个地域,则使用内网地址连接节点
  144. nodeIP := uploadNode.ExternalIP
  145. if uploadNode.IsSameLocation {
  146. nodeIP = uploadNode.LocalIP
  147. log.Infof("client and node %d are at the same location, use local ip\n", uploadNode.ID)
  148. }
  149. fileHash, err = svc.uploadToNode(file, nodeIP)
  150. if err != nil {
  151. return fmt.Errorf("upload to node %s failed, err: %w", nodeIP, err)
  152. }
  153. uploadedNodeIDs = append(uploadedNodeIDs, uploadNode.ID)
  154. }
  155. // 记录写入的文件的Hash
  156. createObjectResp, err := svc.coordinator.CreateRepObject(coormsg.NewCreateRepObjectBody(bucketID, objectName, fileSize, repCount, userID, uploadedNodeIDs, fileHash))
  157. if err != nil {
  158. return fmt.Errorf("request to coordinator failed, err: %w", err)
  159. }
  160. if createObjectResp.IsFailed() {
  161. return fmt.Errorf("coordinator CreateRepObject failed, code: %s, message: %s", createObjectResp.ErrorCode, createObjectResp.ErrorMessage)
  162. }
  163. return nil
  164. }
  165. func (svc *ObjectService) uploadToNode(file io.ReadCloser, nodeIP string) (string, error) {
  166. // 建立grpc连接,发送请求
  167. grpcAddr := fmt.Sprintf("%s:%d", nodeIP, config.Cfg().GRPCPort)
  168. grpcCon, err := grpc.Dial(grpcAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
  169. if err != nil {
  170. return "", fmt.Errorf("connect to grpc server at %s failed, err: %w", grpcAddr, err)
  171. }
  172. defer grpcCon.Close()
  173. client := agentcaller.NewFileTransportClient(grpcCon)
  174. upload, err := mygrpc.SendFileAsStream(client)
  175. if err != nil {
  176. return "", fmt.Errorf("request to send file failed, err: %w", err)
  177. }
  178. // 发送文件数据
  179. _, err = io.Copy(upload, file)
  180. if err != nil {
  181. // 发生错误则关闭连接
  182. upload.Abort(io.ErrClosedPipe)
  183. return "", fmt.Errorf("copy file date to upload stream failed, err: %w", err)
  184. }
  185. // 发送EOF消息,并获得FileHash
  186. fileHash, err := upload.Finish()
  187. if err != nil {
  188. upload.Abort(io.ErrClosedPipe)
  189. return "", fmt.Errorf("send EOF failed, err: %w", err)
  190. }
  191. return fileHash, nil
  192. }
  193. func (svc *ObjectService) uploadToLocalIPFS(file io.ReadCloser, nodeID int) (string, error) {
  194. // 从本地IPFS上传文件
  195. writer, err := svc.ipfs.CreateFile()
  196. if err != nil {
  197. return "", fmt.Errorf("create IPFS file failed, err: %w", err)
  198. }
  199. _, err = io.Copy(writer, file)
  200. if err != nil {
  201. return "", fmt.Errorf("copy file data to IPFS failed, err: %w", err)
  202. }
  203. fileHash, err := writer.Finish()
  204. if err != nil {
  205. return "", fmt.Errorf("finish writing IPFS failed, err: %w", err)
  206. }
  207. // 然后让最近节点pin本地上传的文件
  208. agentClient, err := agtcli.NewAgentClient(nodeID, &config.Cfg().RabbitMQ)
  209. if err != nil {
  210. return "", fmt.Errorf("create agent client to %d failed, err: %w", nodeID, err)
  211. }
  212. defer agentClient.Close()
  213. pinObjResp, err := agentClient.PinObject(agtmsg.NewPinObjectBody(fileHash))
  214. if err != nil {
  215. return "", fmt.Errorf("request to agent %d failed, err: %w", nodeID, err)
  216. }
  217. if pinObjResp.IsFailed() {
  218. return "", fmt.Errorf("agent %d PinObject failed, code: %s, message: %s", nodeID, pinObjResp.ErrorCode, pinObjResp.ErrorMessage)
  219. }
  220. return fileHash, nil
  221. }
  222. // chooseUploadNode 选择一个上传文件的节点
  223. // 1. 从与当前客户端相同地域的节点中随机选一个
  224. // 2. 没有用的话从所有节点中随机选一个
  225. func (svc *ObjectService) chooseUploadNode(nodes []ramsg.RespNode) ramsg.RespNode {
  226. sameLocationNodes := lo.Filter(nodes, func(e ramsg.RespNode, i int) bool { return e.IsSameLocation })
  227. if len(sameLocationNodes) > 0 {
  228. return sameLocationNodes[rand.Intn(len(sameLocationNodes))]
  229. }
  230. return nodes[rand.Intn(len(nodes))]
  231. }
  232. func (svc *ObjectService) UploadECObject(userID int, file io.ReadCloser, fileSize int64, ecName string) error {
  233. // TODO
  234. panic("not implement yet")
  235. }
  236. func (svc *ObjectService) UpdateRepObject(userID int, objectID int, file io.ReadCloser, fileSize int64) error {
  237. preResp, err := svc.coordinator.PreUpdateRepObject(coormsg.NewPreUpdateRepObjectBody(
  238. objectID,
  239. fileSize,
  240. userID,
  241. config.Cfg().ExternalIP,
  242. ))
  243. if err != nil {
  244. return fmt.Errorf("request to coordinator failed, err: %w", err)
  245. }
  246. if preResp.IsFailed() {
  247. return fmt.Errorf("coordinator PreUpdateRepObject failed, code: %s, message: %s", preResp.ErrorCode, preResp.ErrorMessage)
  248. }
  249. if len(preResp.Body.Nodes) == 0 {
  250. return fmt.Errorf("no node to upload file")
  251. }
  252. // 上传文件的方式优先级:
  253. // 1. 本地IPFS
  254. // 2. 包含了旧文件,且与客户端在同地域的节点
  255. // 3. 不在同地域,但包含了旧文件的节点
  256. // 4. 同地域节点
  257. uploadNode := svc.chooseUpdateRepObjectNode(preResp.Body.Nodes)
  258. var fileHash string
  259. uploadedNodeIDs := []int{}
  260. uploadToNode := true
  261. // 本地有IPFS,则直接从本地IPFS上传
  262. if svc.ipfs != nil {
  263. log.Infof("try to use local IPFS to upload file")
  264. fileHash, err = svc.uploadToLocalIPFS(file, uploadNode.ID)
  265. if err != nil {
  266. log.Warnf("upload to local IPFS failed, so try to upload to node %d, err: %s", uploadNode.ID, err.Error())
  267. } else {
  268. uploadToNode = false
  269. }
  270. }
  271. // 否则发送到agent上传
  272. if uploadToNode {
  273. // 如果客户端与节点在同一个地域,则使用内网地址连接节点
  274. nodeIP := uploadNode.ExternalIP
  275. if uploadNode.IsSameLocation {
  276. nodeIP = uploadNode.LocalIP
  277. log.Infof("client and node %d are at the same location, use local ip\n", uploadNode.ID)
  278. }
  279. fileHash, err = svc.uploadToNode(file, nodeIP)
  280. if err != nil {
  281. return fmt.Errorf("upload to node %s failed, err: %w", nodeIP, err)
  282. }
  283. uploadedNodeIDs = append(uploadedNodeIDs, uploadNode.ID)
  284. }
  285. // 更新Object
  286. updateResp, err := svc.coordinator.UpdateRepObject(coormsg.NewUpdateRepObjectBody(objectID, fileHash, fileSize, uploadedNodeIDs, userID))
  287. if err != nil {
  288. return fmt.Errorf("request to coordinator failed, err: %w", err)
  289. }
  290. if updateResp.IsFailed() {
  291. return fmt.Errorf("coordinator UpdateRepObject failed, code: %s, message: %s", updateResp.ErrorCode, updateResp.ErrorMessage)
  292. }
  293. return nil
  294. }
  295. func (svc *ObjectService) chooseUpdateRepObjectNode(nodes []coormsg.PreUpdateRepObjectRespNode) coormsg.PreUpdateRepObjectRespNode {
  296. mysort.Sort(nodes, func(left, right coormsg.PreUpdateRepObjectRespNode) int {
  297. v := -mysort.CmpBool(left.HasOldObject, right.HasOldObject)
  298. if v != 0 {
  299. return v
  300. }
  301. return -mysort.CmpBool(left.IsSameLocation, right.IsSameLocation)
  302. })
  303. return nodes[0]
  304. }
  305. func (svc *ObjectService) DeleteObject(userID int, objectID int) error {
  306. resp, err := svc.coordinator.DeleteObject(coormsg.NewDeleteObjectBody(userID, objectID))
  307. if err != nil {
  308. return fmt.Errorf("request to coordinator failed, err: %w", err)
  309. }
  310. if resp.IsFailed() {
  311. return fmt.Errorf("create bucket objects failed, code: %s, message: %s", resp.ErrorCode, resp.ErrorMessage)
  312. }
  313. return nil
  314. }

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