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.1 kB

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

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