forked from keybase/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
disk_md_cache.go
485 lines (438 loc) · 12.5 KB
/
disk_md_cache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
// Copyright 2018 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package libkbfs
import (
"context"
"io"
"path/filepath"
"sync"
"time"
"github.com/keybase/client/go/kbfs/kbfsmd"
"github.com/keybase/client/go/kbfs/tlf"
"github.com/keybase/client/go/logger"
"github.com/pkg/errors"
ldberrors "github.com/syndtr/goleveldb/leveldb/errors"
"github.com/syndtr/goleveldb/leveldb/opt"
"github.com/syndtr/goleveldb/leveldb/storage"
)
const (
headsDbFilename string = "diskCacheMDHeads.leveldb"
initialDiskMDCacheVersion uint64 = 1
currentDiskMDCacheVersion uint64 = initialDiskMDCacheVersion
defaultMDCacheTableSize int = 50 * opt.MiB
mdCacheFolderName string = "kbfs_md_cache"
)
// diskMDCacheConfig specifies the interfaces that a DiskMDCacheStandard
// needs to perform its functions. This adheres to the standard libkbfs Config
// API.
type diskMDCacheConfig interface {
codecGetter
logMaker
}
type diskMDBlock struct {
// Exported only for serialization.
Buf []byte
Ver kbfsmd.MetadataVer
Time time.Time
Revision kbfsmd.Revision
}
// DiskMDCacheLocal is the standard implementation for DiskMDCache.
type DiskMDCacheLocal struct {
config diskMDCacheConfig
log logger.Logger
// Track the cache hit rate and eviction rate
hitMeter *CountMeter
missMeter *CountMeter
putMeter *CountMeter
// Protect the disk caches from being shutdown while they're being
// accessed, and mutable data.
lock sync.RWMutex
headsDb *levelDb // tlfID -> metadata block
tlfsCached map[tlf.ID]kbfsmd.Revision
tlfsStaged map[tlf.ID][]diskMDBlock
startedCh chan struct{}
startErrCh chan struct{}
shutdownCh chan struct{}
closer func()
}
var _ DiskMDCache = (*DiskMDCacheLocal)(nil)
// DiskMDCacheStartState represents whether this disk MD cache has
// started or failed.
type DiskMDCacheStartState int
// String allows DiskMDCacheStartState to be output as a string.
func (s DiskMDCacheStartState) String() string {
switch s {
case DiskMDCacheStartStateStarting:
return "starting"
case DiskMDCacheStartStateStarted:
return "started"
case DiskMDCacheStartStateFailed:
return "failed"
default:
return "unknown"
}
}
const (
// DiskMDCacheStartStateStarting represents when the cache is starting.
DiskMDCacheStartStateStarting DiskMDCacheStartState = iota
// DiskMDCacheStartStateStarted represents when the cache has started.
DiskMDCacheStartStateStarted
// DiskMDCacheStartStateFailed represents when the cache has failed to
// start.
DiskMDCacheStartStateFailed
)
// DiskMDCacheStatus represents the status of the MD cache.
type DiskMDCacheStatus struct {
StartState DiskMDCacheStartState
NumMDs uint64
NumStaged uint64
Hits MeterStatus
Misses MeterStatus
Puts MeterStatus
}
// newDiskMDCacheLocalFromStorage creates a new *DiskMDCacheLocal
// with the passed-in storage.Storage interfaces as storage layers for each
// cache.
func newDiskMDCacheLocalFromStorage(
config diskMDCacheConfig, headsStorage storage.Storage) (
cache *DiskMDCacheLocal, err error) {
log := config.MakeLogger("DMC")
closers := make([]io.Closer, 0, 1)
closer := func() {
for _, c := range closers {
closeErr := c.Close()
if closeErr != nil {
log.Warning("Error closing leveldb or storage: %+v", closeErr)
}
}
}
defer func() {
if err != nil {
err = errors.WithStack(err)
closer()
}
}()
mdDbOptions := *leveldbOptions
mdDbOptions.CompactionTableSize = defaultMDCacheTableSize
headsDb, err := openLevelDBWithOptions(headsStorage, &mdDbOptions)
if err != nil {
return nil, err
}
closers = append(closers, headsDb)
startedCh := make(chan struct{})
startErrCh := make(chan struct{})
cache = &DiskMDCacheLocal{
config: config,
hitMeter: NewCountMeter(),
missMeter: NewCountMeter(),
putMeter: NewCountMeter(),
log: log,
headsDb: headsDb,
tlfsStaged: make(map[tlf.ID][]diskMDBlock),
startedCh: startedCh,
startErrCh: startErrCh,
shutdownCh: make(chan struct{}),
closer: closer,
}
// Sync the MD counts asynchronously so syncing doesn't block init.
// Since this method blocks, any Get or Put requests to the disk MD
// cache will block until this is done. The log will contain the beginning
// and end of this sync.
go func() {
err := cache.syncMDCountsFromDb()
if err != nil {
close(startErrCh)
closer()
log.Warning("Disabling disk MD cache due to error syncing the "+
"MD counts from DB: %+v", err)
return
}
close(startedCh)
}()
return cache, nil
}
// newDiskMDCacheLocal creates a new *DiskMDCacheLocal with a
// specified directory on the filesystem as storage.
func newDiskMDCacheLocal(
config diskBlockCacheConfig, dirPath string) (
cache *DiskMDCacheLocal, err error) {
log := config.MakeLogger("DMC")
defer func() {
if err != nil {
log.Error("Error initializing MD cache: %+v", err)
}
}()
cachePath := filepath.Join(dirPath, mdCacheFolderName)
versionPath, err := getVersionedPathForDiskCache(
log, cachePath, "md", currentDiskMDCacheVersion)
if err != nil {
return nil, err
}
headsDbPath := filepath.Join(versionPath, headsDbFilename)
headsStorage, err := storage.OpenFile(headsDbPath, false)
if err != nil {
return nil, err
}
defer func() {
if err != nil {
headsStorage.Close()
}
}()
return newDiskMDCacheLocalFromStorage(config, headsStorage)
}
// WaitUntilStarted waits until this cache has started.
func (cache *DiskMDCacheLocal) WaitUntilStarted() error {
select {
case <-cache.startedCh:
return nil
case <-cache.startErrCh:
return DiskMDCacheError{"error starting channel"}
}
}
func (cache *DiskMDCacheLocal) syncMDCountsFromDb() error {
cache.log.Debug("+ syncMDCountsFromDb begin")
defer cache.log.Debug("- syncMDCountsFromDb end")
// We take a write lock for this to prevent any reads from happening while
// we're syncing the MD counts.
cache.lock.Lock()
defer cache.lock.Unlock()
tlfsCached := make(map[tlf.ID]kbfsmd.Revision)
iter := cache.headsDb.NewIterator(nil, nil)
defer iter.Release()
for iter.Next() {
var tlfID tlf.ID
err := tlfID.UnmarshalBinary(iter.Key())
if err != nil {
return err
}
var md diskMDBlock
err = cache.config.Codec().Decode(iter.Value(), &md)
if err != nil {
return err
}
tlfsCached[tlfID] = md.Revision
}
cache.tlfsCached = tlfsCached
return nil
}
// getMetadataLocked retrieves the metadata for a block in the cache, or
// returns leveldb.ErrNotFound and a zero-valued metadata otherwise.
func (cache *DiskMDCacheLocal) getMetadataLocked(
tlfID tlf.ID, metered bool) (metadata diskMDBlock, err error) {
var hitMeter, missMeter *CountMeter
if metered {
hitMeter = cache.hitMeter
missMeter = cache.missMeter
}
metadataBytes, err := cache.headsDb.GetWithMeter(
tlfID.Bytes(), hitMeter, missMeter)
if err != nil {
return diskMDBlock{}, err
}
err = cache.config.Codec().Decode(metadataBytes, &metadata)
if err != nil {
return diskMDBlock{}, err
}
return metadata, nil
}
// checkAndLockCache checks whether the cache is started.
func (cache *DiskMDCacheLocal) checkCacheLocked(
ctx context.Context, method string) error {
// First see if the context has expired since we began.
select {
case <-ctx.Done():
return ctx.Err()
default:
}
select {
case <-cache.startedCh:
case <-cache.startErrCh:
// The cache will never be started. No need for a stack here since this
// could happen anywhere.
return DiskCacheStartingError{method}
default:
// If the cache hasn't started yet, return an error. No need for a
// stack here since this could happen anywhere.
return DiskCacheStartingError{method}
}
// shutdownCh has to be checked under lock, otherwise we can race.
select {
case <-cache.shutdownCh:
return errors.WithStack(DiskCacheClosedError{method})
default:
}
if cache.headsDb == nil {
return errors.WithStack(DiskCacheClosedError{method})
}
return nil
}
// Get implements the DiskMDCache interface for DiskMDCacheLocal.
func (cache *DiskMDCacheLocal) Get(
ctx context.Context, tlfID tlf.ID) (
buf []byte, ver kbfsmd.MetadataVer, timestamp time.Time, err error) {
cache.lock.RLock()
defer cache.lock.RUnlock()
err = cache.checkCacheLocked(ctx, "MD(Get)")
if err != nil {
return nil, -1, time.Time{}, err
}
if _, ok := cache.tlfsCached[tlfID]; !ok {
cache.missMeter.Mark(1)
return nil, -1, time.Time{}, errors.WithStack(ldberrors.ErrNotFound)
}
md, err := cache.getMetadataLocked(tlfID, metered)
if err != nil {
return nil, -1, time.Time{}, err
}
return md.Buf, md.Ver, md.Time, nil
}
// Stage implements the DiskMDCache interface for DiskMDCacheLocal.
func (cache *DiskMDCacheLocal) Stage(
ctx context.Context, tlfID tlf.ID, rev kbfsmd.Revision, buf []byte,
ver kbfsmd.MetadataVer, timestamp time.Time) error {
cache.lock.Lock()
defer cache.lock.Unlock()
err := cache.checkCacheLocked(ctx, "MD(Stage)")
if err != nil {
return err
}
if cachedRev, ok := cache.tlfsCached[tlfID]; ok && cachedRev >= rev {
// Ignore stages for older revisions
return nil
}
md := diskMDBlock{
Buf: buf,
Ver: ver,
Time: timestamp,
Revision: rev,
}
cache.tlfsStaged[tlfID] = append(cache.tlfsStaged[tlfID], md)
return nil
}
// Commit implements the DiskMDCache interface for DiskMDCacheLocal.
func (cache *DiskMDCacheLocal) Commit(
ctx context.Context, tlfID tlf.ID, rev kbfsmd.Revision) error {
cache.lock.Lock()
defer cache.lock.Unlock()
err := cache.checkCacheLocked(ctx, "MD(Commit)")
if err != nil {
return err
}
stagedMDs := cache.tlfsStaged[tlfID]
if len(stagedMDs) == 0 {
// Nothing to do.
return nil
}
newStagedMDs := make([]diskMDBlock, 0, len(stagedMDs)-1)
foundMD := false
// The staged MDs list is unordered, so iterate through the whole
// thing to find what should remain after commiting `rev`.
for _, md := range stagedMDs {
if md.Revision > rev {
newStagedMDs = append(newStagedMDs, md)
continue
} else if md.Revision < rev {
continue
} else if foundMD {
// Duplicate.
continue
}
foundMD = true
encodedMetadata, err := cache.config.Codec().Encode(&md)
if err != nil {
return err
}
err = cache.headsDb.PutWithMeter(
tlfID.Bytes(), encodedMetadata, cache.putMeter)
if err != nil {
return err
}
}
if !foundMD {
// Nothing to do.
return nil
}
cache.tlfsCached[tlfID] = rev
if len(newStagedMDs) == 0 {
delete(cache.tlfsStaged, tlfID)
} else {
cache.tlfsStaged[tlfID] = newStagedMDs
}
return nil
}
// Unstage implements the DiskMDCache interface for DiskMDCacheLocal.
func (cache *DiskMDCacheLocal) Unstage(
ctx context.Context, tlfID tlf.ID, rev kbfsmd.Revision) error {
cache.lock.Lock()
defer cache.lock.Unlock()
err := cache.checkCacheLocked(ctx, "MD(Unstage)")
if err != nil {
return err
}
// Just remove the first one matching `rev`.
stagedMDs := cache.tlfsStaged[tlfID]
for i, md := range stagedMDs {
if md.Revision == rev {
if len(stagedMDs) == 1 {
delete(cache.tlfsStaged, tlfID)
} else {
cache.tlfsStaged[tlfID] = append(
stagedMDs[:i], stagedMDs[i+1:]...)
}
return nil
}
}
return nil
}
// Status implements the DiskMDCache interface for DiskMDCacheLocal.
func (cache *DiskMDCacheLocal) Status(_ context.Context) DiskMDCacheStatus {
select {
case <-cache.startedCh:
case <-cache.startErrCh:
return DiskMDCacheStatus{StartState: DiskMDCacheStartStateFailed}
default:
return DiskMDCacheStatus{StartState: DiskMDCacheStartStateStarting}
}
cache.lock.RLock()
defer cache.lock.RUnlock()
numStaged := uint64(0)
for _, mds := range cache.tlfsStaged {
numStaged += uint64(len(mds))
}
return DiskMDCacheStatus{
StartState: DiskMDCacheStartStateStarted,
NumMDs: uint64(len(cache.tlfsCached)),
NumStaged: numStaged,
Hits: rateMeterToStatus(cache.hitMeter),
Misses: rateMeterToStatus(cache.missMeter),
Puts: rateMeterToStatus(cache.putMeter),
}
}
// Shutdown implements the DiskMDCache interface for DiskMDCacheLocal.
func (cache *DiskMDCacheLocal) Shutdown(ctx context.Context) {
// Wait for the cache to either finish starting or error.
select {
case <-cache.startedCh:
case <-cache.startErrCh:
return
}
cache.lock.Lock()
defer cache.lock.Unlock()
// shutdownCh has to be checked under lock, otherwise we can race.
select {
case <-cache.shutdownCh:
cache.log.CWarningf(ctx, "Shutdown called more than once")
return
default:
}
close(cache.shutdownCh)
if cache.headsDb == nil {
return
}
cache.closer()
cache.headsDb = nil
cache.hitMeter.Shutdown()
cache.missMeter.Shutdown()
cache.putMeter.Shutdown()
}