format_blob_cache.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. package format
  2. import (
  3. "bytes"
  4. "context"
  5. "os"
  6. "path/filepath"
  7. "sync"
  8. "time"
  9. "github.com/pkg/errors"
  10. "github.com/kopia/kopia/internal/atomicfile"
  11. "github.com/kopia/kopia/internal/cache"
  12. "github.com/kopia/kopia/internal/cachedir"
  13. "github.com/kopia/kopia/internal/clock"
  14. "github.com/kopia/kopia/repo/blob"
  15. )
  16. // DefaultRepositoryBlobCacheDuration is the duration for which we treat cached kopia.repository
  17. // as valid.
  18. const DefaultRepositoryBlobCacheDuration = 15 * time.Minute
  19. // blobCache encapsulates cache for format blobs.
  20. // Note that the cache only stores very small number of blobs at the root of the repository,
  21. // usually 1 or 2.
  22. type blobCache interface {
  23. Get(ctx context.Context, blobID blob.ID) ([]byte, time.Time, bool)
  24. Put(ctx context.Context, blobID blob.ID, data []byte) (time.Time, error)
  25. Remove(ctx context.Context, ids []blob.ID)
  26. }
  27. type nullCache struct{}
  28. //nolint:revive
  29. func (nullCache) Get(ctx context.Context, blobID blob.ID) ([]byte, time.Time, bool) {
  30. return nil, time.Time{}, false
  31. }
  32. //nolint:revive
  33. func (nullCache) Put(ctx context.Context, blobID blob.ID, data []byte) (time.Time, error) {
  34. return clock.Now(), nil
  35. }
  36. //nolint:revive
  37. func (nullCache) Remove(ctx context.Context, ids []blob.ID) {
  38. }
  39. type inMemoryCache struct {
  40. timeNow func() time.Time // +checklocksignore
  41. mu sync.Mutex
  42. // +checklocks:mu
  43. data map[blob.ID][]byte
  44. // +checklocks:mu
  45. times map[blob.ID]time.Time
  46. }
  47. func (c *inMemoryCache) Get(_ context.Context, blobID blob.ID) ([]byte, time.Time, bool) {
  48. c.mu.Lock()
  49. defer c.mu.Unlock()
  50. data, ok := c.data[blobID]
  51. if ok {
  52. return data, c.times[blobID], true
  53. }
  54. return nil, time.Time{}, false
  55. }
  56. func (c *inMemoryCache) Put(_ context.Context, blobID blob.ID, data []byte) (time.Time, error) {
  57. c.mu.Lock()
  58. defer c.mu.Unlock()
  59. c.data[blobID] = data
  60. c.times[blobID] = c.timeNow()
  61. return c.times[blobID], nil
  62. }
  63. func (c *inMemoryCache) Remove(_ context.Context, ids []blob.ID) {
  64. c.mu.Lock()
  65. defer c.mu.Unlock()
  66. for _, blobID := range ids {
  67. delete(c.data, blobID)
  68. delete(c.times, blobID)
  69. }
  70. }
  71. type onDiskCache struct {
  72. cacheDirectory string
  73. }
  74. func (c *onDiskCache) Get(_ context.Context, blobID blob.ID) ([]byte, time.Time, bool) {
  75. cachedFile := filepath.Join(c.cacheDirectory, string(blobID))
  76. cst, err := os.Stat(cachedFile)
  77. if err != nil {
  78. return nil, time.Time{}, false
  79. }
  80. cacheMTime := cst.ModTime()
  81. //nolint:gosec
  82. data, err := os.ReadFile(cachedFile)
  83. return data, cacheMTime, err == nil
  84. }
  85. func (c *onDiskCache) Put(_ context.Context, blobID blob.ID, data []byte) (time.Time, error) {
  86. cachedFile := filepath.Join(c.cacheDirectory, string(blobID))
  87. // optimistically assume cache directory exist, create it if not
  88. if err := atomicfile.Write(cachedFile, bytes.NewReader(data)); err != nil {
  89. if err := os.MkdirAll(c.cacheDirectory, cache.DirMode); err != nil && !os.IsExist(err) {
  90. return time.Time{}, errors.Wrap(err, "unable to create cache directory")
  91. }
  92. if err := cachedir.WriteCacheMarker(c.cacheDirectory); err != nil {
  93. return time.Time{}, errors.Wrap(err, "unable to write cache directory marker")
  94. }
  95. if err := atomicfile.Write(cachedFile, bytes.NewReader(data)); err != nil {
  96. return time.Time{}, errors.Wrapf(err, "unable to write to cache: %v", string(blobID))
  97. }
  98. }
  99. cst, err := os.Stat(cachedFile)
  100. if err != nil {
  101. return time.Time{}, errors.Wrap(err, "unable to open cache file")
  102. }
  103. return cst.ModTime(), nil
  104. }
  105. func (c *onDiskCache) Remove(ctx context.Context, ids []blob.ID) {
  106. for _, blobID := range ids {
  107. fname := filepath.Join(c.cacheDirectory, string(blobID))
  108. log(ctx).Infof("deleting %v", fname)
  109. if err := os.Remove(fname); err != nil && !os.IsNotExist(err) {
  110. log(ctx).Debugf("unable to remove cached repository format blob: %v", err)
  111. }
  112. }
  113. }
  114. // NewDiskCache returns on-disk blob cache.
  115. func NewDiskCache(cacheDir string) blobCache {
  116. return &onDiskCache{cacheDir}
  117. }
  118. // NewMemoryBlobCache returns in-memory blob cache.
  119. func NewMemoryBlobCache(timeNow func() time.Time) blobCache {
  120. return &inMemoryCache{
  121. timeNow: timeNow,
  122. data: map[blob.ID][]byte{},
  123. times: map[blob.ID]time.Time{},
  124. }
  125. }
  126. // NewFormatBlobCache creates an implementation of blobCache for particular cache settings.
  127. func NewFormatBlobCache(cacheDir string, validDuration time.Duration, timeNow func() time.Time) blobCache {
  128. if cacheDir != "" {
  129. return NewDiskCache(cacheDir)
  130. }
  131. if validDuration > 0 {
  132. return NewMemoryBlobCache(timeNow)
  133. }
  134. return &nullCache{}
  135. }
  136. var (
  137. _ blobCache = (*nullCache)(nil)
  138. _ blobCache = (*inMemoryCache)(nil)
  139. _ blobCache = (*onDiskCache)(nil)
  140. )