Debian Codegraph @

cache/cache.go

raw
1 /*
2 Copyright The containerd Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package cache
18
19 import (
20 "bytes"
21 "fmt"
22 "io"
23 "os"
24 "path/filepath"
25 "sync"
26
27 "github.com/containerd/stargz-snapshotter/util/cacheutil"
28 "github.com/containerd/stargz-snapshotter/util/namedmutex"
29 "github.com/hashicorp/go-multierror"
30 )
31
32 const (
33 defaultMaxLRUCacheEntry = 10
34 defaultMaxCacheFds = 10
35 )
36
37 type DirectoryCacheConfig struct {
38
39 // Number of entries of LRU cache (default: 10).
40 // This won't be used when DataCache is specified.
41 MaxLRUCacheEntry int
42
43 // Number of file descriptors to cache (default: 10).
44 // This won't be used when FdCache is specified.
45 MaxCacheFds int
46
47 // On Add, wait until the data is fully written to the cache directory.
48 SyncAdd bool
49
50 // DataCache is an on-memory cache of the data.
51 // OnEvicted will be overridden and replaced for internal use.
52 DataCache *cacheutil.LRUCache
53
54 // FdCache is a cache for opened file descriptors.
55 // OnEvicted will be overridden and replaced for internal use.
56 FdCache *cacheutil.LRUCache
57
58 // BufPool will be used for pooling bytes.Buffer.
59 BufPool *sync.Pool
60
61 // Direct forcefully enables direct mode for all operation in cache.
62 // Thus operation won't use on-memory caches.
63 Direct bool
64 }
65
66 // TODO: contents validation.
67
68 // BlobCache represents a cache for bytes data
69 type BlobCache interface {
70 // Add returns a writer to add contents to cache
71 Add(key string, opts ...Option) (Writer, error)
72
73 // Get returns a reader to read the specified contents
74 // from cache
75 Get(key string, opts ...Option) (Reader, error)
76
77 // Close closes the cache
78 Close() error
79 }
80
81 // Reader provides the data cached.
82 type Reader interface {
83 io.ReaderAt
84 Close() error
85 }
86
87 // Writer enables the client to cache byte data. Commit() must be
88 // called after data is fully written to Write(). To abort the written
89 // data, Abort() must be called.
90 type Writer interface {
91 io.WriteCloser
92 Commit() error
93 Abort() error
94 }
95
96 type cacheOpt struct {
97 direct bool
98 }
99
100 type Option func(o *cacheOpt) *cacheOpt
101
102 // Direct option lets FetchAt and Add methods not to use on-memory caches. When
103 // you know that the targeting value won't be used immediately, you can prevent
104 // the limited space of on-memory caches from being polluted by these unimportant
105 // values.
106 func Direct() Option {
107 return func(o *cacheOpt) *cacheOpt {
108 o.direct = true
109 return o
110 }
111 }
112
113 func NewDirectoryCache(directory string, config DirectoryCacheConfig) (BlobCache, error) {
114 if !filepath.IsAbs(directory) {
115 return nil, fmt.Errorf("dir cache path must be an absolute path; got %q", directory)
116 }
117 bufPool := config.BufPool
118 if bufPool == nil {
119 bufPool = &sync.Pool{
120 New: func() interface{} {
121 return new(bytes.Buffer)
122 },
123 }
124 }
125 dataCache := config.DataCache
126 if dataCache == nil {
127 maxEntry := config.MaxLRUCacheEntry
128 if maxEntry == 0 {
129 maxEntry = defaultMaxLRUCacheEntry
130 }
131 dataCache = cacheutil.NewLRUCache(maxEntry)
132 dataCache.OnEvicted = func(key string, value interface{}) {
133 value.(*bytes.Buffer).Reset()
134 bufPool.Put(value)
135 }
136 }
137 fdCache := config.FdCache
138 if fdCache == nil {
139 maxEntry := config.MaxCacheFds
140 if maxEntry == 0 {
141 maxEntry = defaultMaxCacheFds
142 }
143 fdCache = cacheutil.NewLRUCache(maxEntry)
144 fdCache.OnEvicted = func(key string, value interface{}) {
145 value.(*os.File).Close()
146 }
147 }
148 if err := os.MkdirAll(directory, 0700); err != nil {
149 return nil, err
150 }
151 wipdir := filepath.Join(directory, "wip")
152 if err := os.MkdirAll(wipdir, 0700); err != nil {
153 return nil, err
154 }
155 dc := &directoryCache{
156 cache: dataCache,
157 fileCache: fdCache,
158 wipLock: new(namedmutex.NamedMutex),
159 directory: directory,
160 wipDirectory: wipdir,
161 bufPool: bufPool,
162 direct: config.Direct,
163 }
164 dc.syncAdd = config.SyncAdd
165 return dc, nil
166 }
167
168 // directoryCache is a cache implementation which backend is a directory.
169 type directoryCache struct {
170 cache *cacheutil.LRUCache
171 fileCache *cacheutil.LRUCache
172 wipDirectory string
173 directory string
174 wipLock *namedmutex.NamedMutex
175
176 bufPool *sync.Pool
177
178 syncAdd bool
179 direct bool
180
181 closed bool
182 closedMu sync.Mutex
183 }
184
185 func (dc *directoryCache) Get(key string, opts ...Option) (Reader, error) {
186 if dc.isClosed() {
187 return nil, fmt.Errorf("cache is already closed")
188 }
189
190 opt := &cacheOpt{}
191 for _, o := range opts {
192 opt = o(opt)
193 }
194
195 if !dc.direct && !opt.direct {
196 // Get data from memory
197 if b, done, ok := dc.cache.Get(key); ok {
198 return &reader{
199 ReaderAt: bytes.NewReader(b.(*bytes.Buffer).Bytes()),
200 closeFunc: func() error {
201 done()
202 return nil
203 },
204 }, nil
205 }
206
207 // Get data from disk. If the file is already opened, use it.
208 if f, done, ok := dc.fileCache.Get(key); ok {
209 return &reader{
210 ReaderAt: f.(*os.File),
211 closeFunc: func() error {
212 done() // file will be closed when it's evicted from the cache
213 return nil
214 },
215 }, nil
216 }
217 }
218
219 // Open the cache file and read the target region
220 // TODO: If the target cache is write-in-progress, should we wait for the completion
221 // or simply report the cache miss?
222 file, err := os.Open(dc.cachePath(key))
223 if err != nil {
224 return nil, fmt.Errorf("failed to open blob file for %q: %w", key, err)
225 }
226
227 // If "direct" option is specified, do not cache the file on memory.
228 // This option is useful for preventing memory cache from being polluted by data
229 // that won't be accessed immediately.
230 if dc.direct || opt.direct {
231 return &reader{
232 ReaderAt: file,
233 closeFunc: func() error { return file.Close() },
234 }, nil
235 }
236
237 // TODO: should we cache the entire file data on memory?
238 // but making I/O (possibly huge) on every fetching
239 // might be costly.
240 return &reader{
241 ReaderAt: file,
242 closeFunc: func() error {
243 _, done, added := dc.fileCache.Add(key, file)
244 defer done() // Release it immediately. Cleaned up on eviction.
245 if !added {
246 return file.Close() // file already exists in the cache. close it.
247 }
248 return nil
249 },
250 }, nil
251 }
252
253 func (dc *directoryCache) Add(key string, opts ...Option) (Writer, error) {
254 if dc.isClosed() {
255 return nil, fmt.Errorf("cache is already closed")
256 }
257
258 opt := &cacheOpt{}
259 for _, o := range opts {
260 opt = o(opt)
261 }
262
263 wip, err := dc.wipFile(key)
264 if err != nil {
265 return nil, err
266 }
267 w := &writer{
268 WriteCloser: wip,
269 commitFunc: func() error {
270 if dc.isClosed() {
271 return fmt.Errorf("cache is already closed")
272 }
273 // Commit the cache contents
274 c := dc.cachePath(key)
275 if err := os.MkdirAll(filepath.Dir(c), os.ModePerm); err != nil {
276 var allErr error
277 if err := os.Remove(wip.Name()); err != nil {
278 allErr = multierror.Append(allErr, err)
279 }
280 return multierror.Append(allErr,
281 fmt.Errorf("failed to create cache directory %q: %w", c, err))
282 }
283 return os.Rename(wip.Name(), c)
284 },
285 abortFunc: func() error {
286 return os.Remove(wip.Name())
287 },
288 }
289
290 // If "direct" option is specified, do not cache the passed data on memory.
291 // This option is useful for preventing memory cache from being polluted by data
292 // that won't be accessed immediately.
293 if dc.direct || opt.direct {
294 return w, nil
295 }
296
297 b := dc.bufPool.Get().(*bytes.Buffer)
298 memW := &writer{
299 WriteCloser: nopWriteCloser(io.Writer(b)),
300 commitFunc: func() error {
301 if dc.isClosed() {
302 w.Close()
303 return fmt.Errorf("cache is already closed")
304 }
305 cached, done, added := dc.cache.Add(key, b)
306 if !added {
307 dc.putBuffer(b) // already exists in the cache. abort it.
308 }
309 commit := func() error {
310 defer done()
311 defer w.Close()
312 n, err := w.Write(cached.(*bytes.Buffer).Bytes())
313 if err != nil || n != cached.(*bytes.Buffer).Len() {
314 w.Abort()
315 return err
316 }
317 return w.Commit()
318 }
319 if dc.syncAdd {
320 return commit()
321 }
322 go func() {
323 if err := commit(); err != nil {
324 fmt.Println("failed to commit to file:", err)
325 }
326 }()
327 return nil
328 },
329 abortFunc: func() error {
330 defer w.Close()
331 defer w.Abort()
332 dc.putBuffer(b) // abort it.
333 return nil
334 },
335 }
336
337 return memW, nil
338 }
339
340 func (dc *directoryCache) putBuffer(b *bytes.Buffer) {
341 b.Reset()
342 dc.bufPool.Put(b)
343 }
344
345 func (dc *directoryCache) Close() error {
346 dc.closedMu.Lock()
347 defer dc.closedMu.Unlock()
348 if dc.closed {
349 return nil
350 }
351 dc.closed = true
352 return os.RemoveAll(dc.directory)
353 }
354
355 func (dc *directoryCache) isClosed() bool {
356 dc.closedMu.Lock()
357 closed := dc.closed
358 dc.closedMu.Unlock()
359 return closed
360 }
361
362 func (dc *directoryCache) cachePath(key string) string {
363 return filepath.Join(dc.directory, key[:2], key)
364 }
365
366 func (dc *directoryCache) wipFile(key string) (*os.File, error) {
367 return os.CreateTemp(dc.wipDirectory, key+"-*")
368 }
369
370 func NewMemoryCache() BlobCache {
371 return &MemoryCache{
372 Membuf: map[string]*bytes.Buffer{},
373 }
374 }
375
376 // MemoryCache is a cache implementation which backend is a memory.
377 type MemoryCache struct {
378 Membuf map[string]*bytes.Buffer
379 mu sync.Mutex
380 }
381
382 func (mc *MemoryCache) Get(key string, opts ...Option) (Reader, error) {
383 mc.mu.Lock()
384 defer mc.mu.Unlock()
385 b, ok := mc.Membuf[key]
386 if !ok {
387 return nil, fmt.Errorf("Missed cache: %q", key)
388 }
389 return &reader{bytes.NewReader(b.Bytes()), func() error { return nil }}, nil
390 }
391
392 func (mc *MemoryCache) Add(key string, opts ...Option) (Writer, error) {
393 b := new(bytes.Buffer)
394 return &writer{
395 WriteCloser: nopWriteCloser(io.Writer(b)),
396 commitFunc: func() error {
397 mc.mu.Lock()
398 defer mc.mu.Unlock()
399 mc.Membuf[key] = b
400 return nil
401 },
402 abortFunc: func() error { return nil },
403 }, nil
404 }
405
406 func (mc *MemoryCache) Close() error {
407 return nil
408 }
409
410 type reader struct {
411 io.ReaderAt
412 closeFunc func() error
413 }
414
415 func (r *reader) Close() error { return r.closeFunc() }
416
417 type writer struct {
418 io.WriteCloser
419 commitFunc func() error
420 abortFunc func() error
421 }
422
423 func (w *writer) Commit() error {
424 return w.commitFunc()
425 }
426
427 func (w *writer) Abort() error {
428 return w.abortFunc()
429 }
430
431 type writeCloser struct {
432 io.Writer
433 closeFunc func() error
434 }
435
436 func (w *writeCloser) Close() error { return w.closeFunc() }
437
438 func nopWriteCloser(w io.Writer) io.WriteCloser {
439 return &writeCloser{w, func() error { return nil }}
440 }