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 8.0 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
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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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, loadTo []clitypes.UserSpaceID, loadToPath []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. if space.MasterHub == nil {
  52. continue
  53. }
  54. latency := time.Duration(math.MaxInt64)
  55. con, ok := cons[space.MasterHub.HubID]
  56. if ok && con.Latency != nil {
  57. latency = *con.Latency
  58. }
  59. uploadSpaces = append(uploadSpaces, UploadSpaceInfo{
  60. Space: *space,
  61. Delay: latency,
  62. IsSameLocation: space.MasterHub.LocationID == stgglb.Local.LocationID,
  63. })
  64. }
  65. if len(uploadSpaces) == 0 {
  66. return nil, fmt.Errorf("user no available userspaces")
  67. }
  68. loadToSpaces := make([]clitypes.UserSpaceDetail, len(loadTo))
  69. for i, spaceID := range loadTo {
  70. space, ok := lo.Find(spaceDetails, func(space *clitypes.UserSpaceDetail) bool {
  71. return space.UserSpace.UserSpaceID == spaceID
  72. })
  73. if !ok {
  74. return nil, fmt.Errorf("load to storage %v not found", spaceID)
  75. }
  76. if space.MasterHub == nil {
  77. return nil, fmt.Errorf("load to storage %v has no master hub", spaceID)
  78. }
  79. loadToSpaces[i] = *space
  80. }
  81. target := u.chooseUploadStorage(uploadSpaces, affinity)
  82. // 防止上传的副本被清除
  83. pubLock, err := reqbuilder.NewBuilder().Shard().Buzy(target.Space.UserSpace.UserSpaceID).MutexLock(u.pubLock)
  84. if err != nil {
  85. return nil, fmt.Errorf("acquire lock: %w", err)
  86. }
  87. return &UpdateUploader{
  88. uploader: u,
  89. pkgID: pkgID,
  90. targetSpace: target.Space,
  91. pubLock: pubLock,
  92. loadToSpaces: loadToSpaces,
  93. loadToPath: loadToPath,
  94. }, nil
  95. }
  96. // chooseUploadStorage 选择一个上传文件的节点
  97. // 1. 选择设置了亲和性的节点
  98. // 2. 从与当前客户端相同地域的节点中随机选一个
  99. // 3. 没有的话从所有节点选择延迟最低的节点
  100. func (w *Uploader) chooseUploadStorage(spaces []UploadSpaceInfo, spaceAffinity clitypes.UserSpaceID) UploadSpaceInfo {
  101. if spaceAffinity > 0 {
  102. aff, ok := lo.Find(spaces, func(space UploadSpaceInfo) bool { return space.Space.UserSpace.UserSpaceID == spaceAffinity })
  103. if ok {
  104. return aff
  105. }
  106. }
  107. sameLocationStorages := lo.Filter(spaces, func(e UploadSpaceInfo, i int) bool { return e.IsSameLocation })
  108. if len(sameLocationStorages) > 0 {
  109. return sameLocationStorages[rand.Intn(len(sameLocationStorages))]
  110. }
  111. // 选择延迟最低的节点
  112. spaces = sort2.Sort(spaces, func(e1, e2 UploadSpaceInfo) int { return sort2.Cmp(e1.Delay, e2.Delay) })
  113. return spaces[0]
  114. }
  115. func (u *Uploader) BeginCreateLoad(bktID clitypes.BucketID, pkgName string, loadTo []clitypes.UserSpaceID, loadToPath []string) (*CreateLoadUploader, error) {
  116. getSpaces := u.spaceMeta.GetMany(loadTo)
  117. spacesStgs := make([]clitypes.UserSpaceDetail, len(loadTo))
  118. for i, stg := range getSpaces {
  119. if stg == nil {
  120. return nil, fmt.Errorf("storage %v not found", loadTo[i])
  121. }
  122. spacesStgs[i] = *stg
  123. }
  124. pkg, err := db.DoTx01(u.db, func(tx db.SQLContext) (clitypes.Package, error) {
  125. _, err := u.db.Bucket().GetByID(tx, bktID)
  126. if err != nil {
  127. return clitypes.Package{}, err
  128. }
  129. return u.db.Package().Create(u.db.DefCtx(), bktID, pkgName, time.Now())
  130. })
  131. if err != nil {
  132. return nil, fmt.Errorf("create package: %w", err)
  133. }
  134. reqBld := reqbuilder.NewBuilder()
  135. for _, stg := range spacesStgs {
  136. reqBld.Shard().Buzy(stg.UserSpace.UserSpaceID)
  137. }
  138. lock, err := reqBld.MutexLock(u.pubLock)
  139. if err != nil {
  140. return nil, fmt.Errorf("acquire lock: %w", err)
  141. }
  142. return &CreateLoadUploader{
  143. pkg: pkg,
  144. targetSpaces: spacesStgs,
  145. loadRoots: loadToPath,
  146. uploader: u,
  147. pubLock: lock,
  148. }, nil
  149. }
  150. func (u *Uploader) UploadPart(objID clitypes.ObjectID, index int, stream io.Reader) error {
  151. detail, err := u.db.Object().GetDetail(u.db.DefCtx(), objID)
  152. if err != nil {
  153. return fmt.Errorf("getting object detail: %w", err)
  154. }
  155. objDe := detail
  156. _, ok := objDe.Object.Redundancy.(*clitypes.MultipartUploadRedundancy)
  157. if !ok {
  158. return fmt.Errorf("object %v is not a multipart upload", objID)
  159. }
  160. var space clitypes.UserSpaceDetail
  161. if len(objDe.Blocks) > 0 {
  162. cstg := u.spaceMeta.Get(objDe.Blocks[0].UserSpaceID)
  163. if cstg == nil {
  164. return fmt.Errorf("space %v not found", objDe.Blocks[0].UserSpaceID)
  165. }
  166. space = *cstg
  167. } else {
  168. spaceIDs, err := u.db.UserSpace().GetAllIDs(u.db.DefCtx())
  169. if err != nil {
  170. return fmt.Errorf("getting user space ids: %w", err)
  171. }
  172. spaces := u.spaceMeta.GetMany(spaceIDs)
  173. spaces = lo2.RemoveAllDefault(spaces)
  174. cons := u.connectivity.GetAll()
  175. var userStgs []UploadSpaceInfo
  176. for _, space := range spaces {
  177. if space.MasterHub == nil {
  178. continue
  179. }
  180. delay := time.Duration(math.MaxInt64)
  181. con, ok := cons[space.MasterHub.HubID]
  182. if ok && con.Latency != nil {
  183. delay = *con.Latency
  184. }
  185. userStgs = append(userStgs, UploadSpaceInfo{
  186. Space: *space,
  187. Delay: delay,
  188. IsSameLocation: space.MasterHub.LocationID == stgglb.Local.LocationID,
  189. })
  190. }
  191. if len(userStgs) == 0 {
  192. return fmt.Errorf("user no available storages")
  193. }
  194. space = u.chooseUploadStorage(userStgs, 0).Space
  195. }
  196. lock, err := reqbuilder.NewBuilder().Shard().Buzy(space.UserSpace.UserSpaceID).MutexLock(u.pubLock)
  197. if err != nil {
  198. return fmt.Errorf("acquire lock: %w", err)
  199. }
  200. defer lock.Unlock()
  201. ft := ioswitch2.NewFromTo()
  202. fromDrv, hd := ioswitch2.NewFromDriver(ioswitch2.RawStream())
  203. ft.AddFrom(fromDrv).
  204. AddTo(ioswitch2.NewToShardStore(*space.MasterHub, space, ioswitch2.RawStream(), "shard"))
  205. plans := exec.NewPlanBuilder()
  206. err = parser.Parse(ft, plans)
  207. if err != nil {
  208. return fmt.Errorf("parse fromto: %w", err)
  209. }
  210. exeCtx := exec.NewExecContext()
  211. exec.SetValueByType(exeCtx, u.stgPool)
  212. exec := plans.Execute(exeCtx)
  213. exec.BeginWrite(io.NopCloser(stream), hd)
  214. ret, err := exec.Wait(context.TODO())
  215. if err != nil {
  216. return fmt.Errorf("executing plan: %w", err)
  217. }
  218. shardInfo := ret["shard"].(*ops2.ShardInfoValue)
  219. err = u.db.DoTx(func(tx db.SQLContext) error {
  220. return u.db.Object().AppendPart(tx, clitypes.ObjectBlock{
  221. ObjectID: objID,
  222. Index: index,
  223. UserSpaceID: space.UserSpace.UserSpaceID,
  224. FileHash: shardInfo.Hash,
  225. Size: shardInfo.Size,
  226. })
  227. })
  228. return err
  229. }

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