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

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