-
Notifications
You must be signed in to change notification settings - Fork 467
/
file_cache.go
1337 lines (1201 loc) · 39 KB
/
file_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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020 The LevelDB-Go and Pebble Authors. All rights reserved. Use
// of this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
package pebble
import (
"bytes"
"context"
"fmt"
"io"
"runtime/debug"
"sync"
"sync/atomic"
"unsafe"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/pebble/internal/base"
"github.com/cockroachdb/pebble/internal/cache"
"github.com/cockroachdb/pebble/internal/invariants"
"github.com/cockroachdb/pebble/internal/keyspan"
"github.com/cockroachdb/pebble/internal/keyspan/keyspanimpl"
"github.com/cockroachdb/pebble/internal/manifest"
"github.com/cockroachdb/pebble/internal/sstableinternal"
"github.com/cockroachdb/pebble/objstorage"
"github.com/cockroachdb/pebble/objstorage/objstorageprovider/objiotracing"
"github.com/cockroachdb/pebble/sstable"
"github.com/cockroachdb/pebble/sstable/valblk"
)
var emptyIter = &errorIter{err: nil}
var emptyKeyspanIter = &errorKeyspanIter{err: nil}
// tableNewIters creates new iterators (point, range deletion and/or range key)
// for the given file metadata. Which of the various iterator kinds the user is
// requesting is specified with the iterKinds bitmap.
//
// On success, the requested subset of iters.{point,rangeDel,rangeKey} are
// populated with iterators.
//
// If a point iterator is requested and the operation was successful,
// iters.point is guaranteed to be non-nil and must be closed when the caller is
// finished.
//
// If a range deletion or range key iterator is requested, the corresponding
// iterator may be nil if the table does not contain any keys of the
// corresponding kind. The returned iterSet type provides RangeDeletion() and
// RangeKey() convenience methods that return non-nil empty iterators that may
// be used if the caller requires a non-nil iterator.
//
// On error, all iterators are nil.
//
// The only (non-test) implementation of tableNewIters is
// fileCacheContainer.newIters().
type tableNewIters func(
ctx context.Context,
file *manifest.FileMetadata,
opts *IterOptions,
internalOpts internalIterOpts,
kinds iterKinds,
) (iterSet, error)
// tableNewRangeDelIter takes a tableNewIters and returns a TableNewSpanIter
// for the rangedel iterator returned by tableNewIters.
func tableNewRangeDelIter(newIters tableNewIters) keyspanimpl.TableNewSpanIter {
return func(ctx context.Context, file *manifest.FileMetadata, iterOptions keyspan.SpanIterOptions) (keyspan.FragmentIterator, error) {
iters, err := newIters(ctx, file, nil, internalIterOpts{}, iterRangeDeletions)
if err != nil {
return nil, err
}
return iters.RangeDeletion(), nil
}
}
// tableNewRangeKeyIter takes a tableNewIters and returns a TableNewSpanIter
// for the range key iterator returned by tableNewIters.
func tableNewRangeKeyIter(newIters tableNewIters) keyspanimpl.TableNewSpanIter {
return func(ctx context.Context, file *manifest.FileMetadata, iterOptions keyspan.SpanIterOptions) (keyspan.FragmentIterator, error) {
iters, err := newIters(ctx, file, nil, internalIterOpts{}, iterRangeKeys)
if err != nil {
return nil, err
}
return iters.RangeKey(), nil
}
}
// fileCacheOpts contains the db specific fields of a file cache. This is stored
// in the fileCacheContainer along with the file cache.
//
// NB: It is important to make sure that the fields in this struct are
// read-only. Since the fields here are shared by every single fileCacheShard,
// if non read-only fields are updated, we could have unnecessary evictions of
// those fields, and the surrounding fields from the CPU caches.
type fileCacheOpts struct {
// iterCount keeps track of how many iterators are open. It is used to keep
// track of leaked iterators on a per-db level.
iterCount *atomic.Int32
loggerAndTracer LoggerAndTracer
cache *cache.Cache
cacheID cache.ID
objProvider objstorage.Provider
readerOpts sstable.ReaderOptions
sstStatsCollector *sstable.CategoryStatsCollector
}
// fileCacheContainer contains the file cache and fields which are unique to the
// DB.
type fileCacheContainer struct {
fileCache *FileCache
// dbOpts contains fields relevant to the file cache which are unique to
// each DB.
dbOpts fileCacheOpts
}
// newFileCacheContainer will panic if the underlying block cache in the file
// cache doesn't match Options.Cache.
func newFileCacheContainer(
fc *FileCache,
cacheID cache.ID,
objProvider objstorage.Provider,
opts *Options,
size int,
sstStatsCollector *sstable.CategoryStatsCollector,
) *fileCacheContainer {
// We will release a ref to the file cache acquired here when
// fileCacheContainer.close is called.
if fc != nil {
if fc.cache != opts.Cache {
panic("pebble: underlying cache for the file cache and db are different")
}
fc.Ref()
} else {
// NewFileCache should create a ref to fc which the container should
// drop whenever it is closed.
fc = NewFileCache(opts.Cache, opts.Experimental.FileCacheShards, size)
}
t := &fileCacheContainer{}
t.fileCache = fc
t.dbOpts.loggerAndTracer = opts.LoggerAndTracer
t.dbOpts.cache = opts.Cache
t.dbOpts.cacheID = cacheID
t.dbOpts.objProvider = objProvider
t.dbOpts.readerOpts = opts.MakeReaderOptions()
t.dbOpts.readerOpts.FilterMetricsTracker = &sstable.FilterMetricsTracker{}
t.dbOpts.iterCount = new(atomic.Int32)
t.dbOpts.sstStatsCollector = sstStatsCollector
return t
}
// Before calling close, make sure that there will be no further need
// to access any of the files associated with the store.
func (c *fileCacheContainer) close() error {
// We want to do some cleanup work here. Check for leaked iterators
// by the DB using this container. Note that we'll still perform cleanup
// below in the case that there are leaked iterators.
var err error
if v := c.dbOpts.iterCount.Load(); v > 0 {
err = errors.Errorf("leaked iterators: %d", errors.Safe(v))
}
// Release nodes here.
for _, shard := range c.fileCache.shards {
if shard != nil {
shard.removeDB(&c.dbOpts)
}
}
return firstError(err, c.fileCache.Unref())
}
func (c *fileCacheContainer) newIters(
ctx context.Context,
file *manifest.FileMetadata,
opts *IterOptions,
internalOpts internalIterOpts,
kinds iterKinds,
) (iterSet, error) {
return c.fileCache.getShard(file.FileBacking.DiskFileNum).newIters(ctx, file, opts, internalOpts, &c.dbOpts, kinds)
}
// getTableProperties returns the properties associated with the backing physical
// table if the input metadata belongs to a virtual sstable.
func (c *fileCacheContainer) getTableProperties(file *fileMetadata) (*sstable.Properties, error) {
return c.fileCache.getShard(file.FileBacking.DiskFileNum).getTableProperties(file, &c.dbOpts)
}
func (c *fileCacheContainer) evict(fileNum base.DiskFileNum) {
c.fileCache.getShard(fileNum).evict(fileNum, &c.dbOpts, false)
}
func (c *fileCacheContainer) metrics() (CacheMetrics, FilterMetrics) {
var m CacheMetrics
for i := range c.fileCache.shards {
s := c.fileCache.shards[i]
s.mu.RLock()
m.Count += int64(len(s.mu.nodes))
s.mu.RUnlock()
m.Hits += s.hits.Load()
m.Misses += s.misses.Load()
}
m.Size = m.Count * int64(unsafe.Sizeof(fileCacheNode{})+unsafe.Sizeof(fileCacheValue{})+unsafe.Sizeof(sstable.Reader{}))
f := c.dbOpts.readerOpts.FilterMetricsTracker.Load()
return m, f
}
func (c *fileCacheContainer) estimateSize(
meta *fileMetadata, lower, upper []byte,
) (size uint64, err error) {
c.withCommonReader(meta, func(cr sstable.CommonReader) error {
size, err = cr.EstimateDiskUsage(lower, upper)
return err
})
return size, err
}
// createCommonReader creates a Reader for this file.
func createCommonReader(v *fileCacheValue, file *fileMetadata) sstable.CommonReader {
// TODO(bananabrick): We suffer an allocation if file is a virtual sstable.
var cr sstable.CommonReader = v.reader
if file.Virtual {
virtualReader := sstable.MakeVirtualReader(
v.reader, file.VirtualMeta().VirtualReaderParams(v.isShared),
)
cr = &virtualReader
}
return cr
}
func (c *fileCacheContainer) withCommonReader(
meta *fileMetadata, fn func(sstable.CommonReader) error,
) error {
s := c.fileCache.getShard(meta.FileBacking.DiskFileNum)
v := s.findNode(context.TODO(), meta.FileBacking, &c.dbOpts)
defer s.unrefValue(v)
if v.err != nil {
return v.err
}
return fn(createCommonReader(v, meta))
}
func (c *fileCacheContainer) withReader(meta physicalMeta, fn func(*sstable.Reader) error) error {
s := c.fileCache.getShard(meta.FileBacking.DiskFileNum)
v := s.findNode(context.TODO(), meta.FileBacking, &c.dbOpts)
defer s.unrefValue(v)
if v.err != nil {
return v.err
}
return fn(v.reader)
}
// withVirtualReader fetches a VirtualReader associated with a virtual sstable.
func (c *fileCacheContainer) withVirtualReader(
meta virtualMeta, fn func(sstable.VirtualReader) error,
) error {
s := c.fileCache.getShard(meta.FileBacking.DiskFileNum)
v := s.findNode(context.TODO(), meta.FileBacking, &c.dbOpts)
defer s.unrefValue(v)
if v.err != nil {
return v.err
}
provider := c.dbOpts.objProvider
objMeta, err := provider.Lookup(fileTypeTable, meta.FileBacking.DiskFileNum)
if err != nil {
return err
}
return fn(sstable.MakeVirtualReader(v.reader, meta.VirtualReaderParams(objMeta.IsShared())))
}
func (c *fileCacheContainer) iterCount() int64 {
return int64(c.dbOpts.iterCount.Load())
}
// FileCache is a shareable cache for open files. Open files are exclusively
// sstable files today.
type FileCache struct {
refs atomic.Int64
cache *Cache
shards []*fileCacheShard
}
// Ref adds a reference to the file cache. Once a file cache is constructed, the
// cache only remains valid if there is at least one reference to it.
func (c *FileCache) Ref() {
v := c.refs.Add(1)
// We don't want the reference count to ever go from 0 -> 1,
// cause a reference count of 0 implies that we've closed the cache.
if v <= 1 {
panic(fmt.Sprintf("pebble: inconsistent reference count: %d", v))
}
}
// Unref removes a reference to the file cache.
func (c *FileCache) Unref() error {
v := c.refs.Add(-1)
switch {
case v < 0:
panic(fmt.Sprintf("pebble: inconsistent reference count: %d", v))
case v == 0:
var err error
for i := range c.shards {
// The cache shard is not allocated yet, nothing to close.
if c.shards[i] == nil {
continue
}
err = firstError(err, c.shards[i].Close())
}
// Unref the cache which we create a reference to when the file cache is
// first instantiated.
c.cache.Unref()
return err
}
return nil
}
// NewFileCache will create a new file cache with one outstanding reference. It
// is the callers responsibility to call Unref if they will no longer hold a
// reference to the file cache.
func NewFileCache(cache *Cache, numShards int, size int) *FileCache {
if size == 0 {
panic("pebble: cannot create a file cache of size 0")
} else if numShards == 0 {
panic("pebble: cannot create a file cache with 0 shards")
}
c := &FileCache{}
c.cache = cache
c.cache.Ref()
c.shards = make([]*fileCacheShard, numShards)
for i := range c.shards {
c.shards[i] = &fileCacheShard{}
c.shards[i].init(size / len(c.shards))
}
// Hold a ref to the cache here.
c.refs.Store(1)
return c
}
func (c *FileCache) getShard(fileNum base.DiskFileNum) *fileCacheShard {
return c.shards[uint64(fileNum)%uint64(len(c.shards))]
}
type fileCacheKey struct {
cacheID cache.ID
fileNum base.DiskFileNum
}
type fileCacheShard struct {
hits atomic.Int64
misses atomic.Int64
iterCount atomic.Int32
size int
mu struct {
sync.RWMutex
nodes map[fileCacheKey]*fileCacheNode
// The iters map is only created and populated in race builds.
iters map[io.Closer][]byte
handHot *fileCacheNode
handCold *fileCacheNode
handTest *fileCacheNode
coldTarget int
sizeHot int
sizeCold int
sizeTest int
}
releasing sync.WaitGroup
releasingCh chan *fileCacheValue
releaseLoopExit sync.WaitGroup
}
func (c *fileCacheShard) init(size int) {
c.size = size
c.mu.nodes = make(map[fileCacheKey]*fileCacheNode)
c.mu.coldTarget = size
c.releasingCh = make(chan *fileCacheValue, 100)
c.releaseLoopExit.Add(1)
go c.releaseLoop()
if invariants.RaceEnabled {
c.mu.iters = make(map[io.Closer][]byte)
}
}
func (c *fileCacheShard) releaseLoop() {
defer c.releaseLoopExit.Done()
for v := range c.releasingCh {
v.release(c)
}
}
// checkAndIntersectFilters checks the specific table and block property filters
// for intersection with any available table and block-level properties. Returns
// true for ok if this table should be read by this iterator.
func (c *fileCacheShard) checkAndIntersectFilters(
v *fileCacheValue,
blockPropertyFilters []BlockPropertyFilter,
boundLimitedFilter sstable.BoundLimitedBlockPropertyFilter,
syntheticSuffix sstable.SyntheticSuffix,
) (ok bool, filterer *sstable.BlockPropertiesFilterer, err error) {
if boundLimitedFilter != nil || len(blockPropertyFilters) > 0 {
filterer, err = sstable.IntersectsTable(
blockPropertyFilters,
boundLimitedFilter,
v.reader.Properties.UserProperties,
syntheticSuffix,
)
// NB: IntersectsTable will return a nil filterer if the table-level
// properties indicate there's no intersection with the provided filters.
if filterer == nil || err != nil {
return false, nil, err
}
}
return true, filterer, nil
}
func (c *fileCacheShard) newIters(
ctx context.Context,
file *manifest.FileMetadata,
opts *IterOptions,
internalOpts internalIterOpts,
dbOpts *fileCacheOpts,
kinds iterKinds,
) (iterSet, error) {
// TODO(sumeer): constructing the Reader should also use a plumbed context,
// since parts of the sstable are read during the construction. The Reader
// should not remember that context since the Reader can be long-lived.
// Calling findNode gives us the responsibility of decrementing v's
// refCount. If opening the underlying table resulted in error, then we
// decrement this straight away. Otherwise, we pass that responsibility to
// the sstable iterator, which decrements when it is closed.
v := c.findNode(ctx, file.FileBacking, dbOpts)
if v.err != nil {
defer c.unrefValue(v)
return iterSet{}, v.err
}
// Note: This suffers an allocation for virtual sstables.
cr := createCommonReader(v, file)
var iters iterSet
var err error
if kinds.RangeKey() && file.HasRangeKeys {
iters.rangeKey, err = c.newRangeKeyIter(ctx, v, file, cr, opts.SpanIterOptions())
}
if kinds.RangeDeletion() && file.HasPointKeys && err == nil {
iters.rangeDeletion, err = c.newRangeDelIter(ctx, file, cr, dbOpts)
}
if kinds.Point() && err == nil {
iters.point, err = c.newPointIter(ctx, v, file, cr, opts, internalOpts, dbOpts)
}
if err != nil {
// NB: There's a subtlety here: Because the point iterator is the last
// iterator we attempt to create, it's not possible for:
// err != nil && iters.point != nil
// If it were possible, we'd need to account for it to avoid double
// unref-ing here, once during CloseAll and once during `unrefValue`.
iters.CloseAll()
c.unrefValue(v)
return iterSet{}, err
}
// Only point iterators ever require the reader stay pinned in the cache. If
// we're not returning a point iterator to the caller, we need to unref v.
if iters.point == nil {
c.unrefValue(v)
}
return iters, nil
}
// For flushable ingests, we decide whether to use the bloom filter base on
// size.
const filterBlockSizeLimitForFlushableIngests = 64 * 1024
// newPointIter is an internal helper that constructs a point iterator over a
// sstable. This function is for internal use only, and callers should use
// newIters instead.
func (c *fileCacheShard) newPointIter(
ctx context.Context,
v *fileCacheValue,
file *manifest.FileMetadata,
cr sstable.CommonReader,
opts *IterOptions,
internalOpts internalIterOpts,
dbOpts *fileCacheOpts,
) (internalIterator, error) {
var (
hideObsoletePoints bool = false
pointKeyFilters []BlockPropertyFilter
filterer *sstable.BlockPropertiesFilterer
)
if opts != nil {
// This code is appending (at most one filter) in-place to
// opts.PointKeyFilters even though the slice is shared for iterators in
// the same iterator tree. This is acceptable since all the following
// properties are true:
// - The iterator tree is single threaded, so the shared backing for the
// slice is being mutated in a single threaded manner.
// - Each shallow copy of the slice has its own notion of length.
// - The appended element is always the obsoleteKeyBlockPropertyFilter
// struct, which is stateless, so overwriting that struct when creating
// one sstable iterator is harmless to other sstable iterators that are
// relying on that struct.
//
// An alternative would be to have different slices for different sstable
// iterators, but that requires more work to avoid allocations.
//
// TODO(bilal): for compaction reads of foreign sstables, we do hide
// obsolete points (see sstable.Reader.newCompactionIter) but we don't
// apply the obsolete block property filter. We could optimize this by
// applying the filter.
hideObsoletePoints, pointKeyFilters =
v.reader.TryAddBlockPropertyFilterForHideObsoletePoints(
opts.snapshotForHideObsoletePoints, file.LargestSeqNum, opts.PointKeyFilters)
var ok bool
var err error
ok, filterer, err = c.checkAndIntersectFilters(v, pointKeyFilters,
internalOpts.boundLimitedFilter, file.SyntheticPrefixAndSuffix.Suffix())
if err != nil {
return nil, err
} else if !ok {
// No point keys within the table match the filters.
return nil, nil
}
}
var iter sstable.Iterator
filterBlockSizeLimit := sstable.AlwaysUseFilterBlock
if opts != nil {
// By default, we don't use block filters for L6 and restrict the size for
// flushable ingests, as these blocks can be very big.
if !opts.UseL6Filters {
if opts.layer == manifest.Level(6) {
filterBlockSizeLimit = sstable.NeverUseFilterBlock
} else if opts.layer.IsFlushableIngests() {
filterBlockSizeLimit = filterBlockSizeLimitForFlushableIngests
}
}
if opts.layer.IsSet() && !opts.layer.IsFlushableIngests() {
ctx = objiotracing.WithLevel(ctx, opts.layer.Level())
}
}
tableFormat, err := v.reader.TableFormat()
if err != nil {
return nil, err
}
if v.isShared && file.SyntheticSeqNum() != 0 {
if tableFormat < sstable.TableFormatPebblev4 {
return nil, errors.New("pebble: shared ingested sstable has a lower table format than expected")
}
// The table is shared and ingested.
hideObsoletePoints = true
}
transforms := file.IterTransforms()
transforms.HideObsoletePoints = hideObsoletePoints
iterStatsAccum := internalOpts.iterStatsAccumulator
if iterStatsAccum == nil && opts != nil && dbOpts.sstStatsCollector != nil {
iterStatsAccum = dbOpts.sstStatsCollector.Accumulator(
uint64(uintptr(unsafe.Pointer(v.reader))), opts.Category)
}
if internalOpts.compaction {
iter, err = cr.NewCompactionIter(transforms, iterStatsAccum, &v.readerProvider, internalOpts.bufferPool)
} else {
iter, err = cr.NewPointIter(
ctx, transforms, opts.GetLowerBound(), opts.GetUpperBound(), filterer, filterBlockSizeLimit,
internalOpts.stats, iterStatsAccum, &v.readerProvider)
}
if err != nil {
return nil, err
}
// NB: v.closeHook takes responsibility for calling unrefValue(v) here. Take
// care to avoid introducing an allocation here by adding a closure.
iter.SetCloseHook(v.closeHook)
c.iterCount.Add(1)
dbOpts.iterCount.Add(1)
if invariants.RaceEnabled {
c.mu.Lock()
c.mu.iters[iter] = debug.Stack()
c.mu.Unlock()
}
return iter, nil
}
// newRangeDelIter is an internal helper that constructs an iterator over a
// sstable's range deletions. This function is for table-cache internal use
// only, and callers should use newIters instead.
func (c *fileCacheShard) newRangeDelIter(
ctx context.Context, file *manifest.FileMetadata, cr sstable.CommonReader, dbOpts *fileCacheOpts,
) (keyspan.FragmentIterator, error) {
// NB: range-del iterator does not maintain a reference to the table, nor
// does it need to read from it after creation.
rangeDelIter, err := cr.NewRawRangeDelIter(ctx, file.FragmentIterTransforms())
if err != nil {
return nil, err
}
// Assert expected bounds in tests.
if invariants.Sometimes(50) && rangeDelIter != nil {
cmp := base.DefaultComparer.Compare
if dbOpts.readerOpts.Comparer != nil {
cmp = dbOpts.readerOpts.Comparer.Compare
}
rangeDelIter = keyspan.AssertBounds(
rangeDelIter, file.SmallestPointKey, file.LargestPointKey.UserKey, cmp,
)
}
return rangeDelIter, nil
}
// newRangeKeyIter is an internal helper that constructs an iterator over a
// sstable's range keys. This function is for table-cache internal use only, and
// callers should use newIters instead.
func (c *fileCacheShard) newRangeKeyIter(
ctx context.Context,
v *fileCacheValue,
file *fileMetadata,
cr sstable.CommonReader,
opts keyspan.SpanIterOptions,
) (keyspan.FragmentIterator, error) {
transforms := file.FragmentIterTransforms()
// Don't filter a table's range keys if the file contains RANGEKEYDELs.
// The RANGEKEYDELs may delete range keys in other levels. Skipping the
// file's range key blocks may surface deleted range keys below. This is
// done here, rather than deferring to the block-property collector in order
// to maintain parity with point keys and the treatment of RANGEDELs.
if v.reader.Properties.NumRangeKeyDels == 0 && len(opts.RangeKeyFilters) > 0 {
ok, _, err := c.checkAndIntersectFilters(v, opts.RangeKeyFilters, nil, transforms.SyntheticSuffix())
if err != nil {
return nil, err
} else if !ok {
return nil, nil
}
}
// TODO(radu): wrap in an AssertBounds.
return cr.NewRawRangeKeyIter(ctx, transforms)
}
// tableCacheShardReaderProvider implements sstable.ReaderProvider for a
// specific table.
type tableCacheShardReaderProvider struct {
c *fileCacheShard
dbOpts *fileCacheOpts
backingFileNum base.DiskFileNum
mu struct {
sync.Mutex
// v is the result of findNode. Whenever it is not null, we hold a refcount
// on the fileCacheValue.
v *fileCacheValue
// refCount is the number of GetReader() calls that have not received a
// corresponding Close().
refCount int
}
}
var _ valblk.ReaderProvider = &tableCacheShardReaderProvider{}
func (rp *tableCacheShardReaderProvider) init(
c *fileCacheShard, dbOpts *fileCacheOpts, backingFileNum base.DiskFileNum,
) {
rp.c = c
rp.dbOpts = dbOpts
rp.backingFileNum = backingFileNum
rp.mu.v = nil
rp.mu.refCount = 0
}
// GetReader implements sstable.ReaderProvider. Note that it is not the
// responsibility of tableCacheShardReaderProvider to ensure that the file
// continues to exist. The ReaderProvider is used in iterators where the
// top-level iterator is pinning the read state and preventing the files from
// being deleted.
//
// The caller must call tableCacheShardReaderProvider.Close.
//
// Note that currently the Reader returned here is only used to read value
// blocks. This reader shouldn't be used for other purposes like reading keys
// outside of virtual sstable bounds.
//
// TODO(bananabrick): We could return a wrapper over the Reader to ensure
// that the reader isn't used for other purposes.
func (rp *tableCacheShardReaderProvider) GetReader(
ctx context.Context,
) (valblk.ExternalBlockReader, error) {
rp.mu.Lock()
defer rp.mu.Unlock()
if rp.mu.v != nil {
rp.mu.refCount++
return rp.mu.v.reader, nil
}
// Calling findNodeInternal gives us the responsibility of decrementing v's
// refCount. Note that if the table is no longer in the cache,
// findNodeInternal will need to do IO to initialize a new Reader. We hold
// rp.mu during this time so that concurrent GetReader calls block until the
// Reader is created.
v := rp.c.findNodeInternal(ctx, rp.backingFileNum, rp.dbOpts)
if v.err != nil {
defer rp.c.unrefValue(v)
return nil, v.err
}
rp.mu.v = v
rp.mu.refCount = 1
return v.reader, nil
}
// Close implements sstable.ReaderProvider.
func (rp *tableCacheShardReaderProvider) Close() {
rp.mu.Lock()
defer rp.mu.Unlock()
rp.mu.refCount--
if rp.mu.refCount <= 0 {
if rp.mu.refCount < 0 {
panic("pebble: sstable.ReaderProvider misuse")
}
rp.c.unrefValue(rp.mu.v)
rp.mu.v = nil
}
}
// getTableProperties return sst table properties for target file
func (c *fileCacheShard) getTableProperties(
file *fileMetadata, dbOpts *fileCacheOpts,
) (*sstable.Properties, error) {
// Calling findNode gives us the responsibility of decrementing v's refCount here
v := c.findNode(context.TODO(), file.FileBacking, dbOpts)
defer c.unrefValue(v)
if v.err != nil {
return nil, v.err
}
return &v.reader.Properties, nil
}
// releaseNode releases a node from the fileCacheShard.
//
// c.mu must be held when calling this.
func (c *fileCacheShard) releaseNode(n *fileCacheNode) {
c.unlinkNode(n)
c.clearNode(n)
}
// unlinkNode removes a node from the fileCacheShard, leaving the shard
// reference in place.
//
// c.mu must be held when calling this.
func (c *fileCacheShard) unlinkNode(n *fileCacheNode) {
key := fileCacheKey{n.cacheID, n.fileNum}
delete(c.mu.nodes, key)
switch n.ptype {
case fileCacheNodeHot:
c.mu.sizeHot--
case fileCacheNodeCold:
c.mu.sizeCold--
case fileCacheNodeTest:
c.mu.sizeTest--
}
if n == c.mu.handHot {
c.mu.handHot = c.mu.handHot.prev()
}
if n == c.mu.handCold {
c.mu.handCold = c.mu.handCold.prev()
}
if n == c.mu.handTest {
c.mu.handTest = c.mu.handTest.prev()
}
if n.unlink() == n {
// This was the last entry in the cache.
c.mu.handHot = nil
c.mu.handCold = nil
c.mu.handTest = nil
}
n.links.prev = nil
n.links.next = nil
}
func (c *fileCacheShard) clearNode(n *fileCacheNode) {
if v := n.value; v != nil {
n.value = nil
c.unrefValue(v)
}
}
// unrefValue decrements the reference count for the specified value, releasing
// it if the reference count fell to 0. Note that the value has a reference if
// it is present in fileCacheShard.mu.nodes, so a reference count of 0 means the
// node has already been removed from that map.
func (c *fileCacheShard) unrefValue(v *fileCacheValue) {
if v.refCount.Add(-1) == 0 {
c.releasing.Add(1)
c.releasingCh <- v
}
}
// findNode returns the node for the table with the given file number, creating
// that node if it didn't already exist. The caller is responsible for
// decrementing the returned node's refCount.
func (c *fileCacheShard) findNode(
ctx context.Context, b *fileBacking, dbOpts *fileCacheOpts,
) *fileCacheValue {
// The backing must have a positive refcount (otherwise it could be deleted at any time).
b.MustHaveRefs()
// Caution! Here fileMetadata can be a physical or virtual table. File cache
// sstable readers are associated with the physical backings. All virtual
// tables with the same backing will use the same reader from the cache; so
// no information that can differ among these virtual tables can be passed
// to findNodeInternal.
backingFileNum := b.DiskFileNum
return c.findNodeInternal(ctx, backingFileNum, dbOpts)
}
func (c *fileCacheShard) findNodeInternal(
ctx context.Context, backingFileNum base.DiskFileNum, dbOpts *fileCacheOpts,
) *fileCacheValue {
// Fast-path for a hit in the cache.
c.mu.RLock()
key := fileCacheKey{dbOpts.cacheID, backingFileNum}
if n := c.mu.nodes[key]; n != nil && n.value != nil {
// Fast-path hit.
//
// The caller is responsible for decrementing the refCount.
v := n.value
v.refCount.Add(1)
c.mu.RUnlock()
n.referenced.Store(true)
c.hits.Add(1)
<-v.loaded
return v
}
c.mu.RUnlock()
c.mu.Lock()
n := c.mu.nodes[key]
switch {
case n == nil:
// Slow-path miss of a non-existent node.
n = &fileCacheNode{
fileNum: backingFileNum,
ptype: fileCacheNodeCold,
}
c.addNode(n, dbOpts)
c.mu.sizeCold++
case n.value != nil:
// Slow-path hit of a hot or cold node.
//
// The caller is responsible for decrementing the refCount.
v := n.value
v.refCount.Add(1)
n.referenced.Store(true)
c.hits.Add(1)
c.mu.Unlock()
<-v.loaded
return v
default:
// Slow-path miss of a test node.
c.unlinkNode(n)
c.mu.coldTarget++
if c.mu.coldTarget > c.size {
c.mu.coldTarget = c.size
}
n.referenced.Store(false)
n.ptype = fileCacheNodeHot
c.addNode(n, dbOpts)
c.mu.sizeHot++
}
c.misses.Add(1)
v := &fileCacheValue{
loaded: make(chan struct{}),
}
v.readerProvider.init(c, dbOpts, backingFileNum)
v.refCount.Store(2)
// Cache the closure invoked when an iterator is closed. This avoids an
// allocation on every call to newIters.
v.closeHook = func(i sstable.Iterator) error {
if invariants.RaceEnabled {
c.mu.Lock()
delete(c.mu.iters, i)
c.mu.Unlock()
}
c.unrefValue(v)
c.iterCount.Add(-1)
dbOpts.iterCount.Add(-1)
return nil
}
n.value = v
c.mu.Unlock()
// Note adding to the cache lists must complete before we begin loading the
// table as a failure during load will result in the node being unlinked.
v.load(ctx, backingFileNum, c, dbOpts)
return v
}
func (c *fileCacheShard) addNode(n *fileCacheNode, dbOpts *fileCacheOpts) {
c.evictNodes()
n.cacheID = dbOpts.cacheID
key := fileCacheKey{n.cacheID, n.fileNum}
c.mu.nodes[key] = n
n.links.next = n
n.links.prev = n
if c.mu.handHot == nil {
// First element.
c.mu.handHot = n
c.mu.handCold = n
c.mu.handTest = n
} else {
c.mu.handHot.link(n)
}
if c.mu.handCold == c.mu.handHot {
c.mu.handCold = c.mu.handCold.prev()
}
}
func (c *fileCacheShard) evictNodes() {
for c.size <= c.mu.sizeHot+c.mu.sizeCold && c.mu.handCold != nil {
c.runHandCold()
}
}
func (c *fileCacheShard) runHandCold() {
n := c.mu.handCold
if n.ptype == fileCacheNodeCold {
if n.referenced.Load() {
n.referenced.Store(false)
n.ptype = fileCacheNodeHot
c.mu.sizeCold--
c.mu.sizeHot++
} else {
c.clearNode(n)
n.ptype = fileCacheNodeTest
c.mu.sizeCold--
c.mu.sizeTest++
for c.size < c.mu.sizeTest && c.mu.handTest != nil {
c.runHandTest()
}
}
}
c.mu.handCold = c.mu.handCold.next()
for c.size-c.mu.coldTarget <= c.mu.sizeHot && c.mu.handHot != nil {
c.runHandHot()
}
}
func (c *fileCacheShard) runHandHot() {
if c.mu.handHot == c.mu.handTest && c.mu.handTest != nil {
c.runHandTest()
if c.mu.handHot == nil {
return
}
}
n := c.mu.handHot
if n.ptype == fileCacheNodeHot {
if n.referenced.Load() {
n.referenced.Store(false)
} else {
n.ptype = fileCacheNodeCold
c.mu.sizeHot--
c.mu.sizeCold++
}
}
c.mu.handHot = c.mu.handHot.next()
}
func (c *fileCacheShard) runHandTest() {
if c.mu.sizeCold > 0 && c.mu.handTest == c.mu.handCold && c.mu.handCold != nil {
c.runHandCold()
if c.mu.handTest == nil {
return
}
}