-
Notifications
You must be signed in to change notification settings - Fork 453
/
index.go
2822 lines (2480 loc) · 88.3 KB
/
index.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) 2020 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 storage
import (
"bytes"
"errors"
"fmt"
"io"
"math"
goruntime "runtime"
"sort"
"strconv"
"sync"
"time"
"github.com/m3db/m3/src/dbnode/namespace"
"github.com/m3db/m3/src/dbnode/persist"
"github.com/m3db/m3/src/dbnode/persist/fs"
"github.com/m3db/m3/src/dbnode/retention"
"github.com/m3db/m3/src/dbnode/runtime"
"github.com/m3db/m3/src/dbnode/sharding"
"github.com/m3db/m3/src/dbnode/storage/block"
"github.com/m3db/m3/src/dbnode/storage/bootstrap/result"
m3dberrors "github.com/m3db/m3/src/dbnode/storage/errors"
"github.com/m3db/m3/src/dbnode/storage/index"
"github.com/m3db/m3/src/dbnode/storage/index/compaction"
"github.com/m3db/m3/src/dbnode/storage/index/convert"
"github.com/m3db/m3/src/dbnode/storage/limits"
"github.com/m3db/m3/src/dbnode/storage/limits/permits"
"github.com/m3db/m3/src/dbnode/storage/series"
"github.com/m3db/m3/src/dbnode/tracepoint"
"github.com/m3db/m3/src/dbnode/ts/writes"
"github.com/m3db/m3/src/m3ninx/doc"
"github.com/m3db/m3/src/m3ninx/idx"
m3ninxindex "github.com/m3db/m3/src/m3ninx/index"
"github.com/m3db/m3/src/m3ninx/index/segment"
"github.com/m3db/m3/src/m3ninx/index/segment/builder"
idxpersist "github.com/m3db/m3/src/m3ninx/persist"
"github.com/m3db/m3/src/m3ninx/x"
"github.com/m3db/m3/src/x/clock"
"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"
xopentracing "github.com/m3db/m3/src/x/opentracing"
xresource "github.com/m3db/m3/src/x/resource"
xtime "github.com/m3db/m3/src/x/time"
"github.com/m3db/bitset"
"github.com/opentracing/opentracing-go"
opentracinglog "github.com/opentracing/opentracing-go/log"
"github.com/uber-go/tally"
"go.uber.org/atomic"
"go.uber.org/zap"
)
var (
errDbIndexAlreadyClosed = errors.New("database index has already been closed")
errDbIndexUnableToWriteClosed = errors.New("unable to write to database index, already closed")
errDbIndexUnableToQueryClosed = errors.New("unable to query database index, already closed")
errDbIndexUnableToFlushClosed = errors.New("unable to flush database index, already closed")
errDbIndexUnableToCleanupClosed = errors.New("unable to cleanup database index, already closed")
errDbIndexTerminatingTickCancellation = errors.New("terminating tick early due to cancellation")
errDbIndexIsBootstrapping = errors.New("index is already bootstrapping")
errDbIndexDoNotIndexSeries = errors.New("series matched do not index fields")
)
const (
defaultFlushReadDataBlocksBatchSize = int64(4096)
nsIndexReportStatsInterval = 10 * time.Second
defaultFlushDocsBatchSize = 8192
)
var allQuery = idx.NewAllQuery()
// nolint: maligned
type nsIndex struct {
state nsIndexState
// all the vars below this line are not modified past the ctor
// and don't require a lock when being accessed.
nowFn clock.NowFn
blockSize time.Duration
retentionPeriod time.Duration
futureRetentionPeriod time.Duration
bufferPast time.Duration
bufferFuture time.Duration
coldWritesEnabled bool
namespaceRuntimeOptsMgr namespace.RuntimeOptionsManager
indexFilesetsBeforeFn indexFilesetsBeforeFn
deleteFilesFn deleteFilesFn
readIndexInfoFilesFn readIndexInfoFilesFn
newBlockFn index.NewBlockFn
logger *zap.Logger
opts Options
nsMetadata namespace.Metadata
runtimeOptsListener xresource.SimpleCloser
runtimeNsOptsListener xresource.SimpleCloser
resultsPool index.QueryResultsPool
aggregateResultsPool index.AggregateResultsPool
permitsManager permits.Manager
// queriesWg tracks outstanding queries to ensure
// we wait for all queries to complete before actually closing
// blocks and other cleanup tasks on index close
queriesWg sync.WaitGroup
metrics nsIndexMetrics
// forwardIndexDice determines if an incoming index write should be dual
// written to the next block.
forwardIndexDice forwardIndexDice
doNotIndexWithFields []doc.Field
shardSet sharding.ShardSet
activeBlock index.Block
}
type nsIndexState struct {
sync.RWMutex // NB: guards all variables in this struct
closed bool
closeCh chan struct{}
bootstrapState BootstrapState
runtimeOpts nsIndexRuntimeOptions
insertQueue namespaceIndexInsertQueue
// NB: `latestBlock` v `blocksByTime`: blocksByTime contains all the blocks known to `nsIndex`.
// `latestBlock` refers to the block with greatest StartTime within blocksByTime. We do this
// to skip accessing the map blocksByTime in the vast majority of write/query requests. It's
// lazily updated, so it can point to an older element until a Tick()/write rotates it.
blocksByTime map[xtime.UnixNano]index.Block
latestBlock index.Block
// NB: `blockStartsDescOrder` contains the keys from the map `blocksByTime` in reverse
// chronological order. This is used at query time to enforce determinism about results
// returned.
// NB(r): Reference to this slice can be safely taken for iteration purposes
// for Query(..) since it is rebuilt each time and immutable once built.
blocksDescOrderImmutable []blockAndBlockStart
// shardsFilterID is set every time the shards change to correctly
// only return IDs that this node owns.
shardsFilterID func(ident.ID) bool
// shardFilteredForID is set every time the shards change to correctly
// only return IDs that this node owns, and the shard responsible for that ID.
shardFilteredForID func(id ident.ID) (uint32, bool)
shardsAssigned map[uint32]struct{}
}
type blockAndBlockStart struct {
block index.Block
blockStart xtime.UnixNano
}
// NB: nsIndexRuntimeOptions does not contain its own mutex as some of the variables
// are needed for each index write which already at least acquires read lock from
// nsIndex mutex, so to keep the lock acquisitions to a minimum these are protected
// under the same nsIndex mutex.
type nsIndexRuntimeOptions struct {
insertMode index.InsertMode
maxQuerySeriesLimit int64
maxQueryDocsLimit int64
}
// NB(prateek): the returned filesets are strictly before the given time, i.e. they
// live in the period (-infinity, exclusiveTime).
type indexFilesetsBeforeFn func(dir string,
nsID ident.ID,
exclusiveTime xtime.UnixNano,
) ([]string, error)
type readIndexInfoFilesFn func(opts fs.ReadIndexInfoFilesOptions) []fs.ReadIndexInfoFileResult
type newNamespaceIndexOpts struct {
md namespace.Metadata
namespaceRuntimeOptsMgr namespace.RuntimeOptionsManager
shardSet sharding.ShardSet
opts Options
newIndexQueueFn newNamespaceIndexInsertQueueFn
newBlockFn index.NewBlockFn
}
// execBlockQueryFn executes a query against the given block whilst tracking state.
type execBlockQueryFn func(
ctx context.Context,
block index.Block,
permit permits.Permit,
iter index.ResultIterator,
opts index.QueryOptions,
state *asyncQueryExecState,
results index.BaseResults,
logFields []opentracinglog.Field,
)
// newBlockIterFn returns a new ResultIterator for the query.
type newBlockIterFn func(
ctx context.Context,
block index.Block,
query index.Query,
results index.BaseResults,
) (index.ResultIterator, error)
// asyncQueryExecState tracks the async execution errors for a query.
type asyncQueryExecState struct {
sync.RWMutex
multiErr xerrors.MultiError
waitCount atomic.Uint64
}
func (s *asyncQueryExecState) hasErr() bool {
s.RLock()
defer s.RUnlock()
return s.multiErr.NumErrors() > 0
}
func (s *asyncQueryExecState) addErr(err error) {
s.Lock()
s.multiErr = s.multiErr.Add(err)
s.Unlock()
}
func (s *asyncQueryExecState) incWaited(i int) {
s.waitCount.Add(uint64(i))
}
func (s *asyncQueryExecState) waited() int {
return int(s.waitCount.Load())
}
// newNamespaceIndex returns a new namespaceIndex for the provided namespace.
func newNamespaceIndex(
nsMD namespace.Metadata,
namespaceRuntimeOptsMgr namespace.RuntimeOptionsManager,
shardSet sharding.ShardSet,
opts Options,
) (NamespaceIndex, error) {
return newNamespaceIndexWithOptions(newNamespaceIndexOpts{
md: nsMD,
namespaceRuntimeOptsMgr: namespaceRuntimeOptsMgr,
shardSet: shardSet,
opts: opts,
newIndexQueueFn: newNamespaceIndexInsertQueue,
newBlockFn: index.NewBlock,
})
}
// newNamespaceIndexWithInsertQueueFn is a ctor used in tests to override the insert queue.
func newNamespaceIndexWithInsertQueueFn(
nsMD namespace.Metadata,
namespaceRuntimeOptsMgr namespace.RuntimeOptionsManager,
shardSet sharding.ShardSet,
newIndexQueueFn newNamespaceIndexInsertQueueFn,
opts Options,
) (NamespaceIndex, error) {
return newNamespaceIndexWithOptions(newNamespaceIndexOpts{
md: nsMD,
namespaceRuntimeOptsMgr: namespaceRuntimeOptsMgr,
shardSet: shardSet,
opts: opts,
newIndexQueueFn: newIndexQueueFn,
newBlockFn: index.NewBlock,
})
}
// newNamespaceIndexWithNewBlockFn is a ctor used in tests to inject blocks.
func newNamespaceIndexWithNewBlockFn(
nsMD namespace.Metadata,
namespaceRuntimeOptsMgr namespace.RuntimeOptionsManager,
shardSet sharding.ShardSet,
newBlockFn index.NewBlockFn,
opts Options,
) (NamespaceIndex, error) {
return newNamespaceIndexWithOptions(newNamespaceIndexOpts{
md: nsMD,
namespaceRuntimeOptsMgr: namespaceRuntimeOptsMgr,
shardSet: shardSet,
opts: opts,
newIndexQueueFn: newNamespaceIndexInsertQueue,
newBlockFn: newBlockFn,
})
}
// newNamespaceIndexWithOptions returns a new namespaceIndex with the provided configuration options.
func newNamespaceIndexWithOptions(
newIndexOpts newNamespaceIndexOpts,
) (NamespaceIndex, error) {
var (
nsMD = newIndexOpts.md
shardSet = newIndexOpts.shardSet
indexOpts = newIndexOpts.opts.IndexOptions()
instrumentOpts = newIndexOpts.opts.InstrumentOptions()
newIndexQueueFn = newIndexOpts.newIndexQueueFn
newBlockFn = newIndexOpts.newBlockFn
runtimeOptsMgr = newIndexOpts.opts.RuntimeOptionsManager()
)
if err := indexOpts.Validate(); err != nil {
return nil, err
}
scope := instrumentOpts.MetricsScope().
SubScope("dbindex").
Tagged(map[string]string{
"namespace": nsMD.ID().String(),
})
instrumentOpts = instrumentOpts.SetMetricsScope(scope)
indexOpts = indexOpts.SetInstrumentOptions(instrumentOpts)
nowFn := indexOpts.ClockOptions().NowFn()
logger := indexOpts.InstrumentOptions().Logger()
var doNotIndexWithFields []doc.Field
if m := newIndexOpts.opts.DoNotIndexWithFieldsMap(); m != nil && len(m) != 0 {
for k, v := range m {
doNotIndexWithFields = append(doNotIndexWithFields, doc.Field{
Name: []byte(k),
Value: []byte(v),
})
}
}
idx := &nsIndex{
state: nsIndexState{
closeCh: make(chan struct{}),
runtimeOpts: nsIndexRuntimeOptions{
insertMode: indexOpts.InsertMode(), // FOLLOWUP(prateek): wire to allow this to be tweaked at runtime
},
blocksByTime: make(map[xtime.UnixNano]index.Block),
shardsAssigned: make(map[uint32]struct{}),
},
nowFn: nowFn,
blockSize: nsMD.Options().IndexOptions().BlockSize(),
retentionPeriod: nsMD.Options().RetentionOptions().RetentionPeriod(),
futureRetentionPeriod: nsMD.Options().RetentionOptions().FutureRetentionPeriod(),
bufferPast: nsMD.Options().RetentionOptions().BufferPast(),
bufferFuture: nsMD.Options().RetentionOptions().BufferFuture(),
coldWritesEnabled: nsMD.Options().ColdWritesEnabled(),
namespaceRuntimeOptsMgr: newIndexOpts.namespaceRuntimeOptsMgr,
indexFilesetsBeforeFn: fs.IndexFileSetsBefore,
readIndexInfoFilesFn: fs.ReadIndexInfoFiles,
deleteFilesFn: fs.DeleteFiles,
newBlockFn: newBlockFn,
opts: newIndexOpts.opts,
logger: logger,
nsMetadata: nsMD,
resultsPool: indexOpts.QueryResultsPool(),
aggregateResultsPool: indexOpts.AggregateResultsPool(),
permitsManager: newIndexOpts.opts.PermitsOptions().IndexQueryPermitsManager(),
metrics: newNamespaceIndexMetrics(indexOpts, instrumentOpts),
doNotIndexWithFields: doNotIndexWithFields,
shardSet: shardSet,
}
activeBlock, err := idx.newBlockFn(xtime.UnixNano(0), idx.nsMetadata,
index.BlockOptions{ActiveBlock: true}, idx.namespaceRuntimeOptsMgr,
idx.opts.IndexOptions())
if err != nil {
return nil, idx.unableToAllocBlockInvariantError(err)
}
idx.activeBlock = activeBlock
// Assign shard set upfront.
idx.AssignShardSet(shardSet)
idx.runtimeOptsListener = runtimeOptsMgr.RegisterListener(idx)
idx.runtimeNsOptsListener = idx.namespaceRuntimeOptsMgr.RegisterListener(idx)
// set up forward index dice.
dice, err := newForwardIndexDice(newIndexOpts.opts)
if err != nil {
return nil, err
}
if dice.enabled {
logger.Info("namespace forward indexing configured",
zap.Stringer("namespace", nsMD.ID()),
zap.Bool("enabled", dice.enabled),
zap.Duration("threshold", dice.forwardIndexThreshold),
zap.Float64("rate", dice.forwardIndexDice.Rate()))
} else {
idxOpts := newIndexOpts.opts.IndexOptions()
logger.Info("namespace forward indexing not enabled",
zap.Stringer("namespace", nsMD.ID()),
zap.Bool("enabled", false),
zap.Float64("threshold", idxOpts.ForwardIndexThreshold()),
zap.Float64("probability", idxOpts.ForwardIndexProbability()))
}
idx.forwardIndexDice = dice
// allocate indexing queue and start it up.
queue := newIndexQueueFn(idx.writeBatches, nsMD, nowFn, scope)
if err := queue.Start(); err != nil {
return nil, err
}
idx.state.insertQueue = queue
// allocate the current block to ensure we're able to index as soon as we return
currentBlock := xtime.ToUnixNano(nowFn()).Truncate(idx.blockSize)
idx.state.RLock()
_, err = idx.ensureBlockPresentWithRLock(currentBlock)
idx.state.RUnlock()
if err != nil {
return nil, err
}
// Report stats
go idx.reportStatsUntilClosed()
return idx, nil
}
func (i *nsIndex) SetRuntimeOptions(runtime.Options) {
}
func (i *nsIndex) SetNamespaceRuntimeOptions(opts namespace.RuntimeOptions) {
// We don't like to log from every single index segment that has
// settings updated so we log the changes here.
i.logger.Info("set namespace runtime index options",
zap.Stringer("namespace", i.nsMetadata.ID()),
zap.Any("writeIndexingPerCPUConcurrency", opts.WriteIndexingPerCPUConcurrency()),
zap.Any("flushIndexingPerCPUConcurrency", opts.FlushIndexingPerCPUConcurrency()))
}
func (i *nsIndex) reportStatsUntilClosed() {
ticker := time.NewTicker(nsIndexReportStatsInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
err := i.reportStats()
if err != nil {
i.logger.Warn("could not report index stats", zap.Error(err))
}
case <-i.state.closeCh:
return
}
}
}
type nsIndexCompactionLevelStats struct {
numSegments int64
numTotalDocs int64
}
func (i *nsIndex) reportStats() error {
i.state.RLock()
defer i.state.RUnlock()
foregroundLevels := i.metrics.blockMetrics.ForegroundSegments.Levels
foregroundLevelStats := make([]nsIndexCompactionLevelStats, len(foregroundLevels))
backgroundLevels := i.metrics.blockMetrics.BackgroundSegments.Levels
backgroundLevelStats := make([]nsIndexCompactionLevelStats, len(backgroundLevels))
flushedLevels := i.metrics.blockMetrics.FlushedSegments.Levels
flushedLevelStats := make([]nsIndexCompactionLevelStats, len(flushedLevels))
minIndexConcurrency := 0
maxIndexConcurrency := 0
sumIndexConcurrency := 0
numIndexingStats := 0
reporter := index.NewBlockStatsReporter(
func(s index.BlockSegmentStats) {
var (
levels []nsIndexBlocksSegmentsLevelMetrics
levelStats []nsIndexCompactionLevelStats
)
switch s.Type {
case index.ActiveForegroundSegment:
levels = foregroundLevels
levelStats = foregroundLevelStats
case index.ActiveBackgroundSegment:
levels = backgroundLevels
levelStats = backgroundLevelStats
case index.FlushedSegment:
levels = flushedLevels
levelStats = flushedLevelStats
}
for i, l := range levels {
contained := s.Size >= l.MinSizeInclusive && s.Size < l.MaxSizeExclusive
if !contained {
continue
}
l.SegmentsAge.Record(s.Age)
levelStats[i].numSegments++
levelStats[i].numTotalDocs += s.Size
break
}
},
func(s index.BlockIndexingStats) {
first := numIndexingStats == 0
numIndexingStats++
if first {
minIndexConcurrency = s.IndexConcurrency
maxIndexConcurrency = s.IndexConcurrency
sumIndexConcurrency = s.IndexConcurrency
return
}
if v := s.IndexConcurrency; v < minIndexConcurrency {
minIndexConcurrency = v
}
if v := s.IndexConcurrency; v > maxIndexConcurrency {
maxIndexConcurrency = v
}
sumIndexConcurrency += s.IndexConcurrency
})
// iterate known blocks in a defined order of time (newest first)
// for debug log ordering
for _, b := range i.state.blocksDescOrderImmutable {
err := b.block.Stats(reporter)
if err == index.ErrUnableReportStatsBlockClosed {
// Closed blocks are temporarily in the list still
continue
}
if err != nil {
return err
}
}
// Active block should always be open.
if err := i.activeBlock.Stats(reporter); err != nil {
return err
}
// Update level stats.
for _, elem := range []struct {
levels []nsIndexBlocksSegmentsLevelMetrics
levelStats []nsIndexCompactionLevelStats
}{
{foregroundLevels, foregroundLevelStats},
{backgroundLevels, backgroundLevelStats},
} {
for i, v := range elem.levelStats {
elem.levels[i].NumSegments.Update(float64(v.numSegments))
elem.levels[i].NumTotalDocs.Update(float64(v.numTotalDocs))
}
}
// Update the indexing stats.
i.metrics.indexingConcurrencyMin.Update(float64(minIndexConcurrency))
i.metrics.indexingConcurrencyMax.Update(float64(maxIndexConcurrency))
avgIndexConcurrency := float64(sumIndexConcurrency) / float64(numIndexingStats)
i.metrics.indexingConcurrencyAvg.Update(avgIndexConcurrency)
return nil
}
func (i *nsIndex) BlockStartForWriteTime(writeTime xtime.UnixNano) xtime.UnixNano {
return writeTime.Truncate(i.blockSize)
}
func (i *nsIndex) BlockForBlockStart(blockStart xtime.UnixNano) (index.Block, error) {
result, err := i.ensureBlockPresent(blockStart)
if err != nil {
return nil, err
}
return result.block, nil
}
// NB(prateek): including the call chains leading to this point:
//
// - For new entry (previously unseen in the shard):
// shard.WriteTagged()
// => shard.insertSeriesAsyncBatched()
// => shardInsertQueue.Insert()
// => shard.writeBatch()
// => index.WriteBatch()
// => indexQueue.Insert()
// => index.writeBatch()
//
// - For entry which exists in the shard, but needs indexing (either past
// the TTL or the last indexing hasn't happened/failed):
// shard.WriteTagged()
// => shard.insertSeriesForIndexingAsyncBatched()
// => shardInsertQueue.Insert()
// => shard.writeBatch()
// => index.Write()
// => indexQueue.Insert()
// => index.writeBatch()
func (i *nsIndex) WriteBatch(
batch *index.WriteBatch,
) error {
// Filter anything with a pending index out before acquiring lock.
batch.MarkUnmarkedIfAlreadyIndexedSuccessAndFinalize()
if !batch.PendingAny() {
return nil
}
i.state.RLock()
if !i.isOpenWithRLock() {
i.state.RUnlock()
i.metrics.insertAfterClose.Inc(1)
err := errDbIndexUnableToWriteClosed
batch.MarkUnmarkedEntriesError(err)
return err
}
// NB(prateek): retrieving insertMode here while we have the RLock.
insertMode := i.state.runtimeOpts.insertMode
wg, err := i.state.insertQueue.InsertBatch(batch)
// release the lock because we don't need it past this point.
i.state.RUnlock()
// if we're unable to index, we still have to finalize the reference we hold.
if err != nil {
batch.MarkUnmarkedEntriesError(err)
return err
}
// once the write has been queued in the indexInsertQueue, it assumes
// responsibility for calling the resource hooks.
// wait/terminate depending on if we are indexing synchronously or not.
if insertMode != index.InsertAsync {
wg.Wait()
// Re-sort the batch by initial enqueue order
if numErrs := batch.NumErrs(); numErrs > 0 {
// Restore the sort order from when enqueued for the caller.
batch.SortByEnqueued()
return fmt.Errorf("check batch: %d insert errors", numErrs)
}
}
return nil
}
func (i *nsIndex) WritePending(
pending []writes.PendingIndexInsert,
) error {
// Filter anything with a pending index out before acquiring lock.
incoming := pending
pending = pending[:0]
for j := range incoming {
t := i.BlockStartForWriteTime(incoming[j].Entry.Timestamp)
if incoming[j].Entry.OnIndexSeries.IfAlreadyIndexedMarkIndexSuccessAndFinalize(t) {
continue
}
// Continue to add this element.
pending = append(pending, incoming[j])
}
if len(pending) == 0 {
return nil
}
i.state.RLock()
if !i.isOpenWithRLock() {
i.state.RUnlock()
i.metrics.insertAfterClose.Inc(1)
return errDbIndexUnableToWriteClosed
}
_, err := i.state.insertQueue.InsertPending(pending)
// release the lock because we don't need it past this point.
i.state.RUnlock()
return err
}
// WriteBatches is called by the indexInsertQueue.
func (i *nsIndex) writeBatches(
batch *index.WriteBatch,
) {
// NB(prateek): we use a read lock to guard against mutation of the
// indexBlocks, mutations within the underlying blocks are guarded
// by primitives internal to it.
i.state.RLock()
if !i.isOpenWithRLock() {
i.state.RUnlock()
// NB(prateek): deliberately skip calling any of the `OnIndexFinalize` methods
// on the provided inserts to terminate quicker during shutdown.
return
}
var (
now = xtime.ToUnixNano(i.nowFn())
blockSize = i.blockSize
futureLimit = now.Add(1 * i.bufferFuture)
pastLimit = now.Add(-1 * i.bufferPast)
earliestBlockStartToRetain = retention.FlushTimeStartForRetentionPeriod(i.retentionPeriod, i.blockSize, now)
batchOptions = batch.Options()
forwardIndexDice = i.forwardIndexDice
forwardIndexEnabled = forwardIndexDice.enabled
total int
notSkipped int
forwardIndexHits int
forwardIndexMiss int
forwardIndexBatch *index.WriteBatch
)
// NB(r): Release lock early to avoid writing batches impacting ticking
// speed, etc.
// Sometimes foreground compaction can take a long time during heavy inserts.
// Each lookup to ensureBlockPresent checks that index is still open, etc.
i.state.RUnlock()
if forwardIndexEnabled {
// NB(arnikola): Don't initialize forward index batch if forward indexing
// is not enabled.
forwardIndexBatch = index.NewWriteBatch(batchOptions)
}
// Ensure timestamp is not too old/new based on retention policies and that
// doc is valid. Add potential forward writes to the forwardWriteBatch.
batch.ForEach(
func(idx int, entry index.WriteBatchEntry,
d doc.Metadata, _ index.WriteBatchEntryResult) {
total++
if len(i.doNotIndexWithFields) != 0 {
// This feature rarely used, do not optimize and just do n*m checks.
drop := true
for _, matchField := range i.doNotIndexWithFields {
matchedField := false
for _, actualField := range d.Fields {
if bytes.Equal(actualField.Name, matchField.Name) {
matchedField = bytes.Equal(actualField.Value, matchField.Value)
break
}
}
if !matchedField {
drop = false
break
}
}
if drop {
batch.MarkUnmarkedEntryError(errDbIndexDoNotIndexSeries, idx)
return
}
}
ts := entry.Timestamp
// NB(bodu): Always check first to see if the write is within retention.
if !ts.After(earliestBlockStartToRetain) {
batch.MarkUnmarkedEntryError(m3dberrors.ErrTooPast, idx)
return
}
if !futureLimit.After(ts) {
batch.MarkUnmarkedEntryError(m3dberrors.ErrTooFuture, idx)
return
}
if ts.Before(pastLimit) && !i.coldWritesEnabled {
// NB(bodu): We only mark entries as too far in the past if
// cold writes are not enabled.
batch.MarkUnmarkedEntryError(m3dberrors.ErrTooPast, idx)
return
}
if forwardIndexEnabled {
if forwardIndexDice.roll(ts) {
forwardIndexHits++
forwardEntryTimestamp := ts.Truncate(blockSize).Add(blockSize)
if entry.OnIndexSeries.NeedsIndexUpdate(forwardEntryTimestamp) {
forwardIndexEntry := entry
forwardIndexEntry.Timestamp = forwardEntryTimestamp
t := i.BlockStartForWriteTime(forwardEntryTimestamp)
forwardIndexEntry.OnIndexSeries.OnIndexPrepare(t)
forwardIndexBatch.Append(forwardIndexEntry, d)
}
} else {
forwardIndexMiss++
}
}
notSkipped++
})
if forwardIndexEnabled && forwardIndexBatch.Len() > 0 {
i.metrics.forwardIndexCounter.Inc(int64(forwardIndexBatch.Len()))
batch.AppendAll(forwardIndexBatch)
}
// Sort the inserts by which block they're applicable for, and do the inserts
// for each block, making sure to not try to insert any entries already marked
// with a result.
batch.ForEachUnmarkedBatchByBlockStart(i.writeBatchForBlockStart)
// Track index insertions.
// Note: attemptTotal should = attemptSkip + attemptWrite.
i.metrics.asyncInsertAttemptTotal.Inc(int64(total))
i.metrics.asyncInsertAttemptSkip.Inc(int64(total - notSkipped))
i.metrics.forwardIndexHits.Inc(int64(forwardIndexHits))
i.metrics.forwardIndexMisses.Inc(int64(forwardIndexMiss))
}
func (i *nsIndex) writeBatchForBlockStart(
blockStart xtime.UnixNano, batch *index.WriteBatch,
) {
// NB(r): Capture pending entries so we can emit the latencies
pending := batch.PendingEntries()
numPending := len(pending)
// Track attempted write.
// Note: attemptTotal should = attemptSkip + attemptWrite.
i.metrics.asyncInsertAttemptWrite.Inc(int64(numPending))
// i.e. we have the block and the inserts, perform the writes.
result, err := i.activeBlock.WriteBatch(batch)
// Record the end to end indexing latency.
now := i.nowFn()
for idx := range pending {
took := now.Sub(pending[idx].EnqueuedAt)
i.metrics.insertEndToEndLatency.Record(took)
}
// NB: we don't need to do anything to the OnIndexSeries refs in `inserts` at this point,
// the index.Block WriteBatch assumes responsibility for calling the appropriate methods.
if n := result.NumSuccess; n > 0 {
i.metrics.asyncInsertSuccess.Inc(n)
}
// Record mutable segments count foreground/background if latest block.
if stats := result.MutableSegmentsStats; !stats.Empty() {
i.metrics.latestBlockNumSegmentsForeground.Update(float64(stats.Foreground.NumSegments))
i.metrics.latestBlockNumDocsForeground.Update(float64(stats.Foreground.NumDocs))
i.metrics.latestBlockNumSegmentsBackground.Update(float64(stats.Background.NumSegments))
i.metrics.latestBlockNumDocsBackground.Update(float64(stats.Background.NumDocs))
}
// Allow for duplicate write errors since due to re-indexing races
// we may try to re-index a series more than once.
if err := i.sanitizeAllowDuplicatesWriteError(err); err != nil {
numErrors := numPending - int(result.NumSuccess)
if partialError, ok := err.(*m3ninxindex.BatchPartialError); ok {
// If it was a batch partial error we know exactly how many failed
// after filtering out for duplicate ID errors.
numErrors = len(partialError.Errs())
}
i.metrics.asyncInsertErrors.Inc(int64(numErrors))
i.logger.Error("error writing to index block", zap.Error(err))
}
}
// Bootstrap bootstraps the index with the provide blocks.
func (i *nsIndex) Bootstrap(
bootstrapResults result.IndexResults,
) error {
i.state.Lock()
if i.state.bootstrapState == Bootstrapping {
i.state.Unlock()
return errDbIndexIsBootstrapping
}
i.state.bootstrapState = Bootstrapping
i.state.Unlock()
i.state.RLock()
defer func() {
i.state.RUnlock()
i.state.Lock()
i.state.bootstrapState = Bootstrapped
i.state.Unlock()
}()
var multiErr xerrors.MultiError
for blockStart, blockResults := range bootstrapResults {
blockResult, err := i.ensureBlockPresentWithRLock(blockStart)
if err != nil { // should never happen
multiErr = multiErr.Add(i.unableToAllocBlockInvariantError(err))
continue
}
if err := blockResult.block.AddResults(blockResults); err != nil {
multiErr = multiErr.Add(err)
}
}
return multiErr.FinalError()
}
func (i *nsIndex) Bootstrapped() bool {
i.state.RLock()
result := i.state.bootstrapState == Bootstrapped
i.state.RUnlock()
return result
}
func (i *nsIndex) Tick(
c context.Cancellable,
startTime xtime.UnixNano,
) (namespaceIndexTickResult, error) {
var result namespaceIndexTickResult
// First collect blocks and acquire lock to remove those that need removing
// but then release lock so can Tick and do other expensive tasks
// such as notify of sealed blocks.
tickingBlocks, multiErr := i.tickingBlocks(startTime)
result.NumBlocks = int64(tickingBlocks.totalBlocks)
for _, block := range tickingBlocks.tickingBlocks {
if c.IsCancelled() {
multiErr = multiErr.Add(errDbIndexTerminatingTickCancellation)
return result, multiErr.FinalError()
}
blockTickResult, tickErr := block.Tick(c)
multiErr = multiErr.Add(tickErr)
result.NumSegments += blockTickResult.NumSegments
result.NumSegmentsBootstrapped += blockTickResult.NumSegmentsBootstrapped
result.NumSegmentsMutable += blockTickResult.NumSegmentsMutable
result.NumTotalDocs += blockTickResult.NumDocs
result.FreeMmap += blockTickResult.FreeMmap
}
blockTickResult, tickErr := tickingBlocks.activeBlock.Tick(c)
multiErr = multiErr.Add(tickErr)
result.NumSegments += blockTickResult.NumSegments
result.NumSegmentsBootstrapped += blockTickResult.NumSegmentsBootstrapped
result.NumSegmentsMutable += blockTickResult.NumSegmentsMutable
result.NumTotalDocs += blockTickResult.NumDocs
result.FreeMmap += blockTickResult.FreeMmap
i.metrics.tick.Inc(1)
return result, multiErr.FinalError()
}
type tickingBlocksResult struct {
totalBlocks int
activeBlock index.Block
tickingBlocks []index.Block
}
func (i *nsIndex) tickingBlocks(
startTime xtime.UnixNano,
) (tickingBlocksResult, xerrors.MultiError) {
multiErr := xerrors.NewMultiError()
earliestBlockStartToRetain := retention.FlushTimeStartForRetentionPeriod(
i.retentionPeriod, i.blockSize, startTime)
i.state.Lock()
activeBlock := i.activeBlock
tickingBlocks := make([]index.Block, 0, len(i.state.blocksByTime))
defer func() {
i.updateBlockStartsWithLock()
i.state.Unlock()
}()
for blockStart, block := range i.state.blocksByTime {
// Drop any blocks past the retention period.
if blockStart.Before(earliestBlockStartToRetain) {
multiErr = multiErr.Add(block.Close())
delete(i.state.blocksByTime, blockStart)
continue
}
// Tick any blocks we're going to retain, but don't tick inline here
// we'll do this out of the block.
tickingBlocks = append(tickingBlocks, block)
// Seal any blocks that are sealable while holding lock (seal is fast).
if !blockStart.After(i.lastSealableBlockStart(startTime)) && !block.IsSealed() {
multiErr = multiErr.Add(block.Seal())
}
}
return tickingBlocksResult{