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.

cache.go 20 kB

8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
7 months ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. package cache
  2. import (
  3. "errors"
  4. "io"
  5. "os"
  6. "path/filepath"
  7. "sync"
  8. "syscall"
  9. "time"
  10. "github.com/inhies/go-bytesize"
  11. "github.com/samber/lo"
  12. "gitlink.org.cn/cloudream/common/pkgs/logger"
  13. "gitlink.org.cn/cloudream/common/pkgs/trie"
  14. "gitlink.org.cn/cloudream/common/utils/io2"
  15. "gitlink.org.cn/cloudream/common/utils/lo2"
  16. "gitlink.org.cn/cloudream/jcs-pub/client/internal/db"
  17. "gitlink.org.cn/cloudream/jcs-pub/client/internal/downloader"
  18. "gitlink.org.cn/cloudream/jcs-pub/client/internal/mount/config"
  19. "gitlink.org.cn/cloudream/jcs-pub/client/internal/mount/fuse"
  20. "gitlink.org.cn/cloudream/jcs-pub/client/internal/uploader"
  21. clitypes "gitlink.org.cn/cloudream/jcs-pub/client/types"
  22. )
  23. type CacheEntry interface {
  24. fuse.FsEntry
  25. // 在虚拟文件系统中的路径,即不包含缓存目录的路径
  26. PathComps() []string
  27. }
  28. type CacheEntryInfo struct {
  29. PathComps []string
  30. Size int64
  31. Mode os.FileMode
  32. ModTime time.Time
  33. IsDir bool
  34. }
  35. type Cache struct {
  36. cfg *config.Config
  37. db *db.DB
  38. uploader *uploader.Uploader
  39. downloader *downloader.Downloader
  40. lock *sync.RWMutex
  41. cacheDone chan any
  42. activeCache *trie.Trie[*CacheFile]
  43. }
  44. func NewCache(cfg *config.Config, db *db.DB, uploader *uploader.Uploader, downloader *downloader.Downloader) *Cache {
  45. return &Cache{
  46. cfg: cfg,
  47. db: db,
  48. uploader: uploader,
  49. downloader: downloader,
  50. lock: &sync.RWMutex{},
  51. cacheDone: make(chan any),
  52. activeCache: trie.NewTrie[*CacheFile](),
  53. }
  54. }
  55. func (c *Cache) Start() {
  56. go c.scanningCache()
  57. go c.scanningData()
  58. }
  59. func (c *Cache) Stop() {
  60. close(c.cacheDone)
  61. }
  62. func (c *Cache) GetCacheDataPath(comps ...string) string {
  63. comps2 := make([]string, len(comps)+1)
  64. comps2[0] = c.cfg.DataDir
  65. copy(comps2[1:], comps)
  66. return filepath.Join(comps2...)
  67. }
  68. func (c *Cache) GetCacheMetaPath(comps ...string) string {
  69. comps2 := make([]string, len(comps)+1)
  70. comps2[0] = c.cfg.MetaDir
  71. copy(comps2[1:], comps)
  72. return filepath.Join(comps2...)
  73. }
  74. func (c *Cache) Dump() CacheStatus {
  75. c.lock.RLock()
  76. defer c.lock.RUnlock()
  77. var activeFiles []CacheFileStatus
  78. c.activeCache.Iterate(func(path []string, node *trie.Node[*CacheFile], isWordNode bool) trie.VisitCtrl {
  79. if node.Value == nil {
  80. return trie.VisitContinue
  81. }
  82. activeFiles = append(activeFiles, CacheFileStatus{
  83. Path: filepath.Join(path...),
  84. RefCount: node.Value.state.refCount,
  85. IsLoaded: node.Value.state.isLoaded,
  86. IsUploading: node.Value.state.uploading != nil,
  87. })
  88. return trie.VisitContinue
  89. })
  90. return CacheStatus{
  91. ActiveFiles: activeFiles,
  92. }
  93. }
  94. // 获取指定位置的缓存条目信息。如果路径不存在,则返回nil。
  95. func (c *Cache) Stat(pathComps []string) *CacheEntryInfo {
  96. c.lock.RLock()
  97. defer c.lock.RUnlock()
  98. node, ok := c.activeCache.WalkEnd(pathComps)
  99. if ok && node.Value != nil {
  100. info := node.Value.Info()
  101. return &info
  102. }
  103. dataPath := c.GetCacheDataPath(pathComps...)
  104. stat, err := os.Stat(dataPath)
  105. if err != nil {
  106. // TODO 日志记录
  107. return nil
  108. }
  109. if stat.IsDir() {
  110. info, err := loadCacheDirInfo(c, pathComps, stat)
  111. if err != nil {
  112. return nil
  113. }
  114. return info
  115. }
  116. info, err := loadCacheFileInfo(c, pathComps, stat)
  117. if err != nil {
  118. return nil
  119. }
  120. return info
  121. }
  122. // 创建一个缓存文件。如果文件已经存在,则会覆盖已有文件。如果加载过程中发生了错误,或者目标位置是一个目录,则会返回nil。
  123. //
  124. // 记得使用Release减少引用计数
  125. func (c *Cache) CreateFile(pathComps []string) *CacheFile {
  126. c.lock.Lock()
  127. defer c.lock.Unlock()
  128. node, ok := c.activeCache.WalkEnd(pathComps)
  129. if ok && node.Value != nil {
  130. node.Value.Delete()
  131. if node.Value.state.uploading != nil {
  132. node.Value.state.uploading.isDeleted = true
  133. }
  134. }
  135. ch, err := createNewCacheFile(c, pathComps)
  136. if err != nil {
  137. logger.Warnf("create new cache file %v: %v", pathComps, err)
  138. return nil
  139. }
  140. ch.state.refCount++
  141. c.activeCache.CreateWords(pathComps).Value = ch
  142. logger.Debugf("create new cache file %v", pathComps)
  143. return ch
  144. }
  145. // 尝试加载缓存文件,如果文件不存在,则使用obj的信息创建一个新缓存文件,而如果obj为nil,那么会返回nil。
  146. //
  147. // 记得使用Release减少引用计数
  148. func (c *Cache) LoadFile(pathComps []string, obj *clitypes.Object) *CacheFile {
  149. c.lock.Lock()
  150. defer c.lock.Unlock()
  151. node, ok := c.activeCache.WalkEnd(pathComps)
  152. if ok && node.Value != nil {
  153. if !node.Value.state.isLoaded {
  154. err := node.Value.Load()
  155. if err != nil {
  156. logger.Warnf("load cache %v: %v", pathComps, err)
  157. return nil
  158. }
  159. }
  160. return node.Value
  161. }
  162. ch, err := loadCacheFile(c, pathComps)
  163. if err == nil {
  164. ch.remoteObj = obj
  165. ch.state.refCount++
  166. c.activeCache.CreateWords(pathComps).Value = ch
  167. logger.Debugf("load cache %v", pathComps)
  168. return ch
  169. }
  170. if !os.IsNotExist(err) {
  171. // TODO 日志记录
  172. logger.Warnf("load cache %v: %v", pathComps, err)
  173. return nil
  174. }
  175. if obj == nil {
  176. return nil
  177. }
  178. ch, err = newCacheFileFromObject(c, pathComps, obj)
  179. if err != nil {
  180. logger.Warnf("create cache %v from object: %v", pathComps, err)
  181. return nil
  182. }
  183. ch.state.refCount++
  184. c.activeCache.CreateWords(pathComps).Value = ch
  185. logger.Debugf("create cache %v from object %v", pathComps, obj.ObjectID)
  186. return ch
  187. }
  188. // 创建一个缓存目录。如果目录已经存在,则会重置目录属性。如果加载过程中发生了错误,或者目标位置是一个文件,则会返回nil
  189. func (c *Cache) CreateDir(pathComps []string) *CacheDir {
  190. c.lock.Lock()
  191. defer c.lock.Unlock()
  192. ch, err := createNewCacheDir(c, pathComps)
  193. if err != nil {
  194. logger.Warnf("create cache dir: %v", err)
  195. return nil
  196. }
  197. return ch
  198. }
  199. type CreateDirOption struct {
  200. ModTime time.Time
  201. }
  202. // 加载指定缓存目录,如果目录不存在,则使用createOpt选项创建目录,而如果createOpt为nil,那么会返回nil。
  203. func (c *Cache) LoadDir(pathComps []string, createOpt *CreateDirOption) *CacheDir {
  204. c.lock.Lock()
  205. defer c.lock.Unlock()
  206. ch, err := loadCacheDir(c, pathComps)
  207. if err == nil {
  208. return ch
  209. }
  210. if !os.IsNotExist(err) {
  211. // TODO 日志记录
  212. return nil
  213. }
  214. if createOpt == nil {
  215. return nil
  216. }
  217. // 创建目录
  218. ch, err = makeCacheDirFromOption(c, pathComps, *createOpt)
  219. if err != nil {
  220. // TODO 日志记录
  221. return nil
  222. }
  223. return ch
  224. }
  225. // 加载指定路径下的所有缓存条目信息
  226. func (c *Cache) StatMany(pathComps []string) []CacheEntryInfo {
  227. c.lock.RLock()
  228. defer c.lock.RUnlock()
  229. var infos []CacheEntryInfo
  230. exists := make(map[string]bool)
  231. node, ok := c.activeCache.WalkEnd(pathComps)
  232. if ok {
  233. for name, child := range node.WordNexts {
  234. if child.Value != nil {
  235. infos = append(infos, child.Value.Info())
  236. exists[name] = true
  237. }
  238. }
  239. }
  240. osEns, err := os.ReadDir(c.GetCacheDataPath(pathComps...))
  241. if err != nil {
  242. return nil
  243. }
  244. for _, e := range osEns {
  245. if exists[e.Name()] {
  246. continue
  247. }
  248. info, err := e.Info()
  249. if err != nil {
  250. continue
  251. }
  252. if e.IsDir() {
  253. info, err := loadCacheDirInfo(c, append(lo2.ArrayClone(pathComps), e.Name()), info)
  254. if err != nil {
  255. continue
  256. }
  257. infos = append(infos, *info)
  258. } else {
  259. info, err := loadCacheFileInfo(c, append(lo2.ArrayClone(pathComps), e.Name()), info)
  260. if err != nil {
  261. continue
  262. }
  263. infos = append(infos, *info)
  264. }
  265. }
  266. return infos
  267. }
  268. // 删除指定路径的缓存文件或目录。删除目录时如果目录不为空,则会报错。
  269. func (c *Cache) Remove(pathComps []string) error {
  270. c.lock.Lock()
  271. defer c.lock.Unlock()
  272. node, ok := c.activeCache.WalkEnd(pathComps)
  273. if ok {
  274. if len(node.WordNexts) > 0 {
  275. return fuse.ErrNotEmpty
  276. }
  277. if node.Value != nil {
  278. node.Value.Delete()
  279. if node.Value.state.uploading != nil {
  280. node.Value.state.uploading.isDeleted = true
  281. }
  282. }
  283. node.RemoveSelf(true)
  284. logger.Debugf("active cache %v removed", pathComps)
  285. return nil
  286. }
  287. metaPath := c.GetCacheMetaPath(pathComps...)
  288. dataPath := c.GetCacheDataPath(pathComps...)
  289. os.Remove(metaPath)
  290. err := os.Remove(dataPath)
  291. if err == nil || os.IsNotExist(err) {
  292. logger.Debugf("local cache %v removed", pathComps)
  293. return nil
  294. }
  295. if errors.Is(err, syscall.ENOTEMPTY) {
  296. return fuse.ErrNotEmpty
  297. }
  298. return err
  299. }
  300. // 移动指定路径的缓存文件或目录到新的路径。如果目标路径已经存在,则会报错。
  301. //
  302. // 如果移动成功,则返回移动后的缓存文件或目录。如果文件或目录不存在,则返回nil。
  303. func (c *Cache) Move(pathComps []string, newPathComps []string) error {
  304. c.lock.Lock()
  305. defer c.lock.Unlock()
  306. _, ok := c.activeCache.WalkEnd(newPathComps)
  307. if ok {
  308. return fuse.ErrExists
  309. }
  310. newMetaPath := c.GetCacheMetaPath(newPathComps...)
  311. newDataPath := c.GetCacheDataPath(newPathComps...)
  312. _, err := os.Stat(newDataPath)
  313. if err == nil {
  314. return fuse.ErrExists
  315. }
  316. if !os.IsNotExist(err) {
  317. return err
  318. }
  319. oldMetaPath := c.GetCacheMetaPath(pathComps...)
  320. oldDataPath := c.GetCacheDataPath(pathComps...)
  321. // 确定源文件存在,再进行后面的操作
  322. _, err = os.Stat(oldDataPath)
  323. if err != nil {
  324. if os.IsNotExist(err) {
  325. return fuse.ErrNotExists
  326. }
  327. return err
  328. }
  329. // 创建父目录是为了解决被移动的文件不在本地的问题。
  330. // 但同时也导致了如果目的路径的父目录确实不存在,这里会意外的创建了这个目录
  331. newMetaDir := filepath.Dir(newMetaPath)
  332. err = os.MkdirAll(newMetaDir, 0755)
  333. if err != nil {
  334. return err
  335. }
  336. newDataDir := filepath.Dir(newDataPath)
  337. err = os.MkdirAll(newDataDir, 0755)
  338. if err != nil {
  339. return err
  340. }
  341. // 每个缓存文件持有meta文件和data文件的句柄,所以这里移动文件,不影响句柄的使用。
  342. // 只能忽略这里的错误
  343. os.Rename(oldMetaPath, newMetaPath)
  344. os.Rename(oldDataPath, newDataPath)
  345. // 更新缓存
  346. oldNode, ok := c.activeCache.WalkEnd(pathComps)
  347. if ok {
  348. newNode := c.activeCache.CreateWords(newPathComps)
  349. newNode.Value = oldNode.Value
  350. newNode.WordNexts = oldNode.WordNexts
  351. oldNode.RemoveSelf(false)
  352. if newNode.Value != nil {
  353. newNode.Value.Move(newPathComps)
  354. }
  355. newNode.Iterate(func(path []string, node *trie.Node[*CacheFile], isWordNode bool) trie.VisitCtrl {
  356. if node.Value != nil {
  357. node.Value.Move(lo2.AppendNew(newPathComps, path...))
  358. }
  359. return trie.VisitContinue
  360. })
  361. }
  362. logger.Debugf("cache moved: %v -> %v", pathComps, newPathComps)
  363. return nil
  364. }
  365. type uploadingPackage struct {
  366. bktName string
  367. pkgName string
  368. pkg clitypes.Package
  369. upObjs []*uploadingObject
  370. }
  371. type uploadingObject struct {
  372. pathComps []string
  373. cache *CacheFile
  374. reader *CacheFileHandle
  375. isDeleted bool
  376. isSuccess bool
  377. }
  378. func (c *Cache) scanningCache() {
  379. ticker := time.NewTicker(time.Second * 5)
  380. defer ticker.Stop()
  381. lastScanPath := []string{}
  382. for {
  383. select {
  384. case _, ok := <-c.cacheDone:
  385. if !ok {
  386. return
  387. }
  388. case <-ticker.C:
  389. }
  390. c.lock.Lock()
  391. type packageFullName struct {
  392. bktName string
  393. pkgName string
  394. }
  395. uploadingPkgs := make(map[packageFullName]*uploadingPackage)
  396. visitCnt := 0
  397. visitBreak := false
  398. node, _ := c.activeCache.WalkEnd(lastScanPath)
  399. node.Iterate(func(path []string, node *trie.Node[*CacheFile], isWordNode bool) trie.VisitCtrl {
  400. ch := node.Value
  401. if ch == nil {
  402. return trie.VisitContinue
  403. }
  404. if ch.state.refCount > 0 {
  405. logger.Debugf("skip cache %v, refCount: %v", path, ch.state.refCount)
  406. return trie.VisitContinue
  407. }
  408. visitCnt++
  409. shouldUpload := true
  410. // 不存放在Package里的文件,不需要上传
  411. if len(ch.pathComps) <= 2 {
  412. shouldUpload = false
  413. }
  414. if ch.Revision() > 0 && shouldUpload {
  415. // 1. 本地缓存被修改了,如果一段时间内没有被使用,则进行上传
  416. if time.Since(ch.state.freeTime) > c.cfg.UploadPendingTime && ch.state.uploading == nil {
  417. fullName := packageFullName{ch.pathComps[0], ch.pathComps[1]}
  418. pkg, ok := uploadingPkgs[fullName]
  419. if !ok {
  420. pkg = &uploadingPackage{
  421. bktName: ch.pathComps[0],
  422. pkgName: ch.pathComps[1],
  423. }
  424. uploadingPkgs[fullName] = pkg
  425. }
  426. obj := &uploadingObject{
  427. pathComps: lo2.ArrayClone(ch.pathComps),
  428. cache: ch,
  429. reader: ch.OpenReadWhenScanning(),
  430. }
  431. pkg.upObjs = append(pkg.upObjs, obj)
  432. ch.state.uploading = obj
  433. }
  434. } else if ch.state.isLoaded {
  435. // 2. 本地缓存没有被修改,如果一段时间内没有被使用,则进行卸载
  436. if time.Since(ch.state.freeTime) > c.cfg.CacheActiveTime {
  437. ch.Unload()
  438. ch.state.isLoaded = false
  439. ch.state.unloadTime = time.Now()
  440. }
  441. } else {
  442. // 3. 卸载后的缓存,如果一段时间内没有被使用,则进行删除。
  443. if time.Since(ch.state.unloadTime) > c.cfg.CacheExpireTime {
  444. // 如果文件已经同步到远端,则可以直接删除本地缓存
  445. if ch.Revision() == 0 {
  446. ch.Delete()
  447. }
  448. node.RemoveSelf(true)
  449. }
  450. }
  451. // 每次最多遍历500个节点,防止占用锁太久
  452. if visitCnt > 500 {
  453. lastScanPath = lo2.ArrayClone(path)
  454. visitBreak = true
  455. return trie.VisitBreak
  456. }
  457. return trie.VisitContinue
  458. })
  459. if !visitBreak {
  460. lastScanPath = []string{}
  461. }
  462. c.lock.Unlock()
  463. if len(uploadingPkgs) > 0 {
  464. go c.doUploading(lo.Values(uploadingPkgs))
  465. }
  466. }
  467. }
  468. func (c *Cache) scanningData() {
  469. ticker := time.NewTicker(c.cfg.ScanDataDirInterval)
  470. defer ticker.Stop()
  471. var walkTrace []*os.File
  472. var walkTraceComps []string
  473. for {
  474. select {
  475. case <-ticker.C:
  476. case <-c.cacheDone:
  477. return
  478. }
  479. logger.Infof("begin scanning data dir")
  480. if len(walkTrace) == 0 {
  481. dir, err := os.Open(c.cfg.DataDir)
  482. if err != nil {
  483. logger.Warnf("open data dir: %v", err)
  484. continue
  485. }
  486. walkTrace = []*os.File{dir}
  487. walkTraceComps = []string{c.cfg.MetaDir}
  488. }
  489. const maxVisitCnt = 5000
  490. const maxUntrackedFiles = 500
  491. var untrackedFiles [][]string
  492. visitCnt := 0
  493. // 一次最多遍历5000个文件(包括路径上的文件夹),一次最多添加500个未跟踪文件
  494. for len(walkTrace) > 0 && visitCnt < maxVisitCnt && len(untrackedFiles) < maxUntrackedFiles {
  495. lastNode := walkTrace[len(walkTrace)-1]
  496. visitCnt++
  497. e, err := lastNode.Readdir(1)
  498. if err == io.EOF {
  499. lastNode.Close()
  500. walkTrace = walkTrace[:len(walkTrace)-1]
  501. walkTraceComps = walkTraceComps[:len(walkTraceComps)-1]
  502. continue
  503. }
  504. if err != nil {
  505. logger.Warnf("read dir %v: %v", lastNode.Name(), err)
  506. lastNode.Close()
  507. walkTrace = walkTrace[:len(walkTrace)-1]
  508. walkTraceComps = walkTraceComps[:len(walkTraceComps)-1]
  509. continue
  510. }
  511. if e[0].IsDir() {
  512. child, err := os.Open(filepath.Join(lastNode.Name(), e[0].Name()))
  513. if err != nil {
  514. logger.Warnf("open dir %v: %v", e[0].Name(), err)
  515. continue
  516. }
  517. walkTrace = append(walkTrace, child)
  518. walkTraceComps = append(walkTraceComps, e[0].Name())
  519. continue
  520. }
  521. // 对于不在Package层级的文件,不跟踪
  522. if len(walkTrace) <= 2 {
  523. continue
  524. }
  525. walkTraceComps = append(walkTraceComps, e[0].Name())
  526. fileMetaPath := filepath.Join(walkTraceComps...)
  527. _, err = os.Stat(fileMetaPath)
  528. if err == nil || !os.IsNotExist(err) {
  529. walkTraceComps = walkTraceComps[:len(walkTraceComps)-1]
  530. continue
  531. }
  532. untrackedFiles = append(untrackedFiles, lo2.ArrayClone(walkTraceComps[1:]))
  533. walkTraceComps = walkTraceComps[:len(walkTraceComps)-1]
  534. }
  535. if len(untrackedFiles) > 0 {
  536. for _, comps := range untrackedFiles {
  537. ch := c.LoadFile(comps, nil)
  538. if ch != nil {
  539. ch.Release()
  540. }
  541. }
  542. }
  543. logger.Infof("%v file visited, %v untracked files found", visitCnt, len(untrackedFiles))
  544. }
  545. }
  546. func (c *Cache) doUploading(pkgs []*uploadingPackage) {
  547. /// 1. 先尝试创建Package
  548. var sucPkgs []*uploadingPackage
  549. var failedPkgs []*uploadingPackage
  550. for _, pkg := range pkgs {
  551. p, err := db.DoTx21(c.db, c.db.Package().TryCreateAll, pkg.bktName, pkg.pkgName)
  552. if err != nil {
  553. logger.Warnf("try create package %v/%v: %v", pkg.bktName, pkg.pkgName, err)
  554. failedPkgs = append(failedPkgs, pkg)
  555. continue
  556. }
  557. pkg.pkg = p
  558. sucPkgs = append(sucPkgs, pkg)
  559. }
  560. /// 2. 对于创建失败的Package,直接关闭文件,不进行上传
  561. // 在锁的保护下取消上传状态
  562. c.lock.Lock()
  563. for _, pkg := range failedPkgs {
  564. for _, obj := range pkg.upObjs {
  565. obj.cache.state.uploading = nil
  566. }
  567. }
  568. c.lock.Unlock()
  569. // 关闭文件必须在锁外
  570. for _, pkg := range failedPkgs {
  571. for _, obj := range pkg.upObjs {
  572. obj.reader.Close()
  573. }
  574. }
  575. /// 3. 开始上传每个Package
  576. for _, p := range sucPkgs {
  577. uploader, err := c.uploader.BeginUpdate(p.pkg.PackageID, 0, nil, nil)
  578. if err != nil {
  579. logger.Warnf("begin update package %v/%v: %v", p.bktName, p.pkgName, err)
  580. // 取消上传状态
  581. c.lock.Lock()
  582. for _, obj := range p.upObjs {
  583. obj.cache.state.uploading = nil
  584. }
  585. c.lock.Unlock()
  586. for _, obj := range p.upObjs {
  587. obj.reader.Close()
  588. }
  589. continue
  590. }
  591. upSuc := 0
  592. upSucAmt := int64(0)
  593. upFailed := 0
  594. upStartTime := time.Now()
  595. logger.Infof("begin uploading %v objects to package %v/%v", len(p.upObjs), p.bktName, p.pkgName)
  596. for _, o := range p.upObjs {
  597. rd := cacheFileReader{
  598. rw: o.reader,
  599. }
  600. counter := io2.Counter(&rd)
  601. err = uploader.Upload(clitypes.JoinObjectPath(o.pathComps[2:]...), counter)
  602. if err != nil {
  603. logger.Warnf("upload object %v: %v", o.pathComps, err)
  604. upFailed++
  605. continue
  606. }
  607. o.isSuccess = true
  608. upSuc++
  609. upSucAmt += counter.Count()
  610. }
  611. // 在锁保护下登记上传结果
  612. c.lock.Lock()
  613. upCancel := 0
  614. upRename := 0
  615. // 检查是否有文件在上传期间发生了变化
  616. var sucObjs []*uploadingObject
  617. for _, o := range p.upObjs {
  618. o.cache.state.uploading = nil
  619. if !o.isSuccess {
  620. continue
  621. }
  622. oldPath := clitypes.JoinObjectPath(o.pathComps[2:]...)
  623. newPath := clitypes.JoinObjectPath(o.cache.pathComps[2:]...)
  624. if o.isDeleted {
  625. uploader.CancelObject(oldPath)
  626. upCancel++
  627. continue
  628. }
  629. // 如果对象移动到了另一个Package,那么也要取消上传
  630. if !lo2.ArrayEquals(o.pathComps[:2], o.cache.pathComps[:2]) {
  631. uploader.CancelObject(oldPath)
  632. upCancel++
  633. continue
  634. }
  635. // 只有仍在同Package内移动的对象才能直接重命名
  636. if newPath != oldPath {
  637. uploader.RenameObject(oldPath, newPath)
  638. upRename++
  639. }
  640. sucObjs = append(sucObjs, o)
  641. }
  642. _, err = uploader.Commit()
  643. if err != nil {
  644. logger.Warnf("commit update package %v/%v: %v", p.bktName, p.pkgName, err)
  645. } else {
  646. for _, obj := range sucObjs {
  647. obj.cache.RevisionUploaded(obj.reader.revision)
  648. }
  649. upTime := time.Since(upStartTime)
  650. logger.Infof("upload package %v/%v in %v, upload: %v, size: %v, speed: %v/s, cancel: %v, rename: %v",
  651. p.bktName, p.pkgName, upTime, upSuc, upSucAmt, bytesize.New(float64(upSucAmt)/upTime.Seconds()), upCancel, upRename)
  652. }
  653. c.lock.Unlock()
  654. // 在Cache锁以外关闭文件。
  655. // 关闭文件会影响refCount,所以无论是上传失败还是上传成功,都会在等待一段时间后才进行下一阶段的操作
  656. for _, obj := range p.upObjs {
  657. obj.reader.Close()
  658. }
  659. }
  660. }
  661. type cacheFileReader struct {
  662. rw *CacheFileHandle
  663. pos int64
  664. }
  665. func (r *cacheFileReader) Read(p []byte) (int, error) {
  666. n, err := r.rw.ReadAt(p, r.pos)
  667. r.pos += int64(n)
  668. if err != nil {
  669. return n, err
  670. }
  671. if n != len(p) {
  672. return n, io.EOF
  673. }
  674. return n, nil
  675. }

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