-
Notifications
You must be signed in to change notification settings - Fork 454
/
database.go
1015 lines (870 loc) · 27.7 KB
/
database.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 storage
import (
"bytes"
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/m3db/m3/src/dbnode/clock"
"github.com/m3db/m3/src/dbnode/persist/fs/commitlog"
"github.com/m3db/m3/src/dbnode/sharding"
"github.com/m3db/m3/src/dbnode/storage/block"
dberrors "github.com/m3db/m3/src/dbnode/storage/errors"
"github.com/m3db/m3/src/dbnode/storage/index"
"github.com/m3db/m3/src/dbnode/namespace"
"github.com/m3db/m3/src/dbnode/tracepoint"
"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"
xopentracing "github.com/m3db/m3/src/x/opentracing"
xtime "github.com/m3db/m3/src/x/time"
opentracinglog "github.com/opentracing/opentracing-go/log"
"github.com/uber-go/tally"
"go.uber.org/zap"
)
const (
// The database is considered overloaded if the queue size is 90% or more
// of the maximum capacity. We set this below 1.0 because checking the queue
// lengthy is racey so we're gonna burst past this value anyways and the buffer
// gives us breathing room to recover.
commitLogQueueCapacityOverloadedFactor = 0.9
)
var (
// errDatabaseAlreadyOpen raised when trying to open a database that is already open.
errDatabaseAlreadyOpen = errors.New("database is already open")
// errDatabaseNotOpen raised when trying to close a database that is not open.
errDatabaseNotOpen = errors.New("database is not open")
// errDatabaseAlreadyClosed raised when trying to open a database that is already closed.
errDatabaseAlreadyClosed = errors.New("database is already closed")
// errDatabaseIsClosed raised when trying to perform an action that requires an open database.
errDatabaseIsClosed = errors.New("database is closed")
// errWriterDoesNotImplementWriteBatch is raised when the provided ts.BatchWriter does not implement
// ts.WriteBatch.
errWriterDoesNotImplementWriteBatch = errors.New("provided writer does not implement ts.WriteBatch")
)
type databaseState int
const (
databaseNotOpen databaseState = iota
databaseOpen
databaseClosed
)
// increasingIndex provides a monotonically increasing index for new series
type increasingIndex interface {
nextIndex() uint64
}
type db struct {
sync.RWMutex
opts Options
nowFn clock.NowFn
nsWatch databaseNamespaceWatch
namespaces *databaseNamespacesMap
commitLog commitlog.CommitLog
state databaseState
mediator databaseMediator
created uint64
bootstraps int
shardSet sharding.ShardSet
lastReceivedNewShards time.Time
scope tally.Scope
metrics databaseMetrics
log *zap.Logger
writeBatchPool *ts.WriteBatchPool
}
type databaseMetrics struct {
unknownNamespaceRead tally.Counter
unknownNamespaceWrite tally.Counter
unknownNamespaceWriteTagged tally.Counter
unknownNamespaceBatchWriter tally.Counter
unknownNamespaceWriteBatch tally.Counter
unknownNamespaceWriteTaggedBatch tally.Counter
unknownNamespaceFetchBlocks tally.Counter
unknownNamespaceFetchBlocksMetadata tally.Counter
unknownNamespaceQueryIDs tally.Counter
errQueryIDsIndexDisabled tally.Counter
errWriteTaggedIndexDisabled tally.Counter
}
func newDatabaseMetrics(scope tally.Scope) databaseMetrics {
unknownNamespaceScope := scope.SubScope("unknown-namespace")
indexDisabledScope := scope.SubScope("index-disabled")
return databaseMetrics{
unknownNamespaceRead: unknownNamespaceScope.Counter("read"),
unknownNamespaceWrite: unknownNamespaceScope.Counter("write"),
unknownNamespaceWriteTagged: unknownNamespaceScope.Counter("write-tagged"),
unknownNamespaceBatchWriter: unknownNamespaceScope.Counter("batch-writer"),
unknownNamespaceWriteBatch: unknownNamespaceScope.Counter("write-batch"),
unknownNamespaceWriteTaggedBatch: unknownNamespaceScope.Counter("write-tagged-batch"),
unknownNamespaceFetchBlocks: unknownNamespaceScope.Counter("fetch-blocks"),
unknownNamespaceFetchBlocksMetadata: unknownNamespaceScope.Counter("fetch-blocks-metadata"),
unknownNamespaceQueryIDs: unknownNamespaceScope.Counter("query-ids"),
errQueryIDsIndexDisabled: indexDisabledScope.Counter("err-query-ids"),
errWriteTaggedIndexDisabled: indexDisabledScope.Counter("err-write-tagged"),
}
}
// NewDatabase creates a new time series database.
func NewDatabase(
shardSet sharding.ShardSet,
opts Options,
) (Database, error) {
if err := opts.Validate(); err != nil {
return nil, fmt.Errorf("invalid options: %v", err)
}
commitLog, err := commitlog.NewCommitLog(opts.CommitLogOptions())
if err != nil {
return nil, err
}
if err := commitLog.Open(); err != nil {
return nil, err
}
var (
iopts = opts.InstrumentOptions()
scope = iopts.MetricsScope().SubScope("database")
logger = iopts.Logger()
nowFn = opts.ClockOptions().NowFn()
)
d := &db{
opts: opts,
nowFn: nowFn,
shardSet: shardSet,
lastReceivedNewShards: nowFn(),
namespaces: newDatabaseNamespacesMap(databaseNamespacesMapOptions{}),
commitLog: commitLog,
scope: scope,
metrics: newDatabaseMetrics(scope),
log: logger,
writeBatchPool: opts.WriteBatchPool(),
}
databaseIOpts := iopts.SetMetricsScope(scope)
// initialize namespaces
nsInit := opts.NamespaceInitializer()
logger.Info("creating namespaces watch")
nsReg, err := nsInit.Init()
if err != nil {
return nil, err
}
// get a namespace watch
watch, err := nsReg.Watch()
if err != nil {
return nil, err
}
// Wait till first namespaces value is received and set the value.
// Its important that this happens before the mediator is started to prevent
// a race condition where the namespaces haven't been initialized yet and
// GetOwnedNamespaces() returns an empty slice which makes the cleanup logic
// in the background Tick think it can clean up files that it shouldn't.
logger.Info("resolving namespaces with namespace watch")
<-watch.C()
d.nsWatch = newDatabaseNamespaceWatch(d, watch, databaseIOpts)
nsMap := watch.Get()
if err := d.UpdateOwnedNamespaces(nsMap); err != nil {
// Log the error and proceed in case some namespace is miss-configured, e.g. missing schema.
// Miss-configured namespace won't be initialized, should not prevent database
// or other namespaces from getting initialized.
d.log.Error("failed to update owned namespaces",
zap.Error(err))
}
mediator, err := newMediator(
d, commitLog, opts.SetInstrumentOptions(databaseIOpts))
if err != nil {
return nil, err
}
d.mediator = mediator
return d, nil
}
func (d *db) updateSchemaRegistry(newNamespaces namespace.Map) error {
schemaReg := d.opts.SchemaRegistry()
schemaUpdates := newNamespaces.Metadatas()
merr := xerrors.NewMultiError()
for _, metadata := range schemaUpdates {
curSchemaId := "none"
curSchema, err := schemaReg.GetLatestSchema(metadata.ID())
if curSchema != nil {
curSchemaId = curSchema.DeployId()
}
// Log schema update.
latestSchema, found := metadata.Options().SchemaHistory().GetLatest()
if !found {
merr.Add(fmt.Errorf("can not updating namespace(%v) schema to empty", metadata.ID().String()))
continue
} else {
d.log.Info("updating database namespace schema", zap.Stringer("namespace", metadata.ID()),
zap.String("current schema", curSchemaId), zap.String("latest schema", latestSchema.DeployId()))
}
err = schemaReg.SetSchemaHistory(metadata.ID(), metadata.Options().SchemaHistory())
if err != nil {
d.log.Warn("failed to update latest schema for namespace",
zap.Stringer("namespace", metadata.ID()),
zap.Error(err))
merr.Add(fmt.Errorf("failed to update latest schema for namespace %v, error: %v",
metadata.ID().String(), err))
}
}
if merr.Empty() {
return nil
}
return merr
}
func (d *db) UpdateOwnedNamespaces(newNamespaces namespace.Map) error {
if newNamespaces == nil {
return nil
}
// Always update schema registry before owned namespaces.
if err := d.updateSchemaRegistry(newNamespaces); err != nil {
// Log schema update error and proceed.
// In a multi-namespace database, schema update failure for one namespace be isolated.
d.log.Error("failed to update schema registry", zap.Error(err))
}
d.Lock()
defer d.Unlock()
removes, adds, updates := d.namespaceDeltaWithLock(newNamespaces)
if err := d.logNamespaceUpdate(removes, adds, updates); err != nil {
enrichedErr := fmt.Errorf("unable to log namespace updates: %v", err)
d.log.Error(enrichedErr.Error())
return enrichedErr
}
// add any namespaces marked for addition
if err := d.addNamespacesWithLock(adds); err != nil {
enrichedErr := fmt.Errorf("unable to add namespaces: %v", err)
d.log.Error(enrichedErr.Error())
return err
}
// log that updates and removals are skipped
if len(removes) > 0 || len(updates) > 0 {
d.log.Warn("skipping namespace removals and updates (except schema updates), restart process if you want changes to take effect.")
}
// enqueue bootstraps if new namespaces
if len(adds) > 0 {
d.queueBootstrapWithLock()
}
return nil
}
func (d *db) namespaceDeltaWithLock(newNamespaces namespace.Map) ([]ident.ID, []namespace.Metadata, []namespace.Metadata) {
var (
existing = d.namespaces
removes []ident.ID
adds []namespace.Metadata
updates []namespace.Metadata
)
// check if existing namespaces exist in newNamespaces
for _, entry := range existing.Iter() {
ns := entry.Value()
newMd, err := newNamespaces.Get(ns.ID())
// if a namespace doesn't exist in newNamespaces, mark for removal
if err != nil {
removes = append(removes, ns.ID())
continue
}
// if namespace exists in newNamespaces, check if options are the same
optionsSame := newMd.Options().Equal(ns.Options())
// if options are the same, we don't need to do anything
if optionsSame {
continue
}
// if options are not the same, we mark for updates
updates = append(updates, newMd)
}
// check for any namespaces that need to be added
for _, ns := range newNamespaces.Metadatas() {
_, exists := d.namespaces.Get(ns.ID())
if !exists {
adds = append(adds, ns)
}
}
return removes, adds, updates
}
func (d *db) logNamespaceUpdate(removes []ident.ID, adds, updates []namespace.Metadata) error {
removalString, err := tsIDs(removes).String()
if err != nil {
return fmt.Errorf("unable to format removal, err = %v", err)
}
addString, err := metadatas(adds).String()
if err != nil {
return fmt.Errorf("unable to format adds, err = %v", err)
}
updateString, err := metadatas(updates).String()
if err != nil {
return fmt.Errorf("unable to format updates, err = %v", err)
}
// log scheduled operation
d.log.Info("updating database namespaces",
zap.String("adds", addString),
zap.String("updates", updateString),
zap.String("removals", removalString),
)
// NB(prateek): as noted in `UpdateOwnedNamespaces()` above, the current implementation
// does not apply updates, and removals until the m3dbnode process is restarted.
return nil
}
func (d *db) addNamespacesWithLock(namespaces []namespace.Metadata) error {
for _, n := range namespaces {
// ensure namespace doesn't exist
_, ok := d.namespaces.Get(n.ID())
if ok { // should never happen
return fmt.Errorf("existing namespace marked for addition: %v", n.ID().String())
}
// create and add to the database
newNs, err := d.newDatabaseNamespaceWithLock(n)
if err != nil {
return err
}
d.namespaces.Set(n.ID(), newNs)
}
return nil
}
func (d *db) newDatabaseNamespaceWithLock(
md namespace.Metadata,
) (databaseNamespace, error) {
var (
retriever block.DatabaseBlockRetriever
err error
)
if mgr := d.opts.DatabaseBlockRetrieverManager(); mgr != nil {
retriever, err = mgr.Retriever(md)
if err != nil {
return nil, err
}
}
return newDatabaseNamespace(md, d.shardSet, retriever, d, d.commitLog, d.opts)
}
func (d *db) Options() Options {
// Options are immutable safe to pass the current reference
return d.opts
}
func (d *db) AssignShardSet(shardSet sharding.ShardSet) {
d.Lock()
defer d.Unlock()
receivedNewShards := d.hasReceivedNewShardsWithLock(shardSet)
d.shardSet = shardSet
if receivedNewShards {
d.lastReceivedNewShards = d.nowFn()
}
for _, elem := range d.namespaces.Iter() {
ns := elem.Value()
ns.AssignShardSet(shardSet)
}
d.queueBootstrapWithLock()
}
func (d *db) hasReceivedNewShardsWithLock(incoming sharding.ShardSet) bool {
var (
existing = d.shardSet
existingSet = make(map[uint32]struct{}, len(existing.AllIDs()))
)
for _, shard := range existing.AllIDs() {
existingSet[shard] = struct{}{}
}
receivedNewShards := false
for _, shard := range incoming.AllIDs() {
_, ok := existingSet[shard]
if !ok {
receivedNewShards = true
break
}
}
return receivedNewShards
}
func (d *db) ShardSet() sharding.ShardSet {
d.RLock()
defer d.RUnlock()
shardSet := d.shardSet
return shardSet
}
func (d *db) queueBootstrapWithLock() {
// Only perform a bootstrap if at least one bootstrap has already occurred. This enables
// the ability to open the clustered database and assign shardsets to the non-clustered
// database when it receives an initial topology (as well as topology changes) without
// triggering a bootstrap until an external call initiates a bootstrap with an initial
// call to Bootstrap(). After that initial bootstrap, the clustered database will keep
// the non-clustered database bootstrapped by assigning it shardsets which will trigger new
// bootstraps since d.bootstraps > 0 will be true.
if d.bootstraps > 0 {
// NB(r): Trigger another bootstrap, if already bootstrapping this will
// enqueue a new bootstrap to execute before the current bootstrap
// completes.
go func() {
if err := d.mediator.Bootstrap(); err != nil {
d.log.Error("error while bootstrapping", zap.Error(err))
}
}()
}
}
func (d *db) Namespace(id ident.ID) (Namespace, bool) {
d.RLock()
defer d.RUnlock()
return d.namespaces.Get(id)
}
func (d *db) Namespaces() []Namespace {
d.RLock()
defer d.RUnlock()
namespaces := make([]Namespace, 0, d.namespaces.Len())
for _, elem := range d.namespaces.Iter() {
namespaces = append(namespaces, elem.Value())
}
return namespaces
}
func (d *db) Open() error {
d.Lock()
defer d.Unlock()
// check if db has already been opened
if d.state != databaseNotOpen {
return errDatabaseAlreadyOpen
}
d.state = databaseOpen
// start namespace watch
if err := d.nsWatch.Start(); err != nil {
return err
}
// Start the wired list
if wiredList := d.opts.DatabaseBlockOptions().WiredList(); wiredList != nil {
err := wiredList.Start()
if err != nil {
return err
}
}
return d.mediator.Open()
}
func (d *db) terminateWithLock() error {
// ensure database is open
if d.state == databaseNotOpen {
return errDatabaseNotOpen
}
if d.state == databaseClosed {
return errDatabaseAlreadyClosed
}
d.state = databaseClosed
// close the mediator
if err := d.mediator.Close(); err != nil {
return err
}
// stop listening for namespace changes
if err := d.nsWatch.Close(); err != nil {
return err
}
// Stop the wired list
if wiredList := d.opts.DatabaseBlockOptions().WiredList(); wiredList != nil {
err := wiredList.Stop()
if err != nil {
return err
}
}
// NB(prateek): Terminate is meant to return quickly, so we rely upon
// the gc to clean up any resources held by namespaces, and just set
// our reference to the namespaces to nil.
d.namespaces.Reallocate()
// Finally close the commit log
return d.commitLog.Close()
}
func (d *db) Terminate() error {
d.Lock()
defer d.Unlock()
return d.terminateWithLock()
}
func (d *db) Close() error {
d.Lock()
defer d.Unlock()
// get a reference to all owned namespaces
namespaces := d.ownedNamespacesWithLock()
// release any database level resources
if err := d.terminateWithLock(); err != nil {
return err
}
var multiErr xerrors.MultiError
for _, ns := range namespaces {
multiErr = multiErr.Add(ns.Close())
}
return multiErr.FinalError()
}
func (d *db) Write(
ctx context.Context,
namespace ident.ID,
id ident.ID,
timestamp time.Time,
value float64,
unit xtime.Unit,
annotation []byte,
) error {
n, err := d.namespaceFor(namespace)
if err != nil {
d.metrics.unknownNamespaceWrite.Inc(1)
return err
}
series, wasWritten, err := n.Write(ctx, id, timestamp, value, unit, annotation)
if err != nil {
return err
}
if !n.Options().WritesToCommitLog() || !wasWritten {
return nil
}
dp := ts.Datapoint{Timestamp: timestamp, Value: value}
return d.commitLog.Write(ctx, series, dp, unit, annotation)
}
func (d *db) WriteTagged(
ctx context.Context,
namespace ident.ID,
id ident.ID,
tags ident.TagIterator,
timestamp time.Time,
value float64,
unit xtime.Unit,
annotation []byte,
) error {
n, err := d.namespaceFor(namespace)
if err != nil {
d.metrics.unknownNamespaceWriteTagged.Inc(1)
return err
}
series, wasWritten, err := n.WriteTagged(ctx, id, tags, timestamp, value, unit, annotation)
if err != nil {
return err
}
if !n.Options().WritesToCommitLog() || !wasWritten {
return nil
}
dp := ts.Datapoint{Timestamp: timestamp, Value: value}
return d.commitLog.Write(ctx, series, dp, unit, annotation)
}
func (d *db) BatchWriter(namespace ident.ID, batchSize int) (ts.BatchWriter, error) {
n, err := d.namespaceFor(namespace)
if err != nil {
d.metrics.unknownNamespaceBatchWriter.Inc(1)
return nil, err
}
var (
nsID = n.ID()
batchWriter = d.writeBatchPool.Get()
)
batchWriter.Reset(batchSize, nsID)
return batchWriter, nil
}
func (d *db) WriteBatch(
ctx context.Context,
namespace ident.ID,
writer ts.BatchWriter,
errHandler IndexedErrorHandler,
) error {
return d.writeBatch(ctx, namespace, writer, errHandler, false)
}
func (d *db) WriteTaggedBatch(
ctx context.Context,
namespace ident.ID,
writer ts.BatchWriter,
errHandler IndexedErrorHandler,
) error {
return d.writeBatch(ctx, namespace, writer, errHandler, true)
}
func (d *db) writeBatch(
ctx context.Context,
namespace ident.ID,
writer ts.BatchWriter,
errHandler IndexedErrorHandler,
tagged bool,
) error {
writes, ok := writer.(ts.WriteBatch)
if !ok {
return errWriterDoesNotImplementWriteBatch
}
n, err := d.namespaceFor(namespace)
if err != nil {
if tagged {
d.metrics.unknownNamespaceWriteTaggedBatch.Inc(1)
} else {
d.metrics.unknownNamespaceWriteBatch.Inc(1)
}
return err
}
iter := writes.Iter()
for i, write := range iter {
var (
series ts.Series
wasWritten bool
err error
)
if tagged {
series, wasWritten, err = n.WriteTagged(
ctx,
write.Write.Series.ID,
write.TagIter,
write.Write.Datapoint.Timestamp,
write.Write.Datapoint.Value,
write.Write.Unit,
write.Write.Annotation,
)
} else {
series, wasWritten, err = n.Write(
ctx,
write.Write.Series.ID,
write.Write.Datapoint.Timestamp,
write.Write.Datapoint.Value,
write.Write.Unit,
write.Write.Annotation,
)
}
if err != nil {
// Return errors with the original index provided by the caller so they
// can associate the error with the write that caused it.
errHandler.HandleError(write.OriginalIndex, err)
}
// Need to set the outcome in the success case so the commitlog gets the
// updated series object which contains identifiers (like the series ID)
// whose lifecycle lives longer than the span of this request, making them
// safe for use by the async commitlog. Need to set the outcome in the
// error case so that the commitlog knows to skip this entry.
writes.SetOutcome(i, series, err)
if !wasWritten || err != nil {
// This series has no additional information that needs to be written to
// the commit log; set this series to skip writing to the commit log.
writes.SetSkipWrite(i)
}
}
if !n.Options().WritesToCommitLog() {
// Finalize here because we can't rely on the commitlog to do it since
// we're not using it.
writes.Finalize()
return nil
}
return d.commitLog.WriteBatch(ctx, writes)
}
func (d *db) QueryIDs(
ctx context.Context,
namespace ident.ID,
query index.Query,
opts index.QueryOptions,
) (index.QueryResult, error) {
ctx, sp := ctx.StartTraceSpan(tracepoint.DBQueryIDs)
sp.LogFields(
opentracinglog.String("query", query.String()),
opentracinglog.String("namespace", namespace.String()),
opentracinglog.Int("limit", opts.Limit),
xopentracing.Time("start", opts.StartInclusive),
xopentracing.Time("end", opts.EndExclusive),
)
defer sp.Finish()
n, err := d.namespaceFor(namespace)
if err != nil {
sp.LogFields(opentracinglog.Error(err))
d.metrics.unknownNamespaceQueryIDs.Inc(1)
return index.QueryResult{}, err
}
return n.QueryIDs(ctx, query, opts)
}
func (d *db) AggregateQuery(
ctx context.Context,
namespace ident.ID,
query index.Query,
aggResultOpts index.AggregationOptions,
) (index.AggregateQueryResult, error) {
n, err := d.namespaceFor(namespace)
if err != nil {
d.metrics.unknownNamespaceQueryIDs.Inc(1)
return index.AggregateQueryResult{}, err
}
return n.AggregateQuery(ctx, query, aggResultOpts)
}
func (d *db) ReadEncoded(
ctx context.Context,
namespace ident.ID,
id ident.ID,
start, end time.Time,
) ([][]xio.BlockReader, error) {
n, err := d.namespaceFor(namespace)
if err != nil {
d.metrics.unknownNamespaceRead.Inc(1)
return nil, err
}
return n.ReadEncoded(ctx, id, start, end)
}
func (d *db) FetchBlocks(
ctx context.Context,
namespace ident.ID,
shardID uint32,
id ident.ID,
starts []time.Time,
) ([]block.FetchBlockResult, error) {
n, err := d.namespaceFor(namespace)
if err != nil {
d.metrics.unknownNamespaceFetchBlocks.Inc(1)
return nil, xerrors.NewInvalidParamsError(err)
}
return n.FetchBlocks(ctx, shardID, id, starts)
}
func (d *db) FetchBlocksMetadataV2(
ctx context.Context,
namespace ident.ID,
shardID uint32,
start, end time.Time,
limit int64,
pageToken PageToken,
opts block.FetchBlocksMetadataOptions,
) (block.FetchBlocksMetadataResults, PageToken, error) {
n, err := d.namespaceFor(namespace)
if err != nil {
d.metrics.unknownNamespaceFetchBlocksMetadata.Inc(1)
return nil, nil, xerrors.NewInvalidParamsError(err)
}
return n.FetchBlocksMetadataV2(ctx, shardID, start, end, limit,
pageToken, opts)
}
func (d *db) Bootstrap() error {
d.Lock()
d.bootstraps++
d.Unlock()
return d.mediator.Bootstrap()
}
func (d *db) IsBootstrapped() bool {
return d.mediator.IsBootstrapped()
}
// IsBootstrappedAndDurable should only return true if the following conditions are met:
// 1. The database is bootstrapped.
// 2. The last successful snapshot began AFTER the last bootstrap completed.
//
// Those two conditions should be sufficient to ensure that after a placement change the
// node will be able to bootstrap any and all data from its local disk, however, for posterity
// we also perform the following check:
// 3. The last bootstrap completed AFTER the shardset was last assigned.
func (d *db) IsBootstrappedAndDurable() bool {
isBootstrapped := d.mediator.IsBootstrapped()
if !isBootstrapped {
d.log.Debug("not bootstrapped and durable because: not bootstrapped")
return false
}
lastBootstrapCompletionTime, ok := d.mediator.LastBootstrapCompletionTime()
if !ok {
d.log.Debug("not bootstrapped and durable because: no last bootstrap completion time",
zap.Time("lastBootstrapCompletionTime", lastBootstrapCompletionTime))
return false
}
lastSnapshotStartTime, ok := d.mediator.LastSuccessfulSnapshotStartTime()
if !ok {
d.log.Debug("not bootstrapped and durable because: no last snapshot start time",
zap.Time("lastBootstrapCompletionTime", lastBootstrapCompletionTime),
zap.Time("lastSnapshotStartTime", lastSnapshotStartTime),
)
return false
}
var (
hasSnapshottedPostBootstrap = lastSnapshotStartTime.After(lastBootstrapCompletionTime)
hasBootstrappedSinceReceivingNewShards = lastBootstrapCompletionTime.After(d.lastReceivedNewShards) ||
lastBootstrapCompletionTime.Equal(d.lastReceivedNewShards)
isBootstrappedAndDurable = hasSnapshottedPostBootstrap &&
hasBootstrappedSinceReceivingNewShards
)
if !isBootstrappedAndDurable {
d.log.Debug(
"not bootstrapped and durable because: has not snapshotted post bootstrap and/or has not bootstrapped since receiving new shards",
zap.Time("lastBootstrapCompletionTime", lastBootstrapCompletionTime),
zap.Time("lastSnapshotStartTime", lastSnapshotStartTime),
zap.Time("lastReceivedNewShards", d.lastReceivedNewShards),
)
return false
}
return true
}
func (d *db) Repair() error {
return d.mediator.Repair()
}
func (d *db) Truncate(namespace ident.ID) (int64, error) {
n, err := d.namespaceFor(namespace)
if err != nil {
return 0, err
}
return n.Truncate()
}
func (d *db) IsOverloaded() bool {
queueSize := float64(d.commitLog.QueueLength())
queueCapacity := float64(d.opts.CommitLogOptions().BacklogQueueSize())
return queueSize >= commitLogQueueCapacityOverloadedFactor*queueCapacity
}
func (d *db) BootstrapState() DatabaseBootstrapState {
nsBootstrapStates := NamespaceBootstrapStates{}
d.RLock()
for _, n := range d.namespaces.Iter() {
ns := n.Value()
nsBootstrapStates[ns.ID().String()] = ns.BootstrapState()
}
d.RUnlock()
return DatabaseBootstrapState{
NamespaceBootstrapStates: nsBootstrapStates,
}
}
func (d *db) namespaceFor(namespace ident.ID) (databaseNamespace, error) {
d.RLock()
n, exists := d.namespaces.Get(namespace)
d.RUnlock()
if !exists {
return nil, dberrors.NewUnknownNamespaceError(namespace.String())
}
return n, nil
}
func (d *db) ownedNamespacesWithLock() []databaseNamespace {
namespaces := make([]databaseNamespace, 0, d.namespaces.Len())
for _, n := range d.namespaces.Iter() {
namespaces = append(namespaces, n.Value())
}
return namespaces
}
func (d *db) GetOwnedNamespaces() ([]databaseNamespace, error) {
d.RLock()
defer d.RUnlock()
if d.state == databaseClosed {
return nil, errDatabaseIsClosed
}
return d.ownedNamespacesWithLock(), nil
}
func (d *db) nextIndex() uint64 {
created := atomic.AddUint64(&d.created, 1)
return created - 1
}
type tsIDs []ident.ID
func (t tsIDs) String() (string, error) {
var buf bytes.Buffer
buf.WriteRune('[')
for idx, id := range t {
if idx != 0 {
if _, err := buf.WriteString(", "); err != nil {
return "", err
}
}
if _, err := buf.WriteString(id.String()); err != nil {
return "", err
}
}
buf.WriteRune(']')
return buf.String(), nil
}
type metadatas []namespace.Metadata
func (m metadatas) String() (string, error) {