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.

upload_objects.go 8.3 kB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. package cmd
  2. import (
  3. "fmt"
  4. "io"
  5. "math"
  6. "math/rand"
  7. "time"
  8. "github.com/samber/lo"
  9. "gitlink.org.cn/cloudream/common/pkgs/distlock"
  10. "gitlink.org.cn/cloudream/common/pkgs/logger"
  11. cdssdk "gitlink.org.cn/cloudream/common/sdks/storage"
  12. "gitlink.org.cn/cloudream/common/utils/sort2"
  13. stgglb "gitlink.org.cn/cloudream/storage/common/globals"
  14. "gitlink.org.cn/cloudream/storage/common/pkgs/connectivity"
  15. "gitlink.org.cn/cloudream/storage/common/pkgs/distlock/reqbuilder"
  16. "gitlink.org.cn/cloudream/storage/common/pkgs/iterator"
  17. agtmq "gitlink.org.cn/cloudream/storage/common/pkgs/mq/agent"
  18. coormq "gitlink.org.cn/cloudream/storage/common/pkgs/mq/coordinator"
  19. )
  20. type UploadObjects struct {
  21. userID cdssdk.UserID
  22. packageID cdssdk.PackageID
  23. objectIter iterator.UploadingObjectIterator
  24. nodeAffinity *cdssdk.NodeID
  25. }
  26. type UploadObjectsResult struct {
  27. Objects []ObjectUploadResult
  28. }
  29. type ObjectUploadResult struct {
  30. Info *iterator.IterUploadingObject
  31. Error error
  32. Object cdssdk.Object
  33. }
  34. type UploadNodeInfo struct {
  35. Node cdssdk.Node
  36. Delay time.Duration
  37. IsSameLocation bool
  38. }
  39. type UploadObjectsContext struct {
  40. Distlock *distlock.Service
  41. Connectivity *connectivity.Collector
  42. }
  43. func NewUploadObjects(userID cdssdk.UserID, packageID cdssdk.PackageID, objIter iterator.UploadingObjectIterator, nodeAffinity *cdssdk.NodeID) *UploadObjects {
  44. return &UploadObjects{
  45. userID: userID,
  46. packageID: packageID,
  47. objectIter: objIter,
  48. nodeAffinity: nodeAffinity,
  49. }
  50. }
  51. func (t *UploadObjects) Execute(ctx *UploadObjectsContext) (*UploadObjectsResult, error) {
  52. defer t.objectIter.Close()
  53. coorCli, err := stgglb.CoordinatorMQPool.Acquire()
  54. if err != nil {
  55. return nil, fmt.Errorf("new coordinator client: %w", err)
  56. }
  57. getUserNodesResp, err := coorCli.GetUserNodes(coormq.NewGetUserNodes(t.userID))
  58. if err != nil {
  59. return nil, fmt.Errorf("getting user nodes: %w", err)
  60. }
  61. cons := ctx.Connectivity.GetAll()
  62. userNodes := lo.Map(getUserNodesResp.Nodes, func(node cdssdk.Node, index int) UploadNodeInfo {
  63. delay := time.Duration(math.MaxInt64)
  64. con, ok := cons[node.NodeID]
  65. if ok && con.Delay != nil {
  66. delay = *con.Delay
  67. }
  68. return UploadNodeInfo{
  69. Node: node,
  70. Delay: delay,
  71. IsSameLocation: node.LocationID == stgglb.Local.LocationID,
  72. }
  73. })
  74. if len(userNodes) == 0 {
  75. return nil, fmt.Errorf("user no available nodes")
  76. }
  77. // 给上传节点的IPFS加锁
  78. ipfsReqBlder := reqbuilder.NewBuilder()
  79. // 如果本地的IPFS也是存储系统的一个节点,那么从本地上传时,需要加锁
  80. if stgglb.Local.NodeID != nil {
  81. ipfsReqBlder.IPFS().Buzy(*stgglb.Local.NodeID)
  82. }
  83. for _, node := range userNodes {
  84. if stgglb.Local.NodeID != nil && node.Node.NodeID == *stgglb.Local.NodeID {
  85. continue
  86. }
  87. ipfsReqBlder.IPFS().Buzy(node.Node.NodeID)
  88. }
  89. // TODO 考虑加Object的Create锁
  90. // 防止上传的副本被清除
  91. ipfsMutex, err := ipfsReqBlder.MutexLock(ctx.Distlock)
  92. if err != nil {
  93. return nil, fmt.Errorf("acquire locks failed, err: %w", err)
  94. }
  95. defer ipfsMutex.Unlock()
  96. rets, err := uploadAndUpdatePackage(t.packageID, t.objectIter, userNodes, t.nodeAffinity)
  97. if err != nil {
  98. return nil, err
  99. }
  100. return &UploadObjectsResult{
  101. Objects: rets,
  102. }, nil
  103. }
  104. // chooseUploadNode 选择一个上传文件的节点
  105. // 1. 选择设置了亲和性的节点
  106. // 2. 从与当前客户端相同地域的节点中随机选一个
  107. // 3. 没有的话从所有节点选择延迟最低的节点
  108. func chooseUploadNode(nodes []UploadNodeInfo, nodeAffinity *cdssdk.NodeID) UploadNodeInfo {
  109. if nodeAffinity != nil {
  110. aff, ok := lo.Find(nodes, func(node UploadNodeInfo) bool { return node.Node.NodeID == *nodeAffinity })
  111. if ok {
  112. return aff
  113. }
  114. }
  115. sameLocationNodes := lo.Filter(nodes, func(e UploadNodeInfo, i int) bool { return e.IsSameLocation })
  116. if len(sameLocationNodes) > 0 {
  117. return sameLocationNodes[rand.Intn(len(sameLocationNodes))]
  118. }
  119. // 选择延迟最低的节点
  120. nodes = sort2.Sort(nodes, func(e1, e2 UploadNodeInfo) int { return sort2.Cmp(e1.Delay, e2.Delay) })
  121. return nodes[0]
  122. }
  123. func uploadAndUpdatePackage(packageID cdssdk.PackageID, objectIter iterator.UploadingObjectIterator, userNodes []UploadNodeInfo, nodeAffinity *cdssdk.NodeID) ([]ObjectUploadResult, error) {
  124. coorCli, err := stgglb.CoordinatorMQPool.Acquire()
  125. if err != nil {
  126. return nil, fmt.Errorf("new coordinator client: %w", err)
  127. }
  128. defer stgglb.CoordinatorMQPool.Release(coorCli)
  129. // 为所有文件选择相同的上传节点
  130. uploadNode := chooseUploadNode(userNodes, nodeAffinity)
  131. var uploadRets []ObjectUploadResult
  132. //上传文件夹
  133. var adds []coormq.AddObjectEntry
  134. for {
  135. objInfo, err := objectIter.MoveNext()
  136. if err == iterator.ErrNoMoreItem {
  137. break
  138. }
  139. if err != nil {
  140. return nil, fmt.Errorf("reading object: %w", err)
  141. }
  142. err = func() error {
  143. defer objInfo.File.Close()
  144. uploadTime := time.Now()
  145. fileHash, err := uploadFile(objInfo.File, uploadNode)
  146. if err != nil {
  147. return fmt.Errorf("uploading file: %w", err)
  148. }
  149. uploadRets = append(uploadRets, ObjectUploadResult{
  150. Info: objInfo,
  151. Error: err,
  152. })
  153. adds = append(adds, coormq.NewAddObjectEntry(objInfo.Path, objInfo.Size, fileHash, uploadTime, uploadNode.Node.NodeID))
  154. return nil
  155. }()
  156. if err != nil {
  157. return nil, err
  158. }
  159. }
  160. updateResp, err := coorCli.UpdatePackage(coormq.NewUpdatePackage(packageID, adds, nil))
  161. if err != nil {
  162. return nil, fmt.Errorf("updating package: %w", err)
  163. }
  164. updatedObjs := make(map[string]*cdssdk.Object)
  165. for _, obj := range updateResp.Added {
  166. o := obj
  167. updatedObjs[obj.Path] = &o
  168. }
  169. for i := range uploadRets {
  170. obj := updatedObjs[uploadRets[i].Info.Path]
  171. if obj == nil {
  172. uploadRets[i].Error = fmt.Errorf("object %s not found in package", uploadRets[i].Info.Path)
  173. continue
  174. }
  175. uploadRets[i].Object = *obj
  176. }
  177. return uploadRets, nil
  178. }
  179. func uploadFile(file io.Reader, uploadNode UploadNodeInfo) (string, error) {
  180. // 本地有IPFS,则直接从本地IPFS上传
  181. if stgglb.IPFSPool != nil {
  182. logger.Infof("try to use local IPFS to upload file")
  183. // 只有本地IPFS不是存储系统中的一个节点,才需要Pin文件
  184. fileHash, err := uploadToLocalIPFS(file, uploadNode.Node.NodeID, stgglb.Local.NodeID == nil)
  185. if err == nil {
  186. return fileHash, nil
  187. } else {
  188. logger.Warnf("upload to local IPFS failed, so try to upload to node %d, err: %s", uploadNode.Node.NodeID, err.Error())
  189. }
  190. }
  191. // 否则发送到agent上传
  192. // 如果客户端与节点在同一个地域,则使用内网地址连接节点
  193. nodeIP := uploadNode.Node.ExternalIP
  194. grpcPort := uploadNode.Node.ExternalGRPCPort
  195. if uploadNode.IsSameLocation {
  196. nodeIP = uploadNode.Node.LocalIP
  197. grpcPort = uploadNode.Node.LocalGRPCPort
  198. logger.Infof("client and node %d are at the same location, use local ip", uploadNode.Node.NodeID)
  199. }
  200. fileHash, err := uploadToNode(file, nodeIP, grpcPort)
  201. if err != nil {
  202. return "", fmt.Errorf("upload to node %s failed, err: %w", nodeIP, err)
  203. }
  204. return fileHash, nil
  205. }
  206. func uploadToNode(file io.Reader, nodeIP string, grpcPort int) (string, error) {
  207. rpcCli, err := stgglb.AgentRPCPool.Acquire(nodeIP, grpcPort)
  208. if err != nil {
  209. return "", fmt.Errorf("new agent rpc client: %w", err)
  210. }
  211. defer rpcCli.Close()
  212. return rpcCli.SendIPFSFile(file)
  213. }
  214. func uploadToLocalIPFS(file io.Reader, nodeID cdssdk.NodeID, shouldPin bool) (string, error) {
  215. ipfsCli, err := stgglb.IPFSPool.Acquire()
  216. if err != nil {
  217. return "", fmt.Errorf("new ipfs client: %w", err)
  218. }
  219. defer ipfsCli.Close()
  220. // 从本地IPFS上传文件
  221. fileHash, err := ipfsCli.CreateFile(file)
  222. if err != nil {
  223. return "", fmt.Errorf("creating ipfs file: %w", err)
  224. }
  225. if !shouldPin {
  226. return fileHash, nil
  227. }
  228. err = pinIPFSFile(nodeID, fileHash)
  229. if err != nil {
  230. return "", err
  231. }
  232. return fileHash, nil
  233. }
  234. func pinIPFSFile(nodeID cdssdk.NodeID, fileHash string) error {
  235. agtCli, err := stgglb.AgentMQPool.Acquire(nodeID)
  236. if err != nil {
  237. return fmt.Errorf("new agent client: %w", err)
  238. }
  239. defer stgglb.AgentMQPool.Release(agtCli)
  240. // 然后让最近节点pin本地上传的文件
  241. _, err = agtCli.PinObject(agtmq.ReqPinObject([]string{fileHash}, false))
  242. if err != nil {
  243. return fmt.Errorf("start pinning object: %w", err)
  244. }
  245. return nil
  246. }

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