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.

uploader.go 7.7 kB

7 months ago
7 months ago
6 months ago
7 months ago
6 months ago
7 months ago
7 months ago
6 months ago
7 months ago
6 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
6 months ago
7 months ago
6 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
6 months ago
7 months ago
7 months ago
6 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
6 months ago
7 months ago
7 months ago
7 months ago
7 months ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. package uploader
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "math"
  7. "math/rand"
  8. "time"
  9. "github.com/samber/lo"
  10. "gitlink.org.cn/cloudream/common/pkgs/ioswitch/exec"
  11. "gitlink.org.cn/cloudream/common/utils/lo2"
  12. "gitlink.org.cn/cloudream/common/utils/sort2"
  13. "gitlink.org.cn/cloudream/jcs-pub/client/internal/db"
  14. "gitlink.org.cn/cloudream/jcs-pub/client/internal/metacache"
  15. clitypes "gitlink.org.cn/cloudream/jcs-pub/client/types"
  16. stgglb "gitlink.org.cn/cloudream/jcs-pub/common/globals"
  17. "gitlink.org.cn/cloudream/jcs-pub/common/pkgs/connectivity"
  18. "gitlink.org.cn/cloudream/jcs-pub/common/pkgs/distlock"
  19. "gitlink.org.cn/cloudream/jcs-pub/common/pkgs/distlock/reqbuilder"
  20. "gitlink.org.cn/cloudream/jcs-pub/common/pkgs/ioswitch2"
  21. "gitlink.org.cn/cloudream/jcs-pub/common/pkgs/ioswitch2/ops2"
  22. "gitlink.org.cn/cloudream/jcs-pub/common/pkgs/ioswitch2/parser"
  23. "gitlink.org.cn/cloudream/jcs-pub/common/pkgs/storage/pool"
  24. )
  25. type Uploader struct {
  26. pubLock *distlock.Service
  27. connectivity *connectivity.Collector
  28. stgPool *pool.Pool
  29. spaceMeta *metacache.UserSpaceMeta
  30. db *db.DB
  31. }
  32. func NewUploader(pubLock *distlock.Service, connectivity *connectivity.Collector, stgPool *pool.Pool, spaceMeta *metacache.UserSpaceMeta, db *db.DB) *Uploader {
  33. return &Uploader{
  34. pubLock: pubLock,
  35. connectivity: connectivity,
  36. stgPool: stgPool,
  37. spaceMeta: spaceMeta,
  38. db: db,
  39. }
  40. }
  41. func (u *Uploader) BeginUpdate(pkgID clitypes.PackageID, affinity clitypes.UserSpaceID, copyTo []clitypes.UserSpaceID, copyToPath []string) (*UpdateUploader, error) {
  42. spaceIDs, err := u.db.UserSpace().GetAllIDs(u.db.DefCtx())
  43. if err != nil {
  44. return nil, fmt.Errorf("getting user space ids: %w", err)
  45. }
  46. spaceDetails := u.spaceMeta.GetMany(spaceIDs)
  47. spaceDetails = lo2.RemoveAllDefault(spaceDetails)
  48. cons := u.connectivity.GetAll()
  49. var uploadSpaces []UploadSpaceInfo
  50. for _, space := range spaceDetails {
  51. latency := time.Duration(math.MaxInt64)
  52. con, ok := cons[space.RecommendHub.HubID]
  53. if ok && con.Latency != nil {
  54. latency = *con.Latency
  55. }
  56. uploadSpaces = append(uploadSpaces, UploadSpaceInfo{
  57. Space: *space,
  58. Delay: latency,
  59. IsSameLocation: space.RecommendHub.LocationID == stgglb.Local.LocationID,
  60. })
  61. }
  62. if len(uploadSpaces) == 0 {
  63. return nil, fmt.Errorf("user no available userspaces")
  64. }
  65. copyToSpaces := make([]clitypes.UserSpaceDetail, len(copyTo))
  66. for i, spaceID := range copyTo {
  67. space, ok := lo.Find(spaceDetails, func(space *clitypes.UserSpaceDetail) bool {
  68. return space.UserSpace.UserSpaceID == spaceID
  69. })
  70. if !ok {
  71. return nil, fmt.Errorf("user space %v not found", spaceID)
  72. }
  73. copyToSpaces[i] = *space
  74. }
  75. target := u.chooseUploadStorage(uploadSpaces, affinity)
  76. // 防止上传的副本被清除
  77. pubLock, err := reqbuilder.NewBuilder().Shard().Buzy(target.Space.UserSpace.UserSpaceID).MutexLock(u.pubLock)
  78. if err != nil {
  79. return nil, fmt.Errorf("acquire lock: %w", err)
  80. }
  81. return &UpdateUploader{
  82. uploader: u,
  83. pkgID: pkgID,
  84. targetSpace: target.Space,
  85. pubLock: pubLock,
  86. copyToSpaces: copyToSpaces,
  87. copyToPath: copyToPath,
  88. }, nil
  89. }
  90. // chooseUploadStorage 选择一个上传文件的节点
  91. // 1. 选择设置了亲和性的节点
  92. // 2. 从与当前客户端相同地域的节点中随机选一个
  93. // 3. 没有的话从所有节点选择延迟最低的节点
  94. func (w *Uploader) chooseUploadStorage(spaces []UploadSpaceInfo, spaceAffinity clitypes.UserSpaceID) UploadSpaceInfo {
  95. if spaceAffinity > 0 {
  96. aff, ok := lo.Find(spaces, func(space UploadSpaceInfo) bool { return space.Space.UserSpace.UserSpaceID == spaceAffinity })
  97. if ok {
  98. return aff
  99. }
  100. }
  101. sameLocationStorages := lo.Filter(spaces, func(e UploadSpaceInfo, i int) bool { return e.IsSameLocation })
  102. if len(sameLocationStorages) > 0 {
  103. return sameLocationStorages[rand.Intn(len(sameLocationStorages))]
  104. }
  105. // 选择延迟最低的节点
  106. spaces = sort2.Sort(spaces, func(e1, e2 UploadSpaceInfo) int { return sort2.Cmp(e1.Delay, e2.Delay) })
  107. return spaces[0]
  108. }
  109. func (u *Uploader) BeginCreateUpload(bktID clitypes.BucketID, pkgName string, copyTo []clitypes.UserSpaceID, copyToPath []string) (*CreateUploader, error) {
  110. getSpaces := u.spaceMeta.GetMany(copyTo)
  111. spacesStgs := make([]clitypes.UserSpaceDetail, len(copyTo))
  112. for i, stg := range getSpaces {
  113. if stg == nil {
  114. return nil, fmt.Errorf("storage %v not found", copyTo[i])
  115. }
  116. spacesStgs[i] = *stg
  117. }
  118. pkg, err := db.DoTx01(u.db, func(tx db.SQLContext) (clitypes.Package, error) {
  119. _, err := u.db.Bucket().GetByID(tx, bktID)
  120. if err != nil {
  121. return clitypes.Package{}, err
  122. }
  123. return u.db.Package().Create(u.db.DefCtx(), bktID, pkgName, time.Now())
  124. })
  125. if err != nil {
  126. return nil, fmt.Errorf("create package: %w", err)
  127. }
  128. reqBld := reqbuilder.NewBuilder()
  129. for _, stg := range spacesStgs {
  130. reqBld.Shard().Buzy(stg.UserSpace.UserSpaceID)
  131. }
  132. lock, err := reqBld.MutexLock(u.pubLock)
  133. if err != nil {
  134. return nil, fmt.Errorf("acquire lock: %w", err)
  135. }
  136. return &CreateUploader{
  137. pkg: pkg,
  138. targetSpaces: spacesStgs,
  139. copyRoots: copyToPath,
  140. uploader: u,
  141. pubLock: lock,
  142. }, nil
  143. }
  144. func (u *Uploader) UploadPart(objID clitypes.ObjectID, index int, stream io.Reader) error {
  145. detail, err := u.db.Object().GetDetail(u.db.DefCtx(), objID)
  146. if err != nil {
  147. return fmt.Errorf("getting object detail: %w", err)
  148. }
  149. objDe := detail
  150. _, ok := objDe.Object.Redundancy.(*clitypes.MultipartUploadRedundancy)
  151. if !ok {
  152. return fmt.Errorf("object %v is not a multipart upload", objID)
  153. }
  154. var space clitypes.UserSpaceDetail
  155. if len(objDe.Blocks) > 0 {
  156. cstg := u.spaceMeta.Get(objDe.Blocks[0].UserSpaceID)
  157. if cstg == nil {
  158. return fmt.Errorf("space %v not found", objDe.Blocks[0].UserSpaceID)
  159. }
  160. space = *cstg
  161. } else {
  162. spaceIDs, err := u.db.UserSpace().GetAllIDs(u.db.DefCtx())
  163. if err != nil {
  164. return fmt.Errorf("getting user space ids: %w", err)
  165. }
  166. spaces := u.spaceMeta.GetMany(spaceIDs)
  167. spaces = lo2.RemoveAllDefault(spaces)
  168. cons := u.connectivity.GetAll()
  169. var userStgs []UploadSpaceInfo
  170. for _, space := range spaces {
  171. delay := time.Duration(math.MaxInt64)
  172. con, ok := cons[space.RecommendHub.HubID]
  173. if ok && con.Latency != nil {
  174. delay = *con.Latency
  175. }
  176. userStgs = append(userStgs, UploadSpaceInfo{
  177. Space: *space,
  178. Delay: delay,
  179. IsSameLocation: space.RecommendHub.LocationID == stgglb.Local.LocationID,
  180. })
  181. }
  182. if len(userStgs) == 0 {
  183. return fmt.Errorf("user no available storages")
  184. }
  185. space = u.chooseUploadStorage(userStgs, 0).Space
  186. }
  187. lock, err := reqbuilder.NewBuilder().Shard().Buzy(space.UserSpace.UserSpaceID).MutexLock(u.pubLock)
  188. if err != nil {
  189. return fmt.Errorf("acquire lock: %w", err)
  190. }
  191. defer lock.Unlock()
  192. ft := ioswitch2.NewFromTo()
  193. fromDrv, hd := ioswitch2.NewFromDriver(ioswitch2.RawStream())
  194. ft.AddFrom(fromDrv).
  195. AddTo(ioswitch2.NewToShardStore(space, ioswitch2.RawStream(), "shard"))
  196. plans := exec.NewPlanBuilder()
  197. err = parser.Parse(ft, plans)
  198. if err != nil {
  199. return fmt.Errorf("parse fromto: %w", err)
  200. }
  201. exeCtx := exec.NewExecContext()
  202. exec.SetValueByType(exeCtx, u.stgPool)
  203. exec := plans.Execute(exeCtx)
  204. exec.BeginWrite(io.NopCloser(stream), hd)
  205. ret, err := exec.Wait(context.TODO())
  206. if err != nil {
  207. return fmt.Errorf("executing plan: %w", err)
  208. }
  209. shardInfo := ret["shard"].(*ops2.FileInfoValue)
  210. err = u.db.DoTx(func(tx db.SQLContext) error {
  211. return u.db.Object().AppendPart(tx, clitypes.ObjectBlock{
  212. ObjectID: objID,
  213. Index: index,
  214. UserSpaceID: space.UserSpace.UserSpaceID,
  215. FileHash: shardInfo.Hash,
  216. Size: shardInfo.Size,
  217. })
  218. })
  219. return err
  220. }

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