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

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

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