-
Notifications
You must be signed in to change notification settings - Fork 451
/
buffer.go
1454 lines (1272 loc) · 40.1 KB
/
buffer.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 (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package series
import (
"errors"
"fmt"
"sort"
"sync/atomic"
"time"
"github.com/m3db/m3/src/dbnode/clock"
"github.com/m3db/m3/src/dbnode/digest"
"github.com/m3db/m3/src/dbnode/encoding"
"github.com/m3db/m3/src/dbnode/namespace"
"github.com/m3db/m3/src/dbnode/persist"
"github.com/m3db/m3/src/dbnode/storage/block"
m3dberrors "github.com/m3db/m3/src/dbnode/storage/errors"
"github.com/m3db/m3/src/dbnode/ts"
"github.com/m3db/m3/src/dbnode/x/xio"
"github.com/m3db/m3/src/x/context"
xerrors "github.com/m3db/m3/src/x/errors"
"github.com/m3db/m3/src/x/ident"
"github.com/m3db/m3/src/x/instrument"
"github.com/m3db/m3/src/x/pool"
xtime "github.com/m3db/m3/src/x/time"
"go.uber.org/zap"
)
const (
errBucketMapCacheNotInSync = "bucket map keys do not match sorted keys cache"
errBucketMapCacheNotInSyncFmt = errBucketMapCacheNotInSync + ", blockStart: %d"
errTimestampFormat = time.RFC822Z
)
var (
timeZero time.Time
errIncompleteMerge = errors.New("bucket merge did not result in only one encoder")
)
const (
bucketsCacheSize = 2
// optimizedTimesArraySize is the size of the internal array for the
// optimizedTimes struct. Since the size of this array determines the
// effectiveness of minimizing heap allocations, usage of this struct and/or
// changing this const should only be done after considering its current
// use cases:
// 1) The number of buckets that will be removed within a tick due to that
// block being recently flushed
// 2) The number of buckets that contain ColdWrites within a cold flush
// cycle
// TODO(juchan): revisit this after ColdWrites usage to see if this number
// is sane.
optimizedTimesArraySize = 8
writableBucketVersion = 0
)
type databaseBuffer interface {
Write(
ctx context.Context,
timestamp time.Time,
value float64,
unit xtime.Unit,
annotation []byte,
wOpts WriteOptions,
) (bool, error)
Snapshot(
ctx context.Context,
blockStart time.Time,
id ident.ID,
tags ident.Tags,
persistFn persist.DataFn,
nsCtx namespace.Context,
) error
WarmFlush(
ctx context.Context,
blockStart time.Time,
id ident.ID,
tags ident.Tags,
persistFn persist.DataFn,
nsCtx namespace.Context,
) (FlushOutcome, error)
ReadEncoded(
ctx context.Context,
start, end time.Time,
nsCtx namespace.Context,
) ([][]xio.BlockReader, error)
FetchBlocksForColdFlush(
ctx context.Context,
start time.Time,
version int,
nsCtx namespace.Context,
) ([]xio.BlockReader, error)
FetchBlocks(
ctx context.Context,
starts []time.Time,
nsCtx namespace.Context,
) []block.FetchBlockResult
FetchBlocksMetadata(
ctx context.Context,
start, end time.Time,
opts FetchBlocksMetadataOptions,
) (block.FetchBlockMetadataResults, error)
IsEmpty() bool
ColdFlushBlockStarts(blockStates map[xtime.UnixNano]BlockState) OptimizedTimes
Stats() bufferStats
Tick(versions ShardBlockStateSnapshot, nsCtx namespace.Context) bufferTickResult
Load(bl block.DatabaseBlock, writeType WriteType)
Reset(id ident.ID, opts Options)
}
type bufferStats struct {
wiredBlocks int
}
type bufferTickResult struct {
mergedOutOfOrderBlocks int
evictedBucketTimes OptimizedTimes
}
// OptimizedTimes is a struct that holds an unknown number of times. This is
// used to avoid heap allocations as much as possible by trying to not allocate
// a slice of times. To do this, `optimizedTimesArraySize` needs to be
// strategically sized such that for the vast majority of the time, the internal
// array can hold all the times required so that `slice` is nil.
//
// OptimizedTimes should only be interacted with via its helper functions - its
// fields should never be accessed or modified directly, which could cause an
// invalid state.
type OptimizedTimes struct {
arrIdx int
arr [optimizedTimesArraySize]xtime.UnixNano
slice []xtime.UnixNano
}
// Add adds a time to this OptimizedTimes.
func (t *OptimizedTimes) Add(newTime xtime.UnixNano) {
if t.arrIdx < cap(t.arr) {
t.arr[t.arrIdx] = newTime
t.arrIdx++
} else {
t.slice = append(t.slice, newTime)
}
}
// Len returns the number of times in this OptimizedTimes.
func (t *OptimizedTimes) Len() int {
return t.arrIdx + len(t.slice)
}
// Contains returns whether the target time is in this OptimizedTimes.
func (t *OptimizedTimes) Contains(target xtime.UnixNano) bool {
for i := 0; i < t.arrIdx; i++ {
if t.arr[i].Equal(target) {
return true
}
}
for _, tt := range t.slice {
if tt.Equal(target) {
return true
}
}
return false
}
// ForEach runs the given function for each time in this OptimizedTimes.
func (t *OptimizedTimes) ForEach(fn func(t xtime.UnixNano)) {
for i, tNano := range t.arr {
if i >= t.arrIdx {
break
}
fn(tNano)
}
for _, tNano := range t.slice {
fn(tNano)
}
}
type dbBuffer struct {
id ident.ID
opts Options
nowFn clock.NowFn
// bucketsMap is a map from a block start to its corresponding bucket
// versions.
bucketsMap map[xtime.UnixNano]*BufferBucketVersions
// Cache of buckets to avoid map lookup of above.
bucketVersionsCache [bucketsCacheSize]*BufferBucketVersions
// This is an in order slice of the block starts in the bucketsMap.
// We maintain this to avoid sorting the map keys adhoc when we want to
// perform operations in chronological order.
inOrderBlockStarts []time.Time
bucketVersionsPool *BufferBucketVersionsPool
bucketPool *BufferBucketPool
blockSize time.Duration
bufferPast time.Duration
bufferFuture time.Duration
coldWritesEnabled bool
retentionPeriod time.Duration
futureRetentionPeriod time.Duration
}
// NB(prateek): databaseBuffer.Reset(...) must be called upon the returned
// object prior to use.
func newDatabaseBuffer() databaseBuffer {
b := &dbBuffer{
bucketsMap: make(map[xtime.UnixNano]*BufferBucketVersions),
inOrderBlockStarts: make([]time.Time, 0, bucketsCacheSize),
}
return b
}
func (b *dbBuffer) Reset(id ident.ID, opts Options) {
b.id = id
b.opts = opts
b.nowFn = opts.ClockOptions().NowFn()
ropts := opts.RetentionOptions()
b.bucketPool = opts.BufferBucketPool()
b.bucketVersionsPool = opts.BufferBucketVersionsPool()
b.blockSize = ropts.BlockSize()
b.bufferPast = ropts.BufferPast()
b.bufferFuture = ropts.BufferFuture()
b.coldWritesEnabled = opts.ColdWritesEnabled()
b.retentionPeriod = ropts.RetentionPeriod()
b.futureRetentionPeriod = ropts.FutureRetentionPeriod()
}
func (b *dbBuffer) Write(
ctx context.Context,
timestamp time.Time,
value float64,
unit xtime.Unit,
annotation []byte,
wOpts WriteOptions,
) (bool, error) {
var (
now = b.nowFn()
pastLimit = now.Add(-1 * b.bufferPast)
futureLimit = now.Add(b.bufferFuture)
writeType WriteType
)
switch {
case !pastLimit.Before(timestamp):
writeType = ColdWrite
if !b.coldWritesEnabled {
return false, xerrors.NewInvalidParamsError(
fmt.Errorf("datapoint too far in past: "+
"id=%s, off_by=%s, timestamp=%s, past_limit=%s, "+
"timestamp_unix_nanos=%d, past_limit_unix_nanos=%d",
b.id.Bytes(), pastLimit.Sub(timestamp).String(),
timestamp.Format(errTimestampFormat),
pastLimit.Format(errTimestampFormat),
timestamp.UnixNano(), pastLimit.UnixNano()))
}
case !futureLimit.After(timestamp):
writeType = ColdWrite
if !b.coldWritesEnabled {
return false, xerrors.NewInvalidParamsError(
fmt.Errorf("datapoint too far in future: "+
"id=%s, off_by=%s, timestamp=%s, future_limit=%s, "+
"timestamp_unix_nanos=%d, future_limit_unix_nanos=%d",
b.id.Bytes(), timestamp.Sub(futureLimit).String(),
timestamp.Format(errTimestampFormat),
futureLimit.Format(errTimestampFormat),
timestamp.UnixNano(), futureLimit.UnixNano()))
}
default:
writeType = WarmWrite
}
if writeType == ColdWrite {
if now.Add(-b.retentionPeriod).After(timestamp) {
return false, m3dberrors.ErrTooPast
}
if !now.Add(b.futureRetentionPeriod).Add(b.blockSize).After(timestamp) {
return false, m3dberrors.ErrTooFuture
}
b.opts.Stats().IncColdWrites()
}
blockStart := timestamp.Truncate(b.blockSize)
buckets := b.bucketVersionsAtCreate(blockStart)
b.putBucketVersionsInCache(buckets)
if wOpts.TruncateType == TypeBlock {
timestamp = blockStart
}
if wOpts.TransformOptions.ForceValueEnabled {
value = wOpts.TransformOptions.ForceValue
}
return buckets.write(timestamp, value, unit, annotation, writeType, wOpts.SchemaDesc)
}
func (b *dbBuffer) IsEmpty() bool {
// A buffer can only be empty if there are no buckets in its map, since
// buckets are only created when a write for a new block start is done, and
// buckets are removed from the map when they are evicted from memory.
return len(b.bucketsMap) == 0
}
func (b *dbBuffer) ColdFlushBlockStarts(blockStates map[xtime.UnixNano]BlockState) OptimizedTimes {
var times OptimizedTimes
for t, bucketVersions := range b.bucketsMap {
for _, bucket := range bucketVersions.buckets {
if bucket.writeType == ColdWrite &&
// We need to cold flush this bucket if it either:
// 1) Has new cold writes that need to be flushed, or
// 2) This bucket version is higher than what has been
// successfully flushed. This can happen if a cold flush was
// attempted, changing this bucket version, but fails to
// completely finish (which is what the shard block state
// signifies). In this case, we need to try to flush this
// bucket again.
(bucket.version == writableBucketVersion ||
blockStates[xtime.ToUnixNano(bucket.start)].ColdVersion < bucket.version) {
times.Add(t)
break
}
}
}
return times
}
func (b *dbBuffer) Stats() bufferStats {
return bufferStats{
wiredBlocks: len(b.bucketsMap),
}
}
func (b *dbBuffer) Tick(blockStates ShardBlockStateSnapshot, nsCtx namespace.Context) bufferTickResult {
mergedOutOfOrder := 0
var evictedBucketTimes OptimizedTimes
for tNano, buckets := range b.bucketsMap {
// The blockStates map is never written to after creation, so this
// read access is safe. Since this version map is a snapshot of the
// versions, the real block flush versions may be higher. This is okay
// here because it's safe to:
// 1) not remove a bucket that's actually retrievable, or
// 2) remove a lower versioned bucket.
// Retrievable and higher versioned buckets will be left to be
// collected in the next tick.
blockStateSnapshot, bootstrapped := blockStates.UnwrapValue()
// Only use block state snapshot information to make eviction decisions if the block state
// has been properly bootstrapped already.
if bootstrapped {
blockState := blockStateSnapshot.Snapshot[tNano]
if coldVersion := blockState.ColdVersion; blockState.WarmRetrievable || coldVersion > 0 {
if blockState.WarmRetrievable {
// Buckets for WarmWrites that are retrievable will only be version 1, since
// they only get successfully persisted once.
buckets.removeBucketsUpToVersion(WarmWrite, 1)
}
if coldVersion > 0 {
buckets.removeBucketsUpToVersion(ColdWrite, coldVersion)
}
if buckets.streamsLen() == 0 {
t := tNano.ToTime()
// All underlying buckets have been flushed successfully, so we can
// just remove the buckets from the bucketsMap.
b.removeBucketVersionsAt(t)
// Pass which bucket got evicted from the buffer to the series.
// Data gets read in order of precedence: buffer -> cache -> disk.
// After a bucket gets removed from the buffer, data from the cache
// will be served. However, since data just got persisted to disk,
// the cached block is now stale. To correct this, we can either:
// 1) evict the stale block from cache so that new data will
// be retrieved from disk, or
// 2) merge the new data into the cached block.
// It's unclear whether recently flushed data would frequently be
// read soon afterward, so we're choosing (1) here, since it has a
// simpler implementation (just removing from a map).
evictedBucketTimes.Add(tNano)
continue
}
}
}
// Once we've evicted all eligible buckets, we merge duplicate encoders
// in the remaining ones to try and reclaim memory.
merges, err := buckets.merge(WarmWrite, nsCtx)
if err != nil {
log := b.opts.InstrumentOptions().Logger()
log.Error("buffer merge encode error", zap.Error(err))
}
if merges > 0 {
mergedOutOfOrder++
}
}
return bufferTickResult{
mergedOutOfOrderBlocks: mergedOutOfOrder,
evictedBucketTimes: evictedBucketTimes,
}
}
func (b *dbBuffer) Load(bl block.DatabaseBlock, writeType WriteType) {
var (
blockStart = bl.StartTime()
buckets = b.bucketVersionsAtCreate(blockStart)
bucket = buckets.writableBucketCreate(writeType)
)
bucket.loadedBlocks = append(bucket.loadedBlocks, bl)
}
func (b *dbBuffer) Snapshot(
ctx context.Context,
blockStart time.Time,
id ident.ID,
tags ident.Tags,
persistFn persist.DataFn,
nsCtx namespace.Context,
) error {
buckets, exists := b.bucketVersionsAt(blockStart)
if !exists {
return nil
}
// Snapshot must take both cold and warm writes because cold flushes don't
// happen for the current block (since cold flushes can't happen before a
// warm flush has happened).
streams, err := buckets.mergeToStreams(ctx, streamsOptions{filterWriteType: false, nsCtx: nsCtx})
if err != nil {
return err
}
numStreams := len(streams)
var mergedStream xio.SegmentReader
if numStreams == 1 {
mergedStream = streams[0]
} else {
// We may need to merge again here because the regular merge method does
// not merge warm and cold buckets or buckets that have different versions.
sr := make([]xio.SegmentReader, 0, numStreams)
for _, stream := range streams {
sr = append(sr, stream)
}
bopts := b.opts.DatabaseBlockOptions()
encoder := bopts.EncoderPool().Get()
encoder.Reset(blockStart, bopts.DatabaseBlockAllocSize(), nsCtx.Schema)
iter := b.opts.MultiReaderIteratorPool().Get()
defer func() {
encoder.Close()
iter.Close()
}()
iter.Reset(sr, blockStart, b.opts.RetentionOptions().BlockSize(), nsCtx.Schema)
for iter.Next() {
dp, unit, annotation := iter.Current()
if err := encoder.Encode(dp, unit, annotation); err != nil {
return err
}
}
if err := iter.Err(); err != nil {
return err
}
var ok bool
mergedStream, ok = encoder.Stream(encoding.StreamOptions{})
if !ok {
// Don't write out series with no data.
return nil
}
}
segment, err := mergedStream.Segment()
if err != nil {
return err
}
if segment.Len() == 0 {
// Don't write out series with no data.
return nil
}
checksum := digest.SegmentChecksum(segment)
return persistFn(id, tags, segment, checksum)
}
func (b *dbBuffer) WarmFlush(
ctx context.Context,
blockStart time.Time,
id ident.ID,
tags ident.Tags,
persistFn persist.DataFn,
nsCtx namespace.Context,
) (FlushOutcome, error) {
buckets, exists := b.bucketVersionsAt(blockStart)
if !exists {
return FlushOutcomeBlockDoesNotExist, nil
}
// Flush only deals with WarmWrites. ColdWrites get persisted to disk via
// the compaction cycle.
streams, err := buckets.mergeToStreams(ctx, streamsOptions{filterWriteType: true, writeType: WarmWrite, nsCtx: nsCtx})
if err != nil {
return FlushOutcomeErr, err
}
var (
stream xio.SegmentReader
ok bool
)
if numStreams := len(streams); numStreams == 1 {
stream = streams[0]
ok = true
} else {
// In the majority of cases, there will only be one stream to persist
// here. Only when a previous flush fails midway through a shard will
// there be buckets for previous versions. In this case, we need to try
// to flush them again, so we merge them together to one stream and
// persist it.
encoder, _, err := mergeStreamsToEncoder(blockStart, streams, b.opts, nsCtx)
if err != nil {
return FlushOutcomeErr, err
}
stream, ok = encoder.Stream(encoding.StreamOptions{})
encoder.Close()
}
if !ok {
// Don't write out series with no data.
return FlushOutcomeBlockDoesNotExist, nil
}
segment, err := stream.Segment()
if err != nil {
return FlushOutcomeErr, err
}
if segment.Len() == 0 {
// Empty segment is equivalent to no stream, i.e data does not exist.
return FlushOutcomeBlockDoesNotExist, nil
}
checksum := digest.SegmentChecksum(segment)
err = persistFn(id, tags, segment, checksum)
if err != nil {
return FlushOutcomeErr, err
}
if bucket, exists := buckets.writableBucket(WarmWrite); exists {
// WarmFlushes only happen once per block, so it makes sense to always
// set this to 1.
bucket.version = 1
}
return FlushOutcomeFlushedToDisk, nil
}
func (b *dbBuffer) ReadEncoded(
ctx context.Context,
start time.Time,
end time.Time,
nsCtx namespace.Context,
) ([][]xio.BlockReader, error) {
// TODO(r): pool these results arrays
var res [][]xio.BlockReader
for _, blockStart := range b.inOrderBlockStarts {
if !blockStart.Before(end) || !start.Before(blockStart.Add(b.blockSize)) {
continue
}
bv, exists := b.bucketVersionsAt(blockStart)
if !exists {
// Invariant violated. This means the keys in the bucket map does
// not match the sorted keys cache, which should never happen.
instrument.EmitAndLogInvariantViolation(
b.opts.InstrumentOptions(), func(l *zap.Logger) {
l.Error(errBucketMapCacheNotInSync, zap.Int64("blockStart", blockStart.UnixNano()))
})
return nil, instrument.InvariantErrorf(
errBucketMapCacheNotInSyncFmt, blockStart.UnixNano())
}
if streams := bv.streams(ctx, streamsOptions{filterWriteType: false}); len(streams) > 0 {
res = append(res, streams)
}
// NB(r): Store the last read time, should not set this when
// calling FetchBlocks as a read is differentiated from
// a FetchBlocks call. One is initiated by an external
// entity and the other is used for streaming blocks between
// the storage nodes. This distinction is important as this
// data is important for use with understanding access patterns, etc.
bv.setLastRead(b.nowFn())
}
return res, nil
}
func (b *dbBuffer) FetchBlocksForColdFlush(
ctx context.Context,
start time.Time,
version int,
nsCtx namespace.Context,
) ([]xio.BlockReader, error) {
res := b.fetchBlocks(ctx, []time.Time{start},
streamsOptions{filterWriteType: true, writeType: ColdWrite, nsCtx: nsCtx})
if len(res) == 0 {
// The lifecycle of calling this function is preceded by first checking
// which blocks have cold data that have not yet been flushed.
// If we don't get data here, it means that it has since fallen out of
// retention and has been evicted.
return nil, nil
}
if len(res) != 1 {
// Must be only one result if anything at all, since fetchBlocks returns
// one result per block start.
return nil, fmt.Errorf("fetchBlocks did not return just one block for block start %s", start)
}
blocks := res[0].Blocks
buckets, exists := b.bucketVersionsAt(start)
if !exists {
return nil, fmt.Errorf("buckets do not exist with block start %s", start)
}
if bucket, exists := buckets.writableBucket(ColdWrite); exists {
bucket.version = version
} else {
return nil, fmt.Errorf("writable bucket does not exist with block start %s", start)
}
return blocks, nil
}
func (b *dbBuffer) FetchBlocks(ctx context.Context, starts []time.Time, nsCtx namespace.Context) []block.FetchBlockResult {
return b.fetchBlocks(ctx, starts, streamsOptions{filterWriteType: false, nsCtx: nsCtx})
}
func (b *dbBuffer) fetchBlocks(
ctx context.Context,
starts []time.Time,
sOpts streamsOptions,
) []block.FetchBlockResult {
var res []block.FetchBlockResult
for _, start := range starts {
buckets, ok := b.bucketVersionsAt(start)
if !ok {
continue
}
if streams := buckets.streams(ctx, sOpts); len(streams) > 0 {
res = append(res, block.NewFetchBlockResult(start, streams, nil))
}
}
// Result should be sorted in ascending order.
sort.Slice(res, func(i, j int) bool { return res[i].Start.Before(res[j].Start) })
return res
}
func (b *dbBuffer) FetchBlocksMetadata(
ctx context.Context,
start, end time.Time,
opts FetchBlocksMetadataOptions,
) (block.FetchBlockMetadataResults, error) {
blockSize := b.opts.RetentionOptions().BlockSize()
res := b.opts.FetchBlockMetadataResultsPool().Get()
for _, blockStart := range b.inOrderBlockStarts {
if !blockStart.Before(end) || !start.Before(blockStart.Add(blockSize)) {
continue
}
bv, exists := b.bucketVersionsAt(blockStart)
if !exists {
// Invariant violated. This means the keys in the bucket map does
// not match the sorted keys cache, which should never happen.
instrument.EmitAndLogInvariantViolation(
b.opts.InstrumentOptions(), func(l *zap.Logger) {
l.Error(errBucketMapCacheNotInSync, zap.Int64("blockStart", blockStart.UnixNano()))
})
return nil, instrument.InvariantErrorf(errBucketMapCacheNotInSyncFmt, blockStart.UnixNano())
}
size := int64(bv.streamsLen())
// If we have no data in this bucket, skip early without appending it to the result.
if size == 0 {
continue
}
var resultSize int64
if opts.IncludeSizes {
resultSize = size
}
var resultLastRead time.Time
if opts.IncludeLastRead {
resultLastRead = bv.lastRead()
}
var (
checksum *uint32
err error
)
if opts.IncludeChecksums {
// Checksum calculations are best effort since we can't calculate one if there
// are multiple streams without performing an expensive merge.
checksum, err = bv.checksumIfSingleStream()
if err != nil {
return nil, err
}
}
res.Add(block.FetchBlockMetadataResult{
Start: bv.start,
Size: resultSize,
LastRead: resultLastRead,
Checksum: checksum,
})
}
return res, nil
}
func (b *dbBuffer) bucketVersionsAt(
t time.Time,
) (*BufferBucketVersions, bool) {
// First check LRU cache.
for _, buckets := range b.bucketVersionsCache {
if buckets == nil {
continue
}
if buckets.start.Equal(t) {
return buckets, true
}
}
// Then check the map.
if buckets, exists := b.bucketsMap[xtime.ToUnixNano(t)]; exists {
return buckets, true
}
return nil, false
}
func (b *dbBuffer) bucketVersionsAtCreate(
t time.Time,
) *BufferBucketVersions {
if buckets, exists := b.bucketVersionsAt(t); exists {
return buckets
}
buckets := b.bucketVersionsPool.Get()
buckets.resetTo(t, b.opts, b.bucketPool)
b.bucketsMap[xtime.ToUnixNano(t)] = buckets
b.inOrderBlockStartsAdd(t)
return buckets
}
func (b *dbBuffer) putBucketVersionsInCache(newBuckets *BufferBucketVersions) {
replaceIdx := bucketsCacheSize - 1
for i, buckets := range b.bucketVersionsCache {
// Check if we have the same pointer in cache.
if buckets == newBuckets {
replaceIdx = i
}
}
for i := replaceIdx; i > 0; i-- {
b.bucketVersionsCache[i] = b.bucketVersionsCache[i-1]
}
b.bucketVersionsCache[0] = newBuckets
}
func (b *dbBuffer) removeBucketVersionsInCache(oldBuckets *BufferBucketVersions) {
nilIdx := -1
for i, buckets := range b.bucketVersionsCache {
if buckets == oldBuckets {
nilIdx = i
}
}
if nilIdx == -1 {
return
}
for i := nilIdx; i < bucketsCacheSize-1; i++ {
b.bucketVersionsCache[i] = b.bucketVersionsCache[i+1]
}
b.bucketVersionsCache[bucketsCacheSize-1] = nil
}
func (b *dbBuffer) removeBucketVersionsAt(blockStart time.Time) {
buckets, exists := b.bucketVersionsAt(blockStart)
if !exists {
return
}
delete(b.bucketsMap, xtime.ToUnixNano(blockStart))
b.removeBucketVersionsInCache(buckets)
b.inOrderBlockStartsRemove(blockStart)
// nil out pointers.
buckets.resetTo(timeZero, nil, nil)
b.bucketVersionsPool.Put(buckets)
}
func (b *dbBuffer) inOrderBlockStartsAdd(newTime time.Time) {
starts := b.inOrderBlockStarts
idx := len(starts)
// There shouldn't be that many starts here, so just linear search through.
for i, t := range starts {
if t.After(newTime) {
idx = i
break
}
}
// Insert new time without allocating new slice.
b.inOrderBlockStarts = append(starts, timeZero)
// Update to new slice
starts = b.inOrderBlockStarts
copy(starts[idx+1:], starts[idx:])
starts[idx] = newTime
}
func (b *dbBuffer) inOrderBlockStartsRemove(removeTime time.Time) {
starts := b.inOrderBlockStarts
// There shouldn't be that many starts here, so just linear search through.
for i, t := range starts {
if t.Equal(removeTime) {
b.inOrderBlockStarts = append(starts[:i], starts[i+1:]...)
return
}
}
}
// BufferBucketVersions is a container for different versions of buffer buckets.
// Bucket versions are how the buffer separates writes that have been written
// to disk as a fileset and writes that have not. The bucket with a version of
// `writableBucketVersion` is the bucket that all writes go into (as thus is the
// bucket version that have not yet been persisted). After a bucket gets
// persisted, its version gets set to a version that the shard passes down to it
// (since the shard knows what has been fully persisted to disk).
type BufferBucketVersions struct {
buckets []*BufferBucket
start time.Time
opts Options
lastReadUnixNanos int64
bucketPool *BufferBucketPool
}
func (b *BufferBucketVersions) resetTo(
start time.Time,
opts Options,
bucketPool *BufferBucketPool,
) {
// nil all elements so that they get GC'd.
for i := range b.buckets {
b.buckets[i] = nil
}
b.buckets = b.buckets[:0]
b.start = start
b.opts = opts
atomic.StoreInt64(&b.lastReadUnixNanos, 0)
b.bucketPool = bucketPool
}
// streams returns all the streams for this BufferBucketVersions.
func (b *BufferBucketVersions) streams(ctx context.Context, opts streamsOptions) []xio.BlockReader {
var res []xio.BlockReader
for _, bucket := range b.buckets {
if !opts.filterWriteType || bucket.writeType == opts.writeType {
res = append(res, bucket.streams(ctx)...)
}
}
return res
}
func (b *BufferBucketVersions) streamsLen() int {
res := 0
for _, bucket := range b.buckets {
res += bucket.streamsLen()
}
return res
}
func (b *BufferBucketVersions) checksumIfSingleStream() (*uint32, error) {
if len(b.buckets) != 1 {
return nil, nil
}
return b.buckets[0].checksumIfSingleStream()
}
func (b *BufferBucketVersions) write(
timestamp time.Time,
value float64,
unit xtime.Unit,
annotation []byte,
writeType WriteType,
schema namespace.SchemaDescr,
) (bool, error) {
return b.writableBucketCreate(writeType).write(timestamp, value, unit, annotation, schema)
}
func (b *BufferBucketVersions) merge(writeType WriteType, nsCtx namespace.Context) (int, error) {
res := 0
for _, bucket := range b.buckets {
// Only makes sense to merge buckets that are writable.
if bucket.version == writableBucketVersion && writeType == bucket.writeType {
merges, err := bucket.merge(nsCtx)
if err != nil {
return 0, err
}
res += merges
}
}
return res, nil
}
func (b *BufferBucketVersions) removeBucketsUpToVersion(
writeType WriteType,
version int,
) {
// Avoid allocating a new backing array.
nonEvictedBuckets := b.buckets[:0]
for _, bucket := range b.buckets {
bVersion := bucket.version
if bucket.writeType == writeType && bVersion != writableBucketVersion &&
bVersion <= version {
// We no longer need to keep any version which is equal to
// or less than the retrievable version, since that means
// that the version has successfully persisted to disk.
// Bucket gets reset before use.
b.bucketPool.Put(bucket)
continue
}
nonEvictedBuckets = append(nonEvictedBuckets, bucket)
}
b.buckets = nonEvictedBuckets
}
func (b *BufferBucketVersions) setLastRead(value time.Time) {
atomic.StoreInt64(&b.lastReadUnixNanos, value.UnixNano())
}
func (b *BufferBucketVersions) lastRead() time.Time {
return time.Unix(0, atomic.LoadInt64(&b.lastReadUnixNanos))
}
func (b *BufferBucketVersions) writableBucket(writeType WriteType) (*BufferBucket, bool) {
for _, bucket := range b.buckets {
if bucket.version == writableBucketVersion && bucket.writeType == writeType {
return bucket, true
}
}
return nil, false
}
func (b *BufferBucketVersions) writableBucketCreate(writeType WriteType) *BufferBucket {
bucket, exists := b.writableBucket(writeType)
if exists {