-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
shard.go
2748 lines (2396 loc) · 72.9 KB
/
shard.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package tsdb
import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"unicode"
"unsafe"
"github.com/influxdata/influxdb/v2/influxql/query"
"github.com/influxdata/influxdb/v2/logger"
"github.com/influxdata/influxdb/v2/models"
"github.com/influxdata/influxdb/v2/pkg/bytesutil"
errors2 "github.com/influxdata/influxdb/v2/pkg/errors"
"github.com/influxdata/influxdb/v2/pkg/estimator"
"github.com/influxdata/influxdb/v2/pkg/file"
"github.com/influxdata/influxdb/v2/pkg/limiter"
"github.com/influxdata/influxdb/v2/pkg/slices"
internal "github.com/influxdata/influxdb/v2/tsdb/internal"
"github.com/influxdata/influxql"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/zap"
"google.golang.org/protobuf/proto"
)
const (
measurementKey = "_name"
DefaultMetricInterval = 10 * time.Second
FieldsChangeFile = "fields.idxl"
bytesInInt64 = 8
)
var (
// ErrFieldTypeConflict is returned when a new field already exists with a different type.
ErrFieldTypeConflict = errors.New("field type conflict")
// ErrEngineClosed is returned when a caller attempts indirectly to
// access the shard's underlying engine.
ErrEngineClosed = errors.New("engine is closed")
// ErrShardDisabled is returned when a the shard is not available for
// queries or writes.
ErrShardDisabled = errors.New("shard is disabled")
// ErrUnknownFieldsFormat is returned when the fields index file is not identifiable by
// the file's magic number.
ErrUnknownFieldsFormat = errors.New("unknown field index format")
// ErrUnknownFieldType is returned when the type of a field cannot be determined.
ErrUnknownFieldType = errors.New("unknown field type")
// ErrShardNotIdle is returned when an operation requiring the shard to be idle/cold is
// attempted on a hot shard.
ErrShardNotIdle = errors.New("shard not idle")
// fieldsIndexMagicNumber is the file magic number for the fields index file.
fieldsIndexMagicNumber = []byte{0, 6, 1, 3}
)
var (
// Static objects to prevent small allocs.
timeBytes = []byte("time")
)
// A ShardError implements the error interface, and contains extra
// context about the shard that generated the error.
type ShardError struct {
id uint64
Err error
}
// NewShardError returns a new ShardError.
func NewShardError(id uint64, err error) error {
if err == nil {
return nil
}
return ShardError{id: id, Err: err}
}
// Error returns the string representation of the error, to satisfy the error interface.
func (e ShardError) Error() string {
return fmt.Sprintf("[shard %d] %s", e.id, e.Err)
}
// PartialWriteError indicates a write request could only write a portion of the
// requested values.
type PartialWriteError struct {
Reason string
Dropped int
// A sorted slice of series keys that were dropped.
DroppedKeys [][]byte
}
func (e PartialWriteError) Error() string {
return fmt.Sprintf("partial write: %s dropped=%d", e.Reason, e.Dropped)
}
// Shard represents a self-contained time series database. An inverted index of
// the measurement and tag data is kept along with the raw time series data.
// Data can be split across many shards. The query engine in TSDB is responsible
// for combining the output of many shards into a single query result.
type Shard struct {
path string
walPath string
id uint64
database string
retentionPolicy string
sfile *SeriesFile
options EngineOptions
mu sync.RWMutex
_engine Engine
index Index
enabled bool
stats *ShardMetrics
baseLogger *zap.Logger
logger *zap.Logger
metricUpdater *ticker
EnableOnOpen bool
// CompactionDisabled specifies the shard should not schedule compactions.
// This option is intended for offline tooling.
CompactionDisabled bool
}
// NewShard returns a new initialized Shard. walPath doesn't apply to the b1 type index
func NewShard(id uint64, path string, walPath string, sfile *SeriesFile, opt EngineOptions) *Shard {
db, rp := decodeStorePath(path)
logger := zap.NewNop()
engineTags := EngineTags{
Path: path,
WalPath: walPath,
Id: fmt.Sprintf("%d", id),
Bucket: db,
EngineVersion: opt.EngineVersion,
}
s := &Shard{
id: id,
path: path,
walPath: walPath,
sfile: sfile,
options: opt,
stats: newShardMetrics(engineTags),
database: db,
retentionPolicy: rp,
logger: logger,
baseLogger: logger,
EnableOnOpen: true,
}
return s
}
// WithLogger sets the logger on the shard. It must be called before Open.
func (s *Shard) WithLogger(log *zap.Logger) {
s.baseLogger = log
engine, err := s.Engine()
if err == nil {
engine.WithLogger(s.baseLogger)
s.index.WithLogger(s.baseLogger)
}
s.logger = s.baseLogger.With(zap.String("service", "shard"))
}
// SetEnabled enables the shard for queries and write. When disabled, all
// writes and queries return an error and compactions are stopped for the shard.
func (s *Shard) SetEnabled(enabled bool) {
s.mu.Lock()
s.setEnabledNoLock(enabled)
s.mu.Unlock()
}
// ! setEnabledNoLock performs actual work of SetEnabled. Must hold s.mu before calling.
func (s *Shard) setEnabledNoLock(enabled bool) {
// Prevent writes and queries
s.enabled = enabled
if s._engine != nil && !s.CompactionDisabled {
// Disable background compactions and snapshotting
s._engine.SetEnabled(enabled)
}
}
// ScheduleFullCompaction forces a full compaction to be schedule on the shard.
func (s *Shard) ScheduleFullCompaction() error {
engine, err := s.Engine()
if err != nil {
return err
}
return engine.ScheduleFullCompaction()
}
// ID returns the shards ID.
func (s *Shard) ID() uint64 {
return s.id
}
// Database returns the database of the shard.
func (s *Shard) Database() string {
return s.database
}
// RetentionPolicy returns the retention policy of the shard.
func (s *Shard) RetentionPolicy() string {
return s.retentionPolicy
}
var globalShardMetrics = newAllShardMetrics()
type twoCounterObserver struct {
count prometheus.Counter
sum prometheus.Counter
}
func (t twoCounterObserver) Observe(f float64) {
t.sum.Inc()
t.count.Add(f)
}
var _ prometheus.Observer = twoCounterObserver{}
type allShardMetrics struct {
writes *prometheus.CounterVec
writesSum *prometheus.CounterVec
writesErr *prometheus.CounterVec
writesErrSum *prometheus.CounterVec
writesDropped *prometheus.CounterVec
fieldsCreated *prometheus.CounterVec
diskSize *prometheus.GaugeVec
series *prometheus.GaugeVec
}
type ShardMetrics struct {
writes prometheus.Observer
writesErr prometheus.Observer
writesDropped prometheus.Counter
fieldsCreated prometheus.Counter
diskSize prometheus.Gauge
series prometheus.Gauge
}
const storageNamespace = "storage"
const shardSubsystem = "shard"
func newAllShardMetrics() *allShardMetrics {
labels := EngineLabelNames()
return &allShardMetrics{
writes: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: storageNamespace,
Subsystem: shardSubsystem,
Name: "write_count",
Help: "Count of the number of write requests",
}, labels),
writesSum: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: storageNamespace,
Subsystem: shardSubsystem,
Name: "write_sum",
Help: "Counter of the number of points for write requests",
}, labels),
writesErr: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: storageNamespace,
Subsystem: shardSubsystem,
Name: "write_err_count",
Help: "Count of the number of write requests with errors",
}, labels),
writesErrSum: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: storageNamespace,
Subsystem: shardSubsystem,
Name: "write_err_sum",
Help: "Counter of the number of points for write requests with errors",
}, labels),
writesDropped: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: storageNamespace,
Subsystem: shardSubsystem,
Name: "write_dropped_sum",
Help: "Counter of the number of points droppped",
}, labels),
fieldsCreated: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: storageNamespace,
Subsystem: shardSubsystem,
Name: "fields_created",
Help: "Counter of the number of fields created",
}, labels),
diskSize: prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: storageNamespace,
Subsystem: shardSubsystem,
Name: "disk_size",
Help: "Gauge of the disk size for the shard",
}, labels),
series: prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: storageNamespace,
Subsystem: shardSubsystem,
Name: "series",
Help: "Gauge of the number of series in the shard index",
}, labels),
}
}
func ShardCollectors() []prometheus.Collector {
return []prometheus.Collector{
globalShardMetrics.writes,
globalShardMetrics.writesSum,
globalShardMetrics.writesErr,
globalShardMetrics.writesErrSum,
globalShardMetrics.writesDropped,
globalShardMetrics.fieldsCreated,
globalShardMetrics.diskSize,
globalShardMetrics.series,
}
}
func newShardMetrics(tags EngineTags) *ShardMetrics {
labels := tags.GetLabels()
return &ShardMetrics{
writes: twoCounterObserver{
count: globalShardMetrics.writes.With(labels),
sum: globalShardMetrics.writesSum.With(labels),
},
writesErr: twoCounterObserver{
count: globalShardMetrics.writesErr.With(labels),
sum: globalShardMetrics.writesErrSum.With(labels),
},
writesDropped: globalShardMetrics.writesDropped.With(labels),
fieldsCreated: globalShardMetrics.fieldsCreated.With(labels),
diskSize: globalShardMetrics.diskSize.With(labels),
series: globalShardMetrics.series.With(labels),
}
}
// ticker runs fn periodically, and stops when Stop() is called
//
// Stop waits for the last function run to finish if already running
type ticker struct {
wg sync.WaitGroup
closing chan struct{}
}
// Stops the ticker and waits for the function to complete
func (t *ticker) Stop() {
close(t.closing)
t.wg.Wait()
}
// Path returns the path set on the shard when it was created.
func (s *Shard) Path() string { return s.path }
// Open initializes and opens the shard's store.
func (s *Shard) Open(ctx context.Context) error {
s.mu.Lock()
closeWaitNeeded, err := s.openNoLock(ctx)
s.mu.Unlock()
if closeWaitNeeded {
werr := s.closeWait()
// We want the first error we get returned to the caller
if err == nil {
err = werr
}
}
return err
}
// openNoLock performs work of Open. Must hold s.mu before calling. The first return
// value is true if the caller should call closeWait after unlocking s.mu in order
// to clean up a failed open operation.
func (s *Shard) openNoLock(ctx context.Context) (bool, error) {
if err := func() error {
// Return if the shard is already open
if s._engine != nil {
return nil
}
seriesIDSet := NewSeriesIDSet()
// Initialize underlying index.
ipath := filepath.Join(s.path, "index")
idx, err := NewIndex(s.id, s.database, ipath, seriesIDSet, s.sfile, s.options)
if err != nil {
return err
}
idx.WithLogger(s.baseLogger)
// Check if the index needs to be rebuilt before Open() initializes
// its file system layout.
var shouldReindex bool
if _, err := os.Stat(ipath); os.IsNotExist(err) {
shouldReindex = true
}
// Open index.
if err := idx.Open(); err != nil {
return err
}
s.index = idx
// Initialize underlying engine.
e, err := NewEngine(s.id, idx, s.path, s.walPath, s.sfile, s.options)
if err != nil {
return err
}
// Set log output on the engine.
e.WithLogger(s.baseLogger)
// Disable compactions while loading the index
e.SetEnabled(false)
// Open engine.
if err := e.Open(ctx); err != nil {
return err
}
if shouldReindex {
if err := e.Reindex(); err != nil {
return err
}
}
if err := e.LoadMetadataIndex(s.id, s.index); err != nil {
return err
}
s._engine = e
// Set up metric collection
metricUpdater := &ticker{
closing: make(chan struct{}),
}
// We want a way to turn off the series and disk size metrics if they are suspected to cause issues
// This corresponds to the top-level MetricsDisabled argument
if !s.options.MetricsDisabled {
metricUpdater.wg.Add(1)
go func() {
tick := time.NewTicker(DefaultMetricInterval)
defer metricUpdater.wg.Done()
defer tick.Stop()
for {
select {
case <-tick.C:
// Note this takes the engine lock, so we have to be careful not
// to close metricUpdater.closing while holding the engine lock
e, err := s.Engine()
if err != nil {
continue
}
s.stats.series.Set(float64(e.SeriesN()))
s.stats.diskSize.Set(float64(e.DiskSize()))
case <-metricUpdater.closing:
return
}
}
}()
}
s.metricUpdater = metricUpdater
return nil
}(); err != nil {
s.closeNoLock()
return true, NewShardError(s.id, err)
}
if s.EnableOnOpen {
// enable writes, queries and compactions
s.setEnabledNoLock(true)
}
return false, nil
}
// Close shuts down the shard's store.
func (s *Shard) Close() error {
err := func() error {
s.mu.Lock()
defer s.mu.Unlock()
return s.closeNoLock()
}()
// make sure not to hold a lock while waiting for close to finish
werr := s.closeWait()
if err != nil {
return err
}
return werr
}
// closeNoLock closes the shard an removes reference to the shard from associated
// indexes. The s.mu mutex must be held before calling closeNoLock. closeWait should always
// be called after calling closeNoLock.
func (s *Shard) closeNoLock() error {
if s._engine == nil {
return nil
}
if s.metricUpdater != nil {
close(s.metricUpdater.closing)
}
err := s._engine.Close()
if err == nil {
s._engine = nil
}
if e := s.index.Close(); e == nil {
s.index = nil
}
return err
}
// closeWait waits for goroutines and other background operations associated with this
// shard to complete after closeNoLock is called. Must only be called after calling
// closeNoLock. closeWait should always be called after calling closeNoLock.
// Public methods which close the shard should call closeWait after closeNoLock before
// returning. Must be called without holding shard locks to avoid deadlocking.
func (s *Shard) closeWait() error {
if s.metricUpdater != nil {
s.metricUpdater.wg.Wait()
}
return nil
}
// IndexType returns the index version being used for this shard.
//
// IndexType returns the empty string if it is called before the shard is opened,
// since it is only that point that the underlying index type is known.
func (s *Shard) IndexType() string {
s.mu.RLock()
defer s.mu.RUnlock()
if s._engine == nil || s.index == nil { // Shard not open yet.
return ""
}
return s.index.Type()
}
// ready determines if the Shard is ready for queries or writes.
// It returns nil if ready, otherwise ErrShardClosed or ErrShardDisabled
func (s *Shard) ready() error {
var err error
if s._engine == nil {
err = ErrEngineClosed
} else if !s.enabled {
err = ErrShardDisabled
}
return err
}
// LastModified returns the time when this shard was last modified.
func (s *Shard) LastModified() time.Time {
engine, err := s.Engine()
if err != nil {
return time.Time{}
}
return engine.LastModified()
}
// Index returns a reference to the underlying index. It returns an error if
// the index is nil.
func (s *Shard) Index() (Index, error) {
s.mu.RLock()
defer s.mu.RUnlock()
if err := s.ready(); err != nil {
return nil, err
}
return s.index, nil
}
// SeriesFile returns a reference the underlying series file. If return an error
// if the series file is nil.
func (s *Shard) SeriesFile() (*SeriesFile, error) {
s.mu.RLock()
defer s.mu.RUnlock()
if err := s.ready(); err != nil {
return nil, err
}
return s.sfile, nil
}
// IsIdle return true if the shard is not receiving writes and is fully compacted.
func (s *Shard) IsIdle() (state bool, reason string) {
engine, err := s.Engine()
if err != nil {
return true, ""
}
return engine.IsIdle()
}
func (s *Shard) Free() error {
engine, err := s.Engine()
if err != nil {
return err
}
// Disable compactions to stop background goroutines
s.SetCompactionsEnabled(false)
return engine.Free()
}
// SetCompactionsEnabled enables or disable shard background compactions.
func (s *Shard) SetCompactionsEnabled(enabled bool) {
engine, err := s.Engine()
if err != nil {
return
}
engine.SetCompactionsEnabled(enabled)
}
// DiskSize returns the size on disk of this shard.
func (s *Shard) DiskSize() (int64, error) {
s.mu.RLock()
defer s.mu.RUnlock()
// We don't use engine() because we still want to report the shard's disk
// size even if the shard has been disabled.
if s._engine == nil {
return 0, ErrEngineClosed
}
size := s._engine.DiskSize()
return size, nil
}
// FieldCreate holds information for a field to create on a measurement.
type FieldCreate struct {
Measurement []byte
Field *Field
}
// WritePoints will write the raw data points and any new metadata to the index in the shard.
func (s *Shard) WritePoints(ctx context.Context, points []models.Point) (rErr error) {
s.mu.RLock()
defer s.mu.RUnlock()
engine, err := s.engineNoLock()
if err != nil {
return err
}
var writeError error
s.stats.writes.Observe(float64(len(points)))
defer func() {
if rErr != nil {
s.stats.writesErr.Observe(float64(len(points)))
}
}()
points, fieldsToCreate, err := s.validateSeriesAndFields(points)
if err != nil {
if _, ok := err.(PartialWriteError); !ok {
return err
}
// There was a partial write (points dropped), hold onto the error to return
// to the caller, but continue on writing the remaining points.
writeError = err
}
s.stats.fieldsCreated.Add(float64(len(fieldsToCreate)))
// add any new fields and keep track of what needs to be saved
if err := s.createFieldsAndMeasurements(fieldsToCreate); err != nil {
return err
}
// Write to the engine.
if err := engine.WritePoints(ctx, points); err != nil {
return fmt.Errorf("engine: %s", err)
}
return writeError
}
// validateSeriesAndFields checks which series and fields are new and whose metadata should be saved and indexed.
func (s *Shard) validateSeriesAndFields(points []models.Point) ([]models.Point, []*FieldCreate, error) {
var (
fieldsToCreate []*FieldCreate
err error
dropped int
reason string // only first error reason is set unless returned from CreateSeriesListIfNotExists
)
// Create all series against the index in bulk.
keys := make([][]byte, len(points))
names := make([][]byte, len(points))
tagsSlice := make([]models.Tags, len(points))
// Check if keys should be unicode validated.
validateKeys := s.options.Config.ValidateKeys
var j int
for i, p := range points {
tags := p.Tags()
// Drop any series w/ a "time" tag, these are illegal
if v := tags.Get(timeBytes); v != nil {
dropped++
if reason == "" {
reason = fmt.Sprintf(
"invalid tag key: input tag \"%s\" on measurement \"%s\" is invalid",
"time", string(p.Name()))
}
continue
}
// Drop any series with invalid unicode characters in the key.
if validateKeys && !models.ValidKeyTokens(string(p.Name()), tags) {
dropped++
if reason == "" {
reason = fmt.Sprintf("key contains invalid unicode: %q", makePrintable(string(p.Key())))
}
continue
}
keys[j] = p.Key()
names[j] = p.Name()
tagsSlice[j] = tags
points[j] = points[i]
j++
}
points, keys, names, tagsSlice = points[:j], keys[:j], names[:j], tagsSlice[:j]
engine, err := s.engineNoLock()
if err != nil {
return nil, nil, err
}
// Add new series. Check for partial writes.
var droppedKeys [][]byte
if err := engine.CreateSeriesListIfNotExists(keys, names, tagsSlice); err != nil {
switch err := err.(type) {
// (DSB) This was previously *PartialWriteError. Now catch pointer and value types.
case *PartialWriteError:
reason = err.Reason
dropped += err.Dropped
droppedKeys = err.DroppedKeys
s.stats.writesDropped.Add(float64(err.Dropped))
case PartialWriteError:
reason = err.Reason
dropped += err.Dropped
droppedKeys = err.DroppedKeys
s.stats.writesDropped.Add(float64(err.Dropped))
default:
return nil, nil, err
}
}
j = 0
for i, p := range points {
// Skip any points with only invalid fields.
iter := p.FieldIterator()
validField := false
for iter.Next() {
if bytes.Equal(iter.FieldKey(), timeBytes) {
continue
}
validField = true
break
}
if !validField {
if reason == "" {
reason = fmt.Sprintf(
"invalid field name: input field \"%s\" on measurement \"%s\" is invalid",
"time", string(p.Name()))
}
dropped++
continue
}
// Skip any points whos keys have been dropped. Dropped has already been incremented for them.
if len(droppedKeys) > 0 && bytesutil.Contains(droppedKeys, keys[i]) {
continue
}
name := p.Name()
mf := engine.MeasurementFields(name)
// Check with the field validator.
if err := ValidateFields(mf, p, s.options.Config.SkipFieldSizeValidation); err != nil {
switch err := err.(type) {
case PartialWriteError:
if reason == "" {
reason = err.Reason
}
dropped += err.Dropped
s.stats.writesDropped.Add(float64(err.Dropped))
default:
return nil, nil, err
}
continue
}
points[j] = points[i]
j++
// Create any fields that are missing.
iter.Reset()
for iter.Next() {
fieldKey := iter.FieldKey()
// Skip fields named "time". They are illegal.
if bytes.Equal(fieldKey, timeBytes) {
continue
}
if mf.FieldBytes(fieldKey) != nil {
continue
}
dataType := dataTypeFromModelsFieldType(iter.Type())
if dataType == influxql.Unknown {
continue
}
fieldsToCreate = append(fieldsToCreate, &FieldCreate{
Measurement: name,
Field: &Field{
Name: string(fieldKey),
Type: dataType,
},
})
}
}
if dropped > 0 {
err = PartialWriteError{Reason: reason, Dropped: dropped}
}
return points[:j], fieldsToCreate, err
}
const unPrintReplRune = '?'
const unPrintMaxReplRune = 3
// makePrintable - replace invalid and non-printable unicode characters with a few '?' runes
func makePrintable(s string) string {
b := strings.Builder{}
b.Grow(len(s))
c := 0
for _, r := range strings.ToValidUTF8(s, string(unicode.ReplacementChar)) {
if !unicode.IsPrint(r) || r == unicode.ReplacementChar {
if c < unPrintMaxReplRune {
b.WriteRune(unPrintReplRune)
}
c++
} else {
b.WriteRune(r)
c = 0
}
}
return b.String()
}
func (s *Shard) createFieldsAndMeasurements(fieldsToCreate []*FieldCreate) error {
if len(fieldsToCreate) == 0 {
return nil
}
engine, err := s.engineNoLock()
if err != nil {
return err
}
// add fields
changes := make([]*FieldChange, 0, len(fieldsToCreate))
for _, f := range fieldsToCreate {
mf := engine.MeasurementFields(f.Measurement)
if err := mf.CreateFieldIfNotExists([]byte(f.Field.Name), f.Field.Type); err != nil {
return err
}
changes = append(changes, &FieldChange{
FieldCreate: *f,
ChangeType: AddMeasurementField,
})
}
return engine.MeasurementFieldSet().Save(changes)
}
// DeleteSeriesRange deletes all values from for seriesKeys between min and max (inclusive)
func (s *Shard) DeleteSeriesRange(ctx context.Context, itr SeriesIterator, min, max int64) error {
engine, err := s.Engine()
if err != nil {
return err
}
return engine.DeleteSeriesRange(ctx, itr, min, max)
}
// DeleteSeriesRangeWithPredicate deletes all values from for seriesKeys between min and max (inclusive)
// for which predicate() returns true. If predicate() is nil, then all values in range are deleted.
func (s *Shard) DeleteSeriesRangeWithPredicate(
ctx context.Context,
itr SeriesIterator,
predicate func(name []byte, tags models.Tags) (int64, int64, bool),
) error {
engine, err := s.Engine()
if err != nil {
return err
}
return engine.DeleteSeriesRangeWithPredicate(ctx, itr, predicate)
}
// DeleteMeasurement deletes a measurement and all underlying series.
func (s *Shard) DeleteMeasurement(ctx context.Context, name []byte) error {
engine, err := s.Engine()
if err != nil {
return err
}
return engine.DeleteMeasurement(ctx, name)
}
// SeriesN returns the unique number of series in the shard.
func (s *Shard) SeriesN() int64 {
engine, err := s.Engine()
if err != nil {
return 0
}
return engine.SeriesN()
}
// SeriesSketches returns the measurement sketches for the shard.
func (s *Shard) SeriesSketches() (estimator.Sketch, estimator.Sketch, error) {
engine, err := s.Engine()
if err != nil {
return nil, nil, err
}
return engine.SeriesSketches()
}
// MeasurementsSketches returns the measurement sketches for the shard.
func (s *Shard) MeasurementsSketches() (estimator.Sketch, estimator.Sketch, error) {
engine, err := s.Engine()
if err != nil {
return nil, nil, err
}
return engine.MeasurementsSketches()
}
// MeasurementNamesByRegex returns names of measurements matching the regular expression.
func (s *Shard) MeasurementNamesByRegex(re *regexp.Regexp) ([][]byte, error) {
engine, err := s.Engine()
if err != nil {
return nil, err
}
return engine.MeasurementNamesByRegex(re)
}
// MeasurementNamesByPredicate returns fields for a measurement filtered by an expression.
func (s *Shard) MeasurementNamesByPredicate(expr influxql.Expr) ([][]byte, error) {
index, err := s.Index()
if err != nil {
return nil, err
}
indexSet := IndexSet{Indexes: []Index{index}, SeriesFile: s.sfile}
return indexSet.MeasurementNamesByPredicate(query.OpenAuthorizer, expr)
}
// MeasurementFields returns fields for a measurement.
func (s *Shard) MeasurementFields(name []byte) *MeasurementFields {
engine, err := s.Engine()
if err != nil {
return nil
}
return engine.MeasurementFields(name)
}
// MeasurementExists returns true if the shard contains name.
// TODO(edd): This method is currently only being called from tests; do we
// really need it?
func (s *Shard) MeasurementExists(name []byte) (bool, error) {
engine, err := s.Engine()
if err != nil {
return false, err
}
return engine.MeasurementExists(name)
}
// CreateIterator returns an iterator for the data in the shard.
func (s *Shard) CreateIterator(ctx context.Context, m *influxql.Measurement, opt query.IteratorOptions) (query.Iterator, error) {
engine, err := s.Engine()
if err != nil {
return nil, err
}
switch m.SystemIterator {
case "_fieldKeys":
return NewFieldKeysIterator(s, opt)
case "_series":
// TODO(benbjohnson): Move up to the Shards.CreateIterator().