/
file_store.go
1545 lines (1306 loc) · 42.2 KB
/
file_store.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
package tsm1
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"math"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/influxdata/influxdb/models"
"github.com/influxdata/influxdb/pkg/file"
"github.com/influxdata/influxdb/pkg/limiter"
"github.com/influxdata/influxdb/pkg/metrics"
"github.com/influxdata/influxdb/query"
"github.com/influxdata/influxdb/tsdb"
"go.uber.org/zap"
)
const (
// The extension used to describe temporary snapshot files.
TmpTSMFileExtension = "tmp"
// The extension used to describe corrupt snapshot files.
BadTSMFileExtension = "bad"
)
// TSMFile represents an on-disk TSM file.
type TSMFile interface {
// Path returns the underlying file path for the TSMFile. If the file
// has not be written or loaded from disk, the zero value is returned.
Path() string
// Read returns all the values in the block where time t resides.
Read(key []byte, t int64) ([]Value, error)
// ReadAt returns all the values in the block identified by entry.
ReadAt(entry *IndexEntry, values []Value) ([]Value, error)
ReadFloatBlockAt(entry *IndexEntry, values *[]FloatValue) ([]FloatValue, error)
ReadFloatArrayBlockAt(entry *IndexEntry, values *tsdb.FloatArray) error
ReadIntegerBlockAt(entry *IndexEntry, values *[]IntegerValue) ([]IntegerValue, error)
ReadIntegerArrayBlockAt(entry *IndexEntry, values *tsdb.IntegerArray) error
ReadUnsignedBlockAt(entry *IndexEntry, values *[]UnsignedValue) ([]UnsignedValue, error)
ReadUnsignedArrayBlockAt(entry *IndexEntry, values *tsdb.UnsignedArray) error
ReadStringBlockAt(entry *IndexEntry, values *[]StringValue) ([]StringValue, error)
ReadStringArrayBlockAt(entry *IndexEntry, values *tsdb.StringArray) error
ReadBooleanBlockAt(entry *IndexEntry, values *[]BooleanValue) ([]BooleanValue, error)
ReadBooleanArrayBlockAt(entry *IndexEntry, values *tsdb.BooleanArray) error
// Entries returns the index entries for all blocks for the given key.
Entries(key []byte) []IndexEntry
ReadEntries(key []byte, entries *[]IndexEntry) []IndexEntry
// Returns true if the TSMFile may contain a value with the specified
// key and time.
ContainsValue(key []byte, t int64) bool
// Contains returns true if the file contains any values for the given
// key.
Contains(key []byte) bool
// OverlapsTimeRange returns true if the time range of the file intersect min and max.
OverlapsTimeRange(min, max int64) bool
// OverlapsKeyRange returns true if the key range of the file intersects min and max.
OverlapsKeyRange(min, max []byte) bool
// TimeRange returns the min and max time across all keys in the file.
TimeRange() (int64, int64)
// TombstoneRange returns ranges of time that are deleted for the given key.
TombstoneRange(key []byte) []TimeRange
// KeyRange returns the min and max keys in the file.
KeyRange() ([]byte, []byte)
// KeyCount returns the number of distinct keys in the file.
KeyCount() int
// Seek returns the position in the index with the key <= key.
Seek(key []byte) int
// KeyAt returns the key located at index position idx.
KeyAt(idx int) ([]byte, byte)
// Type returns the block type of the values stored for the key. Returns one of
// BlockFloat64, BlockInt64, BlockBoolean, BlockString. If key does not exist,
// an error is returned.
Type(key []byte) (byte, error)
// BatchDelete return a BatchDeleter that allows for multiple deletes in batches
// and group commit or rollback.
BatchDelete() BatchDeleter
// Delete removes the keys from the set of keys available in this file.
Delete(keys [][]byte) error
// DeleteRange removes the values for keys between timestamps min and max.
DeleteRange(keys [][]byte, min, max int64) error
// HasTombstones returns true if file contains values that have been deleted.
HasTombstones() bool
// TombstoneStats returns the tombstone filestats if there are any tombstones
// written for this file.
TombstoneStats() TombstoneStat
// Close closes the underlying file resources.
Close() error
// Size returns the size of the file on disk in bytes.
Size() uint32
// Rename renames the existing TSM file to a new name and replaces the mmap backing slice using the new
// file name. Index and Reader state are not re-initialized.
Rename(path string) error
// Remove deletes the file from the filesystem.
Remove() error
// InUse returns true if the file is currently in use by queries.
InUse() bool
// Ref records that this file is actively in use.
Ref()
// Unref records that this file is no longer in use.
Unref()
// Stats returns summary information about the TSM file.
Stats() FileStat
// BlockIterator returns an iterator pointing to the first block in the file and
// allows sequential iteration to each and every block.
BlockIterator() *BlockIterator
// Free releases any resources held by the FileStore to free up system resources.
Free() error
}
// Statistics gathered by the FileStore.
const (
statFileStoreBytes = "diskBytes"
statFileStoreCount = "numFiles"
)
var (
floatBlocksDecodedCounter = metrics.MustRegisterCounter("float_blocks_decoded", metrics.WithGroup(tsmGroup))
floatBlocksSizeCounter = metrics.MustRegisterCounter("float_blocks_size_bytes", metrics.WithGroup(tsmGroup))
integerBlocksDecodedCounter = metrics.MustRegisterCounter("integer_blocks_decoded", metrics.WithGroup(tsmGroup))
integerBlocksSizeCounter = metrics.MustRegisterCounter("integer_blocks_size_bytes", metrics.WithGroup(tsmGroup))
unsignedBlocksDecodedCounter = metrics.MustRegisterCounter("unsigned_blocks_decoded", metrics.WithGroup(tsmGroup))
unsignedBlocksSizeCounter = metrics.MustRegisterCounter("unsigned_blocks_size_bytes", metrics.WithGroup(tsmGroup))
stringBlocksDecodedCounter = metrics.MustRegisterCounter("string_blocks_decoded", metrics.WithGroup(tsmGroup))
stringBlocksSizeCounter = metrics.MustRegisterCounter("string_blocks_size_bytes", metrics.WithGroup(tsmGroup))
booleanBlocksDecodedCounter = metrics.MustRegisterCounter("boolean_blocks_decoded", metrics.WithGroup(tsmGroup))
booleanBlocksSizeCounter = metrics.MustRegisterCounter("boolean_blocks_size_bytes", metrics.WithGroup(tsmGroup))
)
// FileStore is an abstraction around multiple TSM files.
type FileStore struct {
mu sync.RWMutex
lastModified time.Time
// Most recently known file stats. If nil then stats will need to be
// recalculated
lastFileStats []FileStat
currentGeneration int
dir string
files []TSMFile
openLimiter limiter.Fixed // limit the number of concurrent opening TSM files.
logger *zap.Logger // Logger to be used for important messages
traceLogger *zap.Logger // Logger to be used when trace-logging is on.
traceLogging bool
stats *FileStoreStatistics
purger *purger
currentTempDirID int
parseFileName ParseFileNameFunc
obs tsdb.FileStoreObserver
copyFiles bool
readerOptions []tsmReaderOption
}
// FileStat holds information about a TSM file on disk.
type FileStat struct {
Path string
HasTombstone bool
Size uint32
LastModified int64
MinTime, MaxTime int64
MinKey, MaxKey []byte
}
// TombstoneStat holds information about a possible tombstone file on disk.
type TombstoneStat struct {
TombstoneExists bool
Path string
LastModified int64
Size uint32
}
// OverlapsTimeRange returns true if the time range of the file intersect min and max.
func (f FileStat) OverlapsTimeRange(min, max int64) bool {
return f.MinTime <= max && f.MaxTime >= min
}
// OverlapsKeyRange returns true if the min and max keys of the file overlap the arguments min and max.
func (f FileStat) OverlapsKeyRange(min, max []byte) bool {
return len(min) != 0 && len(max) != 0 && bytes.Compare(f.MinKey, max) <= 0 && bytes.Compare(f.MaxKey, min) >= 0
}
// ContainsKey returns true if the min and max keys of the file overlap the arguments min and max.
func (f FileStat) ContainsKey(key []byte) bool {
return bytes.Compare(f.MinKey, key) >= 0 || bytes.Compare(key, f.MaxKey) <= 0
}
// NewFileStore returns a new instance of FileStore based on the given directory.
func NewFileStore(dir string, options ...tsmReaderOption) *FileStore {
logger := zap.NewNop()
fs := &FileStore{
dir: dir,
lastModified: time.Time{},
logger: logger,
traceLogger: logger,
openLimiter: limiter.NewFixed(runtime.GOMAXPROCS(0)),
stats: &FileStoreStatistics{},
purger: &purger{
files: map[string]TSMFile{},
logger: logger,
},
obs: noFileStoreObserver{},
parseFileName: DefaultParseFileName,
copyFiles: runtime.GOOS == "windows",
readerOptions: options,
}
fs.purger.fileStore = fs
return fs
}
// WithObserver sets the observer for the file store.
func (f *FileStore) WithObserver(obs tsdb.FileStoreObserver) {
f.obs = obs
}
func (f *FileStore) WithParseFileNameFunc(parseFileNameFunc ParseFileNameFunc) {
f.parseFileName = parseFileNameFunc
}
func (f *FileStore) ParseFileName(path string) (int, int, error) {
return f.parseFileName(path)
}
// enableTraceLogging must be called before the FileStore is opened.
func (f *FileStore) enableTraceLogging(enabled bool) {
f.traceLogging = enabled
if enabled {
f.traceLogger = f.logger
}
}
// WithLogger sets the logger on the file store.
func (f *FileStore) WithLogger(log *zap.Logger) {
f.logger = log.With(zap.String("service", "filestore"))
f.purger.logger = f.logger
if f.traceLogging {
f.traceLogger = f.logger
}
}
// FileStoreStatistics keeps statistics about the file store.
type FileStoreStatistics struct {
DiskBytes int64
FileCount int64
}
// Statistics returns statistics for periodic monitoring.
func (f *FileStore) Statistics(tags map[string]string) []models.Statistic {
return []models.Statistic{{
Name: "tsm1_filestore",
Tags: tags,
Values: map[string]interface{}{
statFileStoreBytes: atomic.LoadInt64(&f.stats.DiskBytes),
statFileStoreCount: atomic.LoadInt64(&f.stats.FileCount),
},
}}
}
// Count returns the number of TSM files currently loaded.
func (f *FileStore) Count() int {
f.mu.RLock()
defer f.mu.RUnlock()
return len(f.files)
}
// Files returns the slice of TSM files currently loaded. This is only used for
// tests, and the files aren't guaranteed to stay valid in the presence of compactions.
func (f *FileStore) Files() []TSMFile {
f.mu.RLock()
defer f.mu.RUnlock()
return f.files
}
// Free releases any resources held by the FileStore. The resources will be re-acquired
// if necessary if they are needed after freeing them.
func (f *FileStore) Free() error {
f.mu.RLock()
defer f.mu.RUnlock()
for _, f := range f.files {
if err := f.Free(); err != nil {
return err
}
}
return nil
}
// CurrentGeneration returns the current generation of the TSM files.
func (f *FileStore) CurrentGeneration() int {
f.mu.RLock()
defer f.mu.RUnlock()
return f.currentGeneration
}
// NextGeneration increments the max file ID and returns the new value.
func (f *FileStore) NextGeneration() int {
f.mu.Lock()
defer f.mu.Unlock()
f.currentGeneration++
return f.currentGeneration
}
// WalkKeys calls fn for every key in every TSM file known to the FileStore. If the key
// exists in multiple files, it will be invoked for each file.
func (f *FileStore) WalkKeys(seek []byte, fn func(key []byte, typ byte) error) error {
f.mu.RLock()
if len(f.files) == 0 {
f.mu.RUnlock()
return nil
}
// Ensure files are not unmapped while we're iterating over them.
for _, r := range f.files {
r.Ref()
defer r.Unref()
}
ki := newMergeKeyIterator(f.files, seek)
f.mu.RUnlock()
for ki.Next() {
key, typ := ki.Read()
if err := fn(key, typ); err != nil {
return err
}
}
return nil
}
// Keys returns all keys and types for all files in the file store.
func (f *FileStore) Keys() map[string]byte {
f.mu.RLock()
defer f.mu.RUnlock()
uniqueKeys := map[string]byte{}
if err := f.WalkKeys(nil, func(key []byte, typ byte) error {
uniqueKeys[string(key)] = typ
return nil
}); err != nil {
return nil
}
return uniqueKeys
}
// Type returns the type of values store at the block for key.
func (f *FileStore) Type(key []byte) (byte, error) {
f.mu.RLock()
defer f.mu.RUnlock()
for _, f := range f.files {
if f.Contains(key) {
return f.Type(key)
}
}
return 0, fmt.Errorf("unknown type for %v", key)
}
// Delete removes the keys from the set of keys available in this file.
func (f *FileStore) Delete(keys [][]byte) error {
return f.DeleteRange(keys, math.MinInt64, math.MaxInt64)
}
func (f *FileStore) Apply(fn func(r TSMFile) error) error {
// Limit apply fn to number of cores
limiter := limiter.NewFixed(runtime.GOMAXPROCS(0))
f.mu.RLock()
errC := make(chan error, len(f.files))
for _, f := range f.files {
go func(r TSMFile) {
limiter.Take()
defer limiter.Release()
r.Ref()
defer r.Unref()
errC <- fn(r)
}(f)
}
var applyErr error
for i := 0; i < cap(errC); i++ {
if err := <-errC; err != nil {
applyErr = err
}
}
f.mu.RUnlock()
f.mu.Lock()
f.lastModified = time.Now().UTC()
f.lastFileStats = nil
f.mu.Unlock()
return applyErr
}
// DeleteRange removes the values for keys between timestamps min and max. This should only
// be used with smaller batches of series keys.
func (f *FileStore) DeleteRange(keys [][]byte, min, max int64) error {
var batches BatchDeleters
f.mu.RLock()
for _, f := range f.files {
if f.OverlapsTimeRange(min, max) {
batches = append(batches, f.BatchDelete())
}
}
f.mu.RUnlock()
if len(batches) == 0 {
return nil
}
if err := func() error {
if err := batches.DeleteRange(keys, min, max); err != nil {
return err
}
return batches.Commit()
}(); err != nil {
// Rollback the deletes
_ = batches.Rollback()
return err
}
f.mu.Lock()
f.lastModified = time.Now().UTC()
f.lastFileStats = nil
f.mu.Unlock()
return nil
}
// Open loads all the TSM files in the configured directory.
func (f *FileStore) Open() error {
f.mu.Lock()
defer f.mu.Unlock()
// Not loading files from disk so nothing to do
if f.dir == "" {
return nil
}
if f.openLimiter == nil {
return errors.New("cannot open FileStore without an OpenLimiter (is EngineOptions.OpenLimiter set?)")
}
// find the current max ID for temp directories
tmpfiles, err := os.ReadDir(f.dir)
if err != nil {
return err
}
// ascertain the current temp directory number by examining the existing
// directories and choosing the one with the higest basename when converted
// to an integer.
for _, fi := range tmpfiles {
if !fi.IsDir() || !strings.HasSuffix(fi.Name(), "."+TmpTSMFileExtension) {
continue
}
ss := strings.Split(filepath.Base(fi.Name()), ".")
if len(ss) != 2 {
continue
}
i, err := strconv.Atoi(ss[0])
if err != nil || i <= f.currentTempDirID {
continue
}
// i must be a valid integer and greater than f.currentTempDirID at this
// point
f.currentTempDirID = i
}
files, err := filepath.Glob(filepath.Join(f.dir, "*."+TSMFileExtension))
if err != nil {
return err
}
// struct to hold the result of opening each reader in a goroutine
type res struct {
r *TSMReader
err error
}
readerC := make(chan *res)
for i, fn := range files {
// Keep track of the latest ID
generation, _, err := f.parseFileName(fn)
if err != nil {
return err
}
if generation >= f.currentGeneration {
f.currentGeneration = generation + 1
}
file, err := os.OpenFile(fn, os.O_RDONLY, 0666)
if err != nil {
return fmt.Errorf("error opening file %s: %v", fn, err)
}
go func(idx int, file *os.File) {
// Ensure a limited number of TSM files are loaded at once.
// Systems which have very large datasets (1TB+) can have thousands
// of TSM files which can cause extremely long load times.
f.openLimiter.Take()
defer f.openLimiter.Release()
start := time.Now()
df, err := NewTSMReader(file, f.readerOptions...)
f.logger.Info("Opened file",
zap.String("path", file.Name()),
zap.Int("id", idx),
zap.Duration("duration", time.Since(start)))
// If we are unable to read a TSM file then log the error.
if err != nil {
file.Close()
if errors.Is(err, MmapError{}) {
// An MmapError may indicate we have insufficient
// handles for the mmap call, in which case the file should
// be left untouched, and the vm.max_map_count be raised.
f.logger.Error("Cannot read TSM file, system limit for vm.max_map_count may be too low",
zap.String("path", file.Name()), zap.Int("id", idx), zap.Error(err))
readerC <- &res{r: df, err: fmt.Errorf("cannot read file %s, system limit for vm.max_map_count may be too low: %v", file.Name(), err)}
return
} else {
// If the file is corrupt, rename it and
// continue loading the shard without it.
f.logger.Error("Cannot read corrupt tsm file, renaming", zap.String("path", file.Name()), zap.Int("id", idx), zap.Error(err))
if e := os.Rename(file.Name(), file.Name()+"."+BadTSMFileExtension); e != nil {
f.logger.Error("Cannot rename corrupt tsm file", zap.String("path", file.Name()), zap.Int("id", idx), zap.Error(e))
readerC <- &res{r: df, err: fmt.Errorf("cannot rename corrupt file %s: %v", file.Name(), e)}
return
}
readerC <- &res{r: df, err: fmt.Errorf("cannot read corrupt file %s: %v", file.Name(), err)}
return
}
}
df.WithObserver(f.obs)
readerC <- &res{r: df}
}(i, file)
}
var lm int64
isEmpty := true
for range files {
res := <-readerC
if res.err != nil {
return res.err
} else if res.r == nil {
continue
}
f.files = append(f.files, res.r)
// Accumulate file store size stats
atomic.AddInt64(&f.stats.DiskBytes, int64(res.r.Size()))
if ts := res.r.TombstoneStats(); ts.TombstoneExists {
atomic.AddInt64(&f.stats.DiskBytes, int64(ts.Size))
}
// Re-initialize the lastModified time for the file store
if res.r.LastModified() > lm {
lm = res.r.LastModified()
}
isEmpty = false
}
if isEmpty {
if fi, err := os.Stat(f.dir); err == nil {
f.lastModified = fi.ModTime().UTC()
} else {
close(readerC)
return err
}
} else {
f.lastModified = time.Unix(0, lm).UTC()
}
close(readerC)
sort.Sort(tsmReaders(f.files))
atomic.StoreInt64(&f.stats.FileCount, int64(len(f.files)))
return nil
}
// Close closes the file store.
func (f *FileStore) Close() error {
// Make the object appear closed to other method calls.
f.mu.Lock()
files := f.files
f.lastFileStats = nil
f.files = nil
atomic.StoreInt64(&f.stats.FileCount, 0)
// Let other methods access this closed object while we do the actual closing.
f.mu.Unlock()
for _, file := range files {
err := file.Close()
if err != nil {
return err
}
}
return nil
}
func (f *FileStore) DiskSizeBytes() int64 {
return atomic.LoadInt64(&f.stats.DiskBytes)
}
// Read returns the slice of values for the given key and the given timestamp,
// if any file matches those constraints.
func (f *FileStore) Read(key []byte, t int64) ([]Value, error) {
f.mu.RLock()
defer f.mu.RUnlock()
for _, f := range f.files {
// Can this file possibly contain this key and timestamp?
if !f.Contains(key) {
continue
}
// May have the key and time we are looking for so try to find
v, err := f.Read(key, t)
if err != nil {
return nil, err
}
if len(v) > 0 {
return v, nil
}
}
return nil, nil
}
func (f *FileStore) Cost(key []byte, min, max int64) query.IteratorCost {
f.mu.RLock()
defer f.mu.RUnlock()
return f.cost(key, min, max)
}
// Reader returns a TSMReader for path if one is currently managed by the FileStore.
// Otherwise it returns nil. If it returns a file, you must call Unref on it when
// you are done, and never use it after that.
func (f *FileStore) TSMReader(path string) *TSMReader {
f.mu.RLock()
defer f.mu.RUnlock()
for _, r := range f.files {
if r.Path() == path {
r.Ref()
return r.(*TSMReader)
}
}
return nil
}
// KeyCursor returns a KeyCursor for key and t across the files in the FileStore.
func (f *FileStore) KeyCursor(ctx context.Context, key []byte, t int64, ascending bool) *KeyCursor {
f.mu.RLock()
defer f.mu.RUnlock()
return newKeyCursor(ctx, f, key, t, ascending)
}
// Stats returns the stats of the underlying files, preferring the cached version if it is still valid.
func (f *FileStore) Stats() []FileStat {
f.mu.RLock()
if len(f.lastFileStats) > 0 {
defer f.mu.RUnlock()
return f.lastFileStats
}
f.mu.RUnlock()
// The file stats cache is invalid due to changes to files. Need to
// recalculate.
f.mu.Lock()
defer f.mu.Unlock()
if len(f.lastFileStats) > 0 {
return f.lastFileStats
}
// If lastFileStats's capacity is far away from the number of entries
// we need to add, then we'll reallocate.
if cap(f.lastFileStats) < len(f.files)/2 {
f.lastFileStats = make([]FileStat, 0, len(f.files))
}
for _, fd := range f.files {
f.lastFileStats = append(f.lastFileStats, fd.Stats())
}
return f.lastFileStats
}
// ReplaceWithCallback replaces oldFiles with newFiles and calls updatedFn with the files to be added the FileStore.
func (f *FileStore) ReplaceWithCallback(oldFiles, newFiles []string, updatedFn func(r []TSMFile)) error {
return f.replace(oldFiles, newFiles, updatedFn)
}
// Replace replaces oldFiles with newFiles.
func (f *FileStore) Replace(oldFiles, newFiles []string) error {
return f.replace(oldFiles, newFiles, nil)
}
func (f *FileStore) replace(oldFiles, newFiles []string, updatedFn func(r []TSMFile)) error {
if len(oldFiles) == 0 && len(newFiles) == 0 {
return nil
}
f.mu.RLock()
maxTime := f.lastModified
f.mu.RUnlock()
updated := make([]TSMFile, 0, len(newFiles))
tsmTmpExt := fmt.Sprintf("%s.%s", TSMFileExtension, TmpTSMFileExtension)
// Rename all the new files to make them live on restart
for _, file := range newFiles {
if !strings.HasSuffix(file, tsmTmpExt) && !strings.HasSuffix(file, TSMFileExtension) {
// This isn't a .tsm or .tsm.tmp file.
continue
}
// give the observer a chance to process the file first.
if err := f.obs.FileFinishing(file); err != nil {
return err
}
var oldName, newName = file, file
if strings.HasSuffix(oldName, tsmTmpExt) {
// The new TSM files have a tmp extension. First rename them.
newName = file[:len(file)-4]
if err := os.Rename(oldName, newName); err != nil {
return err
}
}
// Any error after this point should result in the file being bein named
// back to the original name. The caller then has the opportunity to
// remove it.
fd, err := os.Open(newName)
if err != nil {
if newName != oldName {
if err1 := os.Rename(newName, oldName); err1 != nil {
return err1
}
}
return err
}
// Keep track of the new mod time
if stat, err := fd.Stat(); err == nil {
if maxTime.IsZero() || stat.ModTime().UTC().After(maxTime) {
maxTime = stat.ModTime().UTC()
}
}
tsm, err := NewTSMReader(fd, f.readerOptions...)
if err != nil {
if newName != oldName {
if err1 := os.Rename(newName, oldName); err1 != nil {
return err1
}
}
return err
}
tsm.WithObserver(f.obs)
updated = append(updated, tsm)
}
if updatedFn != nil {
updatedFn(updated)
}
f.mu.Lock()
defer f.mu.Unlock()
// Copy the current set of active files while we rename
// and load the new files. We copy the pointers here to minimize
// the time that locks are held as well as to ensure that the replacement
// is atomic.©
updated = append(updated, f.files...)
// We need to prune our set of active files now
var active, inuse []TSMFile
for _, file := range updated {
keep := true
for _, remove := range oldFiles {
if remove == file.Path() {
keep = false
// give the observer a chance to process the file first.
if err := f.obs.FileUnlinking(file.Path()); err != nil {
return err
}
if ts := file.TombstoneStats(); ts.TombstoneExists {
if err := f.obs.FileUnlinking(ts.Path); err != nil {
return err
}
}
// If queries are running against this file, then we need to move it out of the
// way and let them complete. We'll then delete the original file to avoid
// blocking callers upstream. If the process crashes, the temp file is
// cleaned up at startup automatically.
//
// In order to ensure that there are no races with this (file held externally calls Ref
// after we check InUse), we need to maintain the invariant that every handle to a file
// is handed out in use (Ref'd), and handlers only ever relinquish the file once (call Unref
// exactly once, and never use it again). InUse is only valid during a write lock, since
// we allow calls to Ref and Unref under the read lock and no lock at all respectively.
if file.InUse() {
// Copy all the tombstones related to this TSM file
var deletes []string
if ts := file.TombstoneStats(); ts.TombstoneExists {
deletes = append(deletes, ts.Path)
}
// Rename the TSM file used by this reader
tempPath := fmt.Sprintf("%s.%s", file.Path(), TmpTSMFileExtension)
if err := file.Rename(tempPath); err != nil {
return err
}
// Remove the old file and tombstones. We can't use the normal TSMReader.Remove()
// because it now refers to our temp file which we can't remove.
for _, f := range deletes {
if err := os.Remove(f); err != nil {
return err
}
}
inuse = append(inuse, file)
continue
}
if err := file.Close(); err != nil {
return err
}
if err := file.Remove(); err != nil {
return err
}
break
}
}
if keep {
active = append(active, file)
}
}
if err := file.SyncDir(f.dir); err != nil {
return err
}
// Tell the purger about our in-use files we need to remove
f.purger.add(inuse)
// If times didn't change (which can happen since file mod times are second level),
// then add a ns to the time to ensure that lastModified changes since files on disk
// actually did change
if maxTime.Equal(f.lastModified) || maxTime.Before(f.lastModified) {
maxTime = f.lastModified.UTC().Add(1)
}
f.lastModified = maxTime.UTC()
f.lastFileStats = nil
f.files = active
sort.Sort(tsmReaders(f.files))
atomic.StoreInt64(&f.stats.FileCount, int64(len(f.files)))
// Recalculate the disk size stat
var totalSize int64
for _, file := range f.files {
totalSize += int64(file.Size())
if ts := file.TombstoneStats(); ts.TombstoneExists {
totalSize += int64(ts.Size)
}
}
atomic.StoreInt64(&f.stats.DiskBytes, totalSize)
return nil
}
// LastModified returns the last time the file store was updated with new
// TSM files or a delete.
func (f *FileStore) LastModified() time.Time {
f.mu.RLock()
defer f.mu.RUnlock()
return f.lastModified
}
// BlockCount returns number of values stored in the block at location idx
// in the file at path. If path does not match any file in the store, 0 is
// returned. If idx is out of range for the number of blocks in the file,
// 0 is returned.
func (f *FileStore) BlockCount(path string, idx int) int {
f.mu.RLock()
defer f.mu.RUnlock()
if idx < 0 {
return 0
}
for _, fd := range f.files {
if fd.Path() == path {
iter := fd.BlockIterator()
for i := 0; i < idx; i++ {
if !iter.Next() {
return 0
}
}
_, _, _, _, _, block, _ := iter.Read()
// on Error, BlockCount(block) returns 0 for cnt
cnt, _ := BlockCount(block)
return cnt
}
}
return 0
}
// We need to determine the possible files that may be accessed by this query given
// the time range.
func (f *FileStore) cost(key []byte, min, max int64) query.IteratorCost {
var cache []IndexEntry
cost := query.IteratorCost{}
for _, fd := range f.files {
minTime, maxTime := fd.TimeRange()
if !(maxTime > min && minTime < max) {
continue
}
skipped := true
tombstones := fd.TombstoneRange(key)
entries := fd.ReadEntries(key, &cache)
ENTRIES:
for i := 0; i < len(entries); i++ {
ie := entries[i]
if !(ie.MaxTime > min && ie.MinTime < max) {
continue
}
// Skip any blocks only contain values that are tombstoned.