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

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