-
Notifications
You must be signed in to change notification settings - Fork 569
/
Copy pathingester.go
4245 lines (3577 loc) · 156 KB
/
ingester.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
// SPDX-License-Identifier: AGPL-3.0-only
// Provenance-includes-location: https://github.com/cortexproject/cortex/blob/master/pkg/ingester/ingester.go
// Provenance-includes-license: Apache-2.0
// Provenance-includes-copyright: The Cortex Authors.
// Provenance-includes-location: https://github.com/cortexproject/cortex/blob/master/pkg/ingester/ingester_v2.go
// Provenance-includes-license: Apache-2.0
// Provenance-includes-copyright: The Cortex Authors.
package ingester
import (
"context"
"encoding/json"
"flag"
"fmt"
"io"
"math"
"net/http"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"time"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/grafana/dskit/concurrency"
"github.com/grafana/dskit/kv"
"github.com/grafana/dskit/middleware"
"github.com/grafana/dskit/ring"
"github.com/grafana/dskit/services"
"github.com/grafana/dskit/tenant"
"github.com/oklog/ulid"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/model"
promcfg "github.com/prometheus/prometheus/config"
"github.com/prometheus/prometheus/model/exemplar"
"github.com/prometheus/prometheus/model/histogram"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/storage"
"github.com/prometheus/prometheus/tsdb"
"github.com/prometheus/prometheus/tsdb/chunkenc"
"github.com/prometheus/prometheus/tsdb/chunks"
"github.com/prometheus/prometheus/tsdb/hashcache"
"github.com/prometheus/prometheus/tsdb/index"
"github.com/prometheus/prometheus/util/zeropool"
"github.com/thanos-io/objstore"
"go.uber.org/atomic"
"golang.org/x/sync/errgroup"
"github.com/grafana/mimir/pkg/costattribution"
"github.com/grafana/mimir/pkg/ingester/activeseries"
asmodel "github.com/grafana/mimir/pkg/ingester/activeseries/model"
"github.com/grafana/mimir/pkg/ingester/client"
"github.com/grafana/mimir/pkg/mimirpb"
"github.com/grafana/mimir/pkg/querier/api"
mimir_storage "github.com/grafana/mimir/pkg/storage"
"github.com/grafana/mimir/pkg/storage/bucket"
"github.com/grafana/mimir/pkg/storage/ingest"
"github.com/grafana/mimir/pkg/storage/sharding"
mimir_tsdb "github.com/grafana/mimir/pkg/storage/tsdb"
"github.com/grafana/mimir/pkg/storage/tsdb/block"
"github.com/grafana/mimir/pkg/usagestats"
"github.com/grafana/mimir/pkg/util"
"github.com/grafana/mimir/pkg/util/globalerror"
"github.com/grafana/mimir/pkg/util/limiter"
util_log "github.com/grafana/mimir/pkg/util/log"
util_math "github.com/grafana/mimir/pkg/util/math"
"github.com/grafana/mimir/pkg/util/reactivelimiter"
"github.com/grafana/mimir/pkg/util/shutdownmarker"
"github.com/grafana/mimir/pkg/util/spanlogger"
"github.com/grafana/mimir/pkg/util/tracing"
"github.com/grafana/mimir/pkg/util/validation"
)
const (
// Number of timeseries to return in each batch of a QueryStream.
queryStreamBatchSize = 128
// Discarded Metadata metric labels.
perUserMetadataLimit = "per_user_metadata_limit"
perMetricMetadataLimit = "per_metric_metadata_limit"
// Period at which to attempt purging metadata from memory.
metadataPurgePeriod = 5 * time.Minute
// How frequently update the usage statistics.
usageStatsUpdateInterval = usagestats.DefaultReportSendInterval / 10
// IngesterRingKey is the key under which we store the ingesters ring in the KVStore.
IngesterRingKey = "ring"
// PartitionRingKey is the key under which we store the partitions ring used by the "ingest storage".
PartitionRingKey = "ingester-partitions"
PartitionRingName = "ingester-partitions"
// Jitter applied to the idle timeout to prevent compaction in all ingesters concurrently.
compactionIdleTimeoutJitter = 0.25
instanceIngestionRateTickInterval = time.Second
// Reasons for discarding samples
reasonSampleOutOfOrder = "sample-out-of-order"
reasonSampleTooOld = "sample-too-old"
reasonSampleTooFarInFuture = "sample-too-far-in-future"
reasonNewValueForTimestamp = "new-value-for-timestamp"
reasonSampleTimestampTooOld = "sample-timestamp-too-old"
reasonPerUserSeriesLimit = "per_user_series_limit"
reasonPerMetricSeriesLimit = "per_metric_series_limit"
reasonInvalidNativeHistogram = "invalid-native-histogram"
replicationFactorStatsName = "ingester_replication_factor"
ringStoreStatsName = "ingester_ring_store"
memorySeriesStatsName = "ingester_inmemory_series"
activeSeriesStatsName = "ingester_active_series"
memoryTenantsStatsName = "ingester_inmemory_tenants"
appendedSamplesStatsName = "ingester_appended_samples"
appendedExemplarsStatsName = "ingester_appended_exemplars"
tenantsWithOutOfOrderEnabledStatName = "ingester_ooo_enabled_tenants"
minOutOfOrderTimeWindowSecondsStatName = "ingester_ooo_min_window"
maxOutOfOrderTimeWindowSecondsStatName = "ingester_ooo_max_window"
// Value used to track the limit between sequential and concurrent TSDB opernings.
// Below this value, TSDBs of different tenants are opened sequentially, otherwise concurrently.
maxTSDBOpenWithoutConcurrency = 10
)
var (
reasonIngesterMaxIngestionRate = globalerror.IngesterMaxIngestionRate.LabelValue()
reasonIngesterMaxTenants = globalerror.IngesterMaxTenants.LabelValue()
reasonIngesterMaxInMemorySeries = globalerror.IngesterMaxInMemorySeries.LabelValue()
reasonIngesterMaxInflightPushRequests = globalerror.IngesterMaxInflightPushRequests.LabelValue()
reasonIngesterMaxInflightPushRequestsBytes = globalerror.IngesterMaxInflightPushRequestsBytes.LabelValue()
reasonIngesterMaxInflightReadRequests = globalerror.IngesterMaxInflightReadRequests.LabelValue()
)
// Usage-stats expvars. Initialized as package-global in order to avoid race conditions and panics
// when initializing expvars per-ingester in multiple parallel tests at once.
var (
// updated in Ingester.updateUsageStats.
memorySeriesStats = usagestats.GetAndResetInt(memorySeriesStatsName)
memoryTenantsStats = usagestats.GetAndResetInt(memoryTenantsStatsName)
activeSeriesStats = usagestats.GetAndResetInt(activeSeriesStatsName)
tenantsWithOutOfOrderEnabledStat = usagestats.GetAndResetInt(tenantsWithOutOfOrderEnabledStatName)
minOutOfOrderTimeWindowSecondsStat = usagestats.GetAndResetInt(minOutOfOrderTimeWindowSecondsStatName)
maxOutOfOrderTimeWindowSecondsStat = usagestats.GetAndResetInt(maxOutOfOrderTimeWindowSecondsStatName)
// updated in Ingester.PushWithCleanup.
appendedSamplesStats = usagestats.GetAndResetCounter(appendedSamplesStatsName)
appendedExemplarsStats = usagestats.GetAndResetCounter(appendedExemplarsStatsName)
// Set in newIngester.
replicationFactor = usagestats.GetInt(replicationFactorStatsName)
ringStoreName = usagestats.GetString(ringStoreStatsName)
)
// BlocksUploader interface is used to have an easy way to mock it in tests.
type BlocksUploader interface {
Sync(ctx context.Context) (uploaded int, err error)
}
// QueryStreamType defines type of function to use when doing query-stream operation.
type QueryStreamType int
const (
QueryStreamDefault QueryStreamType = iota // Use default configured value.
QueryStreamSamples // Stream individual samples.
QueryStreamChunks // Stream entire chunks.
)
type requestWithUsersAndCallback struct {
users *util.AllowedTenants // if nil, all tenants are allowed.
callback chan<- struct{} // when compaction/shipping is finished, this channel is closed
}
// Config for an Ingester.
type Config struct {
IngesterRing RingConfig `yaml:"ring"`
IngesterPartitionRing PartitionRingConfig `yaml:"partition_ring" category:"experimental"`
// Config for metadata purging.
MetadataRetainPeriod time.Duration `yaml:"metadata_retain_period" category:"advanced"`
RateUpdatePeriod time.Duration `yaml:"rate_update_period" category:"advanced"`
ActiveSeriesMetrics activeseries.Config `yaml:",inline"`
TSDBConfigUpdatePeriod time.Duration `yaml:"tsdb_config_update_period" category:"experimental"`
BlocksStorageConfig mimir_tsdb.BlocksStorageConfig `yaml:"-"`
StreamChunksWhenUsingBlocks bool `yaml:"-" category:"advanced"`
// Runtime-override for type of streaming query to use (chunks or samples).
StreamTypeFn func() QueryStreamType `yaml:"-"`
DefaultLimits InstanceLimits `yaml:"instance_limits"`
InstanceLimitsFn func() *InstanceLimits `yaml:"-"`
IgnoreSeriesLimitForMetricNames string `yaml:"ignore_series_limit_for_metric_names" category:"advanced"`
ReadPathCPUUtilizationLimit float64 `yaml:"read_path_cpu_utilization_limit" category:"experimental"`
ReadPathMemoryUtilizationLimit uint64 `yaml:"read_path_memory_utilization_limit" category:"experimental"`
ErrorSampleRate int64 `yaml:"error_sample_rate" json:"error_sample_rate" category:"advanced"`
// UseIngesterOwnedSeriesForLimits was added in 2.12, but we keep it experimental until we decide, what is the correct behaviour
// when the replication factor and the number of zones don't match. Refer to notes in https://github.com/grafana/mimir/pull/8695 and https://github.com/grafana/mimir/pull/9496
UseIngesterOwnedSeriesForLimits bool `yaml:"use_ingester_owned_series_for_limits" category:"experimental"`
UpdateIngesterOwnedSeries bool `yaml:"track_ingester_owned_series" category:"experimental"`
OwnedSeriesUpdateInterval time.Duration `yaml:"owned_series_update_interval" category:"experimental"`
PushCircuitBreaker CircuitBreakerConfig `yaml:"push_circuit_breaker"`
ReadCircuitBreaker CircuitBreakerConfig `yaml:"read_circuit_breaker"`
RejectionPrioritizer reactivelimiter.RejectionPrioritizerConfig `yaml:"rejection_prioritizer"`
PushReactiveLimiter reactivelimiter.Config `yaml:"push_reactive_limiter"`
ReadReactiveLimiter reactivelimiter.Config `yaml:"read_reactive_limiter"`
PushGrpcMethodEnabled bool `yaml:"push_grpc_method_enabled" category:"experimental" doc:"hidden"`
// This config is dynamically injected because defined outside the ingester config.
IngestStorageConfig ingest.Config `yaml:"-"`
// This config can be overridden in tests.
limitMetricsUpdatePeriod time.Duration `yaml:"-"`
}
// RegisterFlags adds the flags required to config this to the given FlagSet
func (cfg *Config) RegisterFlags(f *flag.FlagSet, logger log.Logger) {
cfg.IngesterRing.RegisterFlags(f, logger)
cfg.IngesterPartitionRing.RegisterFlags(f)
cfg.DefaultLimits.RegisterFlags(f)
cfg.ActiveSeriesMetrics.RegisterFlags(f)
cfg.PushCircuitBreaker.RegisterFlagsWithPrefix("ingester.push-circuit-breaker.", f, circuitBreakerDefaultPushTimeout)
cfg.ReadCircuitBreaker.RegisterFlagsWithPrefix("ingester.read-circuit-breaker.", f, circuitBreakerDefaultReadTimeout)
cfg.RejectionPrioritizer.RegisterFlagsWithPrefix("ingester.rejection-prioritizer.", f)
cfg.PushReactiveLimiter.RegisterFlagsWithPrefix("ingester.push-reactive-limiter.", f)
cfg.ReadReactiveLimiter.RegisterFlagsWithPrefix("ingester.read-reactive-limiter.", f)
f.DurationVar(&cfg.MetadataRetainPeriod, "ingester.metadata-retain-period", 10*time.Minute, "Period at which metadata we have not seen will remain in memory before being deleted.")
f.DurationVar(&cfg.RateUpdatePeriod, "ingester.rate-update-period", 15*time.Second, "Period with which to update the per-tenant ingestion rates.")
f.BoolVar(&cfg.StreamChunksWhenUsingBlocks, "ingester.stream-chunks-when-using-blocks", true, "Stream chunks from ingesters to queriers.")
f.DurationVar(&cfg.TSDBConfigUpdatePeriod, "ingester.tsdb-config-update-period", 15*time.Second, "Period with which to update the per-tenant TSDB configuration.")
f.StringVar(&cfg.IgnoreSeriesLimitForMetricNames, "ingester.ignore-series-limit-for-metric-names", "", "Comma-separated list of metric names, for which the -ingester.max-global-series-per-metric limit will be ignored. Does not affect the -ingester.max-global-series-per-user limit.")
f.Float64Var(&cfg.ReadPathCPUUtilizationLimit, "ingester.read-path-cpu-utilization-limit", 0, "CPU utilization limit, as CPU cores, for CPU/memory utilization based read request limiting. Use 0 to disable it.")
f.Uint64Var(&cfg.ReadPathMemoryUtilizationLimit, "ingester.read-path-memory-utilization-limit", 0, "Memory limit, in bytes, for CPU/memory utilization based read request limiting. Use 0 to disable it.")
f.Int64Var(&cfg.ErrorSampleRate, "ingester.error-sample-rate", 10, "Each error will be logged once in this many times. Use 0 to log all of them.")
f.BoolVar(&cfg.UseIngesterOwnedSeriesForLimits, "ingester.use-ingester-owned-series-for-limits", false, "When enabled, only series currently owned by ingester according to the ring are used when checking user per-tenant series limit.")
f.BoolVar(&cfg.UpdateIngesterOwnedSeries, "ingester.track-ingester-owned-series", false, "This option enables tracking of ingester-owned series based on ring state, even if -ingester.use-ingester-owned-series-for-limits is disabled.")
f.DurationVar(&cfg.OwnedSeriesUpdateInterval, "ingester.owned-series-update-interval", 15*time.Second, "How often to check for ring changes and possibly recompute owned series as a result of detected change.")
f.BoolVar(&cfg.PushGrpcMethodEnabled, "ingester.push-grpc-method-enabled", true, "Enables Push gRPC method on ingester. Can be only disabled when using ingest-storage to make sure ingesters only receive data from Kafka.")
// Hardcoded config (can only be overridden in tests).
cfg.limitMetricsUpdatePeriod = time.Second * 15
}
func (cfg *Config) Validate(log.Logger) error {
if cfg.ErrorSampleRate < 0 {
return fmt.Errorf("error sample rate cannot be a negative number")
}
return cfg.IngesterRing.Validate()
}
func (cfg *Config) getIgnoreSeriesLimitForMetricNamesMap() map[string]struct{} {
if cfg.IgnoreSeriesLimitForMetricNames == "" {
return nil
}
result := map[string]struct{}{}
for _, s := range strings.Split(cfg.IgnoreSeriesLimitForMetricNames, ",") {
tr := strings.TrimSpace(s)
if tr != "" {
result[tr] = struct{}{}
}
}
if len(result) == 0 {
return nil
}
return result
}
// Ingester deals with "in flight" chunks. Based on Prometheus 1.x
// MemorySeriesStorage.
type Ingester struct {
*services.BasicService
cfg Config
metrics *ingesterMetrics
logger log.Logger
lifecycler *ring.Lifecycler
limits *validation.Overrides
limiter *Limiter
subservicesWatcher *services.FailureWatcher
ownedSeriesService *ownedSeriesService
compactionService services.Service
metricsUpdaterService services.Service
metadataPurgerService services.Service
// Mimir blocks storage.
tsdbsMtx sync.RWMutex
tsdbs map[string]*userTSDB // tsdb sharded by userID
bucket objstore.Bucket
// Value used by shipper as external label.
shipperIngesterID string
// Metrics shared across all per-tenant shippers.
shipperMetrics *shipperMetrics
subservicesForPartitionReplay *services.Manager
subservicesAfterIngesterRingLifecycler *services.Manager
activeGroups *util.ActiveGroupsCleanupService
costAttributionMgr *costattribution.Manager
tsdbMetrics *tsdbMetrics
forceCompactTrigger chan requestWithUsersAndCallback
shipTrigger chan requestWithUsersAndCallback
// Maps the per-block series ID with its labels hash.
seriesHashCache *hashcache.SeriesHashCache
// Timeout chosen for idle compactions.
compactionIdleTimeout time.Duration
// Number of series in memory, across all tenants.
seriesCount atomic.Int64
// For storing metadata ingested.
usersMetadataMtx sync.RWMutex
usersMetadata map[string]*userMetricsMetadata
// Rate of pushed samples. Used to limit global samples push rate.
ingestionRate *util_math.EwmaRate
inflightPushRequests atomic.Int64
inflightPushRequestsBytes atomic.Int64
utilizationBasedLimiter utilizationBasedLimiter
errorSamplers ingesterErrSamplers
// The following is used by ingest storage (when enabled).
ingestReader *ingest.PartitionReader
ingestPartitionID int32
ingestPartitionLifecycler *ring.PartitionInstanceLifecycler
circuitBreaker ingesterCircuitBreaker
reactiveLimiter *ingesterReactiveLimiter
}
func newIngester(cfg Config, limits *validation.Overrides, registerer prometheus.Registerer, logger log.Logger) (*Ingester, error) {
if cfg.BlocksStorageConfig.Bucket.Backend == bucket.Filesystem {
level.Warn(logger).Log("msg", "-blocks-storage.backend=filesystem is for development and testing only; you should switch to an external object store for production use or use a shared filesystem")
}
bucketClient, err := bucket.NewClient(context.Background(), cfg.BlocksStorageConfig.Bucket, "ingester", logger, registerer)
if err != nil {
return nil, errors.Wrap(err, "failed to create the bucket client")
}
// Track constant usage stats.
replicationFactor.Set(int64(cfg.IngesterRing.ReplicationFactor))
ringStoreName.Set(cfg.IngesterRing.KVStore.Store)
return &Ingester{
cfg: cfg,
limits: limits,
logger: logger,
tsdbs: make(map[string]*userTSDB),
usersMetadata: make(map[string]*userMetricsMetadata),
bucket: bucketClient,
tsdbMetrics: newTSDBMetrics(registerer, logger),
shipperMetrics: newShipperMetrics(registerer),
forceCompactTrigger: make(chan requestWithUsersAndCallback),
shipTrigger: make(chan requestWithUsersAndCallback),
seriesHashCache: hashcache.NewSeriesHashCache(cfg.BlocksStorageConfig.TSDB.SeriesHashCacheMaxBytes),
errorSamplers: newIngesterErrSamplers(cfg.ErrorSampleRate),
}, nil
}
// New returns an Ingester that uses Mimir block storage.
func New(cfg Config, limits *validation.Overrides, ingestersRing ring.ReadRing, partitionRingWatcher *ring.PartitionRingWatcher, activeGroupsCleanupService *util.ActiveGroupsCleanupService, costAttributionMgr *costattribution.Manager, registerer prometheus.Registerer, logger log.Logger) (*Ingester, error) {
i, err := newIngester(cfg, limits, registerer, logger)
if err != nil {
return nil, err
}
i.ingestionRate = util_math.NewEWMARate(0.2, instanceIngestionRateTickInterval)
i.metrics = newIngesterMetrics(registerer, cfg.ActiveSeriesMetrics.Enabled, i.getInstanceLimits, i.ingestionRate, &i.inflightPushRequests, &i.inflightPushRequestsBytes)
i.activeGroups = activeGroupsCleanupService
i.costAttributionMgr = costAttributionMgr
// We create a circuit breaker, which will be activated on a successful completion of starting.
i.circuitBreaker = newIngesterCircuitBreaker(i.cfg.PushCircuitBreaker, i.cfg.ReadCircuitBreaker, logger, registerer)
i.reactiveLimiter = newIngesterReactiveLimiter(&i.cfg.RejectionPrioritizer, &i.cfg.PushReactiveLimiter, &i.cfg.ReadReactiveLimiter, logger, registerer)
if registerer != nil {
promauto.With(registerer).NewGaugeFunc(prometheus.GaugeOpts{
Name: "cortex_ingester_oldest_unshipped_block_timestamp_seconds",
Help: "Unix timestamp of the oldest TSDB block not shipped to the storage yet. 0 if ingester has no blocks or all blocks have been shipped.",
}, i.getOldestUnshippedBlockMetric)
promauto.With(registerer).NewGaugeFunc(prometheus.GaugeOpts{
Name: "cortex_ingester_tsdb_head_min_timestamp_seconds",
Help: "Minimum timestamp of the head block across all tenants.",
}, i.minTsdbHeadTimestamp)
promauto.With(registerer).NewGaugeFunc(prometheus.GaugeOpts{
Name: "cortex_ingester_tsdb_head_max_timestamp_seconds",
Help: "Maximum timestamp of the head block across all tenants.",
}, i.maxTsdbHeadTimestamp)
}
i.lifecycler, err = ring.NewLifecycler(cfg.IngesterRing.ToLifecyclerConfig(), i, "ingester", IngesterRingKey, cfg.BlocksStorageConfig.TSDB.FlushBlocksOnShutdown, logger, prometheus.WrapRegistererWithPrefix("cortex_", registerer))
if err != nil {
return nil, err
}
i.subservicesWatcher = services.NewFailureWatcher()
i.subservicesWatcher.WatchService(i.lifecycler)
if cfg.ReadPathCPUUtilizationLimit > 0 || cfg.ReadPathMemoryUtilizationLimit > 0 {
i.utilizationBasedLimiter = limiter.NewUtilizationBasedLimiter(cfg.ReadPathCPUUtilizationLimit,
cfg.ReadPathMemoryUtilizationLimit, true,
log.WithPrefix(logger, "context", "read path"),
prometheus.WrapRegistererWithPrefix("cortex_ingester_", registerer))
}
i.shipperIngesterID = i.lifecycler.ID
// Apply positive jitter only to ensure that the minimum timeout is adhered to.
i.compactionIdleTimeout = util.DurationWithPositiveJitter(i.cfg.BlocksStorageConfig.TSDB.HeadCompactionIdleTimeout, compactionIdleTimeoutJitter)
level.Info(i.logger).Log("msg", "TSDB idle compaction timeout set", "timeout", i.compactionIdleTimeout)
var limiterStrategy limiterRingStrategy
var ownedSeriesStrategy ownedSeriesRingStrategy
if ingestCfg := cfg.IngestStorageConfig; ingestCfg.Enabled {
kafkaCfg := ingestCfg.KafkaConfig
i.ingestPartitionID, err = ingest.IngesterPartitionID(cfg.IngesterRing.InstanceID)
if err != nil {
return nil, errors.Wrap(err, "calculating ingester partition ID")
}
// We use the ingester instance ID as consumer group. This means that we have N consumer groups
// where N is the total number of ingesters. Each ingester is part of their own consumer group
// so that they all replay the owned partition with no gaps.
kafkaCfg.FallbackClientErrorSampleRate = cfg.ErrorSampleRate
i.ingestReader, err = ingest.NewPartitionReaderForPusher(kafkaCfg, i.ingestPartitionID, cfg.IngesterRing.InstanceID, i, log.With(logger, "component", "ingest_reader"), registerer)
if err != nil {
return nil, errors.Wrap(err, "creating ingest storage reader")
}
partitionRingKV := cfg.IngesterPartitionRing.KVStore.Mock
if partitionRingKV == nil {
partitionRingKV, err = kv.NewClient(cfg.IngesterPartitionRing.KVStore, ring.GetPartitionRingCodec(), kv.RegistererWithKVName(registerer, PartitionRingName+"-lifecycler"), logger)
if err != nil {
return nil, errors.Wrap(err, "creating KV store for ingester partition ring")
}
}
i.ingestPartitionLifecycler = ring.NewPartitionInstanceLifecycler(
i.cfg.IngesterPartitionRing.ToLifecyclerConfig(i.ingestPartitionID, cfg.IngesterRing.InstanceID),
PartitionRingName,
PartitionRingKey,
partitionRingKV,
logger,
prometheus.WrapRegistererWithPrefix("cortex_", registerer))
limiterStrategy = newPartitionRingLimiterStrategy(partitionRingWatcher, i.limits.IngestionPartitionsTenantShardSize)
ownedSeriesStrategy = newOwnedSeriesPartitionRingStrategy(i.ingestPartitionID, partitionRingWatcher, i.limits.IngestionPartitionsTenantShardSize)
} else {
limiterStrategy = newIngesterRingLimiterStrategy(ingestersRing, cfg.IngesterRing.ReplicationFactor, cfg.IngesterRing.ZoneAwarenessEnabled, cfg.IngesterRing.InstanceZone, i.limits.IngestionTenantShardSize)
ownedSeriesStrategy = newOwnedSeriesIngesterRingStrategy(i.lifecycler.ID, ingestersRing, i.limits.IngestionTenantShardSize)
}
i.limiter = NewLimiter(limits, limiterStrategy)
if cfg.UseIngesterOwnedSeriesForLimits || cfg.UpdateIngesterOwnedSeries {
i.ownedSeriesService = newOwnedSeriesService(i.cfg.OwnedSeriesUpdateInterval, ownedSeriesStrategy, log.With(i.logger, "component", "owned series"), registerer, i.limiter.maxSeriesPerUser, i.getTSDBUsers, i.getTSDB)
// We add owned series service explicitly, because ingester doesn't start it using i.subservices.
i.subservicesWatcher.WatchService(i.ownedSeriesService)
}
// Init compaction service, responsible to periodically run TSDB head compactions.
i.compactionService = services.NewBasicService(nil, i.compactionServiceRunning, nil)
i.subservicesWatcher.WatchService(i.compactionService)
// Init metrics updater service, responsible to periodically update ingester metrics and stats.
i.metricsUpdaterService = services.NewBasicService(nil, i.metricsUpdaterServiceRunning, nil)
i.subservicesWatcher.WatchService(i.metricsUpdaterService)
// Init metadata purger service, responsible to periodically delete metrics metadata past their retention period.
i.metadataPurgerService = services.NewTimerService(metadataPurgePeriod, nil, func(context.Context) error {
i.purgeUserMetricsMetadata()
return nil
}, nil)
i.subservicesWatcher.WatchService(i.metadataPurgerService)
i.BasicService = services.NewBasicService(i.starting, i.ingesterRunning, i.stopping)
return i, nil
}
// NewForFlusher is a special version of ingester used by Flusher. This
// ingester is not ingesting anything, its only purpose is to react on Flush
// method and flush all openened TSDBs when called.
func NewForFlusher(cfg Config, limits *validation.Overrides, registerer prometheus.Registerer, logger log.Logger) (*Ingester, error) {
i, err := newIngester(cfg, limits, registerer, logger)
if err != nil {
return nil, err
}
i.metrics = newIngesterMetrics(registerer, false, i.getInstanceLimits, nil, &i.inflightPushRequests, &i.inflightPushRequestsBytes)
i.shipperIngesterID = "flusher"
i.limiter = NewLimiter(limits, flusherLimiterStrategy{})
// This ingester will not start any subservices (lifecycler, compaction, shipping),
// and will only open TSDBs, wait for Flush to be called, and then close TSDBs again.
i.BasicService = services.NewIdleService(i.startingForFlusher, i.stoppingForFlusher)
return i, nil
}
func (i *Ingester) startingForFlusher(ctx context.Context) error {
if err := i.openExistingTSDB(ctx); err != nil {
// Try to rollback and close opened TSDBs before halting the ingester.
i.closeAllTSDB()
return errors.Wrap(err, "opening existing TSDBs")
}
// Don't start any sub-services (lifecycler, compaction, shipper) at all.
return nil
}
func (i *Ingester) starting(ctx context.Context) (err error) {
defer func() {
if err != nil {
// if starting() fails for any reason (e.g., context canceled),
// the lifecycler must be stopped.
_ = services.StopAndAwaitTerminated(context.Background(), i.lifecycler)
}
}()
// First of all we have to check if the shutdown marker is set. This needs to be done
// as first thing because, if found, it may change the behaviour of the ingester startup.
if exists, err := shutdownmarker.Exists(shutdownmarker.GetPath(i.cfg.BlocksStorageConfig.TSDB.Dir)); err != nil {
return errors.Wrap(err, "failed to check ingester shutdown marker")
} else if exists {
level.Info(i.logger).Log("msg", "detected existing shutdown marker, setting unregister and flush on shutdown", "path", shutdownmarker.GetPath(i.cfg.BlocksStorageConfig.TSDB.Dir))
i.setPrepareShutdown()
}
if err := i.openExistingTSDB(ctx); err != nil {
// Try to rollback and close opened TSDBs before halting the ingester.
i.closeAllTSDB()
return errors.Wrap(err, "opening existing TSDBs")
}
if i.ownedSeriesService != nil {
// We need to perform the initial computation of owned series after the TSDBs are opened but before the ingester becomes
// ACTIVE in the ring and starts to accept requests. However, because the ingester still uses the Lifecycler (rather
// than BasicLifecycler) there is no deterministic way to delay the ACTIVE state until we finish the calculations.
//
// Start owned series service before starting lifecyclers. We wait for ownedSeriesService
// to enter Running state here, that is ownedSeriesService computes owned series if ring is not empty.
// If ring is empty, ownedSeriesService doesn't do anything.
// If ring is not empty, but instance is not in the ring yet, ownedSeriesService will compute 0 owned series.
//
// We pass ingester's service context to ownedSeriesService, to make ownedSeriesService stop when ingester's
// context is done (i.e. when ingester fails in Starting state, or when ingester exits Running state).
if err := services.StartAndAwaitRunning(ctx, i.ownedSeriesService); err != nil {
return errors.Wrap(err, "failed to start owned series service")
}
}
// Start the following services before starting the ingest storage reader, in order to have them
// running while replaying the partition (if ingest storage is enabled).
i.subservicesForPartitionReplay, err = createManagerThenStartAndAwaitHealthy(ctx, i.compactionService, i.metricsUpdaterService, i.metadataPurgerService)
if err != nil {
return errors.Wrap(err, "failed to start ingester subservices before partition reader")
}
// When ingest storage is enabled, we have to make sure that reader catches up replaying the partition
// BEFORE the ingester ring lifecycler is started, because once the ingester ring lifecycler will start
// it will switch the ingester state in the ring to ACTIVE.
if i.ingestReader != nil {
if err := services.StartAndAwaitRunning(ctx, i.ingestReader); err != nil {
return errors.Wrap(err, "failed to start partition reader")
}
}
// Important: we want to keep lifecycler running until we ask it to stop, so we need to give it independent context
if err := i.lifecycler.StartAsync(context.Background()); err != nil {
return errors.Wrap(err, "failed to start lifecycler")
}
if err := i.lifecycler.AwaitRunning(ctx); err != nil {
return errors.Wrap(err, "failed to start lifecycler")
}
// Finally we start all services that should run after the ingester ring lifecycler.
var servs []services.Service
if i.cfg.BlocksStorageConfig.TSDB.IsBlocksShippingEnabled() {
shippingService := services.NewBasicService(nil, i.shipBlocksLoop, nil)
servs = append(servs, shippingService)
}
if i.cfg.BlocksStorageConfig.TSDB.CloseIdleTSDBTimeout > 0 {
interval := i.cfg.BlocksStorageConfig.TSDB.CloseIdleTSDBInterval
if interval == 0 {
interval = mimir_tsdb.DefaultCloseIdleTSDBInterval
}
closeIdleService := services.NewTimerService(interval, nil, i.closeAndDeleteIdleUserTSDBs, nil)
servs = append(servs, closeIdleService)
}
if i.utilizationBasedLimiter != nil {
servs = append(servs, i.utilizationBasedLimiter)
}
if i.reactiveLimiter != nil {
servs = append(servs, i.reactiveLimiter)
}
if i.ingestPartitionLifecycler != nil {
servs = append(servs, i.ingestPartitionLifecycler)
}
// Since subservices are conditional, We add an idle service if there are no subservices to
// guarantee there's at least 1 service to run otherwise the service manager fails to start.
if len(servs) == 0 {
servs = append(servs, services.NewIdleService(nil, nil))
}
i.subservicesAfterIngesterRingLifecycler, err = createManagerThenStartAndAwaitHealthy(ctx, servs...)
if err != nil {
return errors.Wrap(err, "failed to start ingester subservices after ingester ring lifecycler")
}
i.circuitBreaker.read.activate()
if ro, _ := i.lifecycler.GetReadOnlyState(); !ro {
// If the ingester is not read-only, activate the push circuit breaker.
i.circuitBreaker.push.activate()
}
return nil
}
func (i *Ingester) stoppingForFlusher(_ error) error {
if !i.cfg.BlocksStorageConfig.TSDB.KeepUserTSDBOpenOnShutdown {
i.closeAllTSDB()
}
return nil
}
func (i *Ingester) stopping(_ error) error {
if i.ingestReader != nil {
if err := services.StopAndAwaitTerminated(context.Background(), i.ingestReader); err != nil {
level.Warn(i.logger).Log("msg", "failed to stop partition reader", "err", err)
}
}
if i.ownedSeriesService != nil {
err := services.StopAndAwaitTerminated(context.Background(), i.ownedSeriesService)
if err != nil {
// This service can't really fail.
level.Warn(i.logger).Log("msg", "error encountered while stopping owned series service", "err", err)
}
}
// Stop subservices.
i.subservicesForPartitionReplay.StopAsync()
i.subservicesAfterIngesterRingLifecycler.StopAsync()
if err := i.subservicesForPartitionReplay.AwaitStopped(context.Background()); err != nil {
level.Warn(i.logger).Log("msg", "failed to stop ingester subservices", "err", err)
}
if err := i.subservicesAfterIngesterRingLifecycler.AwaitStopped(context.Background()); err != nil {
level.Warn(i.logger).Log("msg", "failed to stop ingester subservices", "err", err)
}
// Next initiate our graceful exit from the ring.
if err := services.StopAndAwaitTerminated(context.Background(), i.lifecycler); err != nil {
level.Warn(i.logger).Log("msg", "failed to stop ingester lifecycler", "err", err)
}
// Remove the shutdown marker if it exists since we are shutting down
shutdownMarkerPath := shutdownmarker.GetPath(i.cfg.BlocksStorageConfig.TSDB.Dir)
if err := shutdownmarker.Remove(shutdownMarkerPath); err != nil {
level.Warn(i.logger).Log("msg", "failed to remove shutdown marker", "path", shutdownMarkerPath, "err", err)
}
if !i.cfg.BlocksStorageConfig.TSDB.KeepUserTSDBOpenOnShutdown {
i.closeAllTSDB()
}
return nil
}
func (i *Ingester) ingesterRunning(ctx context.Context) error {
tsdbUpdateTicker := time.NewTicker(i.cfg.TSDBConfigUpdatePeriod)
defer tsdbUpdateTicker.Stop()
for {
select {
case <-tsdbUpdateTicker.C:
i.applyTSDBSettings()
case <-ctx.Done():
return nil
case err := <-i.subservicesWatcher.Chan():
return errors.Wrap(err, "ingester subservice failed")
}
}
}
// metricsUpdaterServiceRunning is the running function for the internal metrics updater service.
func (i *Ingester) metricsUpdaterServiceRunning(ctx context.Context) error {
// Launch a dedicated goroutine for inflightRequestsTicker
// to ensure it operates independently, unaffected by delays from other logics in this function.
go func() {
inflightRequestsTicker := time.NewTicker(250 * time.Millisecond)
defer inflightRequestsTicker.Stop()
for {
select {
case <-inflightRequestsTicker.C:
i.metrics.inflightRequestsSummary.Observe(float64(i.inflightPushRequests.Load()))
case <-ctx.Done():
return
}
}
}()
rateUpdateTicker := time.NewTicker(i.cfg.RateUpdatePeriod)
defer rateUpdateTicker.Stop()
ingestionRateTicker := time.NewTicker(instanceIngestionRateTickInterval)
defer ingestionRateTicker.Stop()
var activeSeriesTickerChan <-chan time.Time
if i.cfg.ActiveSeriesMetrics.Enabled {
t := time.NewTicker(i.cfg.ActiveSeriesMetrics.UpdatePeriod)
activeSeriesTickerChan = t.C
defer t.Stop()
}
usageStatsUpdateTicker := time.NewTicker(usageStatsUpdateInterval)
defer usageStatsUpdateTicker.Stop()
limitMetricsUpdateTicker := time.NewTicker(i.cfg.limitMetricsUpdatePeriod)
defer limitMetricsUpdateTicker.Stop()
for {
select {
case <-ingestionRateTicker.C:
i.ingestionRate.Tick()
case <-rateUpdateTicker.C:
i.tsdbsMtx.RLock()
for _, db := range i.tsdbs {
db.ingestedAPISamples.Tick()
db.ingestedRuleSamples.Tick()
}
i.tsdbsMtx.RUnlock()
case <-activeSeriesTickerChan:
i.updateActiveSeries(time.Now())
case <-usageStatsUpdateTicker.C:
i.updateUsageStats()
case <-limitMetricsUpdateTicker.C:
i.updateLimitMetrics()
case <-ctx.Done():
return nil
}
}
}
func (i *Ingester) replaceMatchersAndTrackers(asm *asmodel.Matchers, cat *costattribution.ActiveSeriesTracker, userDB *userTSDB, now time.Time) {
i.metrics.deletePerUserCustomTrackerMetrics(userDB.userID, userDB.activeSeries.CurrentMatcherNames())
userDB.activeSeries.ReloadMatchersAndTrackers(asm, cat, now)
}
func (i *Ingester) updateActiveSeries(now time.Time) {
for _, userID := range i.getTSDBUsers() {
userDB := i.getTSDB(userID)
if userDB == nil {
continue
}
newMatchersConfig := i.limits.ActiveSeriesCustomTrackersConfig(userID)
newCostAttributionActiveSeriesTracker := i.costAttributionMgr.ActiveSeriesTracker(userID)
if userDB.activeSeries.ConfigDiffers(newMatchersConfig, newCostAttributionActiveSeriesTracker) {
i.replaceMatchersAndTrackers(asmodel.NewMatchers(newMatchersConfig), newCostAttributionActiveSeriesTracker, userDB, now)
}
idx := userDB.Head().MustIndex()
valid := userDB.activeSeries.Purge(now, idx)
idx.Close()
if !valid {
// Active series config has been reloaded, exposing loading metric until MetricsIdleTimeout passes.
i.metrics.activeSeriesLoading.WithLabelValues(userID).Set(1)
} else {
allActive, activeMatching, allActiveHistograms, activeMatchingHistograms, allActiveBuckets, activeMatchingBuckets := userDB.activeSeries.ActiveWithMatchers()
i.metrics.activeSeriesLoading.DeleteLabelValues(userID)
if allActive > 0 {
i.metrics.activeSeriesPerUser.WithLabelValues(userID).Set(float64(allActive))
} else {
i.metrics.activeSeriesPerUser.DeleteLabelValues(userID)
}
if allActiveHistograms > 0 {
i.metrics.activeSeriesPerUserNativeHistograms.WithLabelValues(userID).Set(float64(allActiveHistograms))
} else {
i.metrics.activeSeriesPerUserNativeHistograms.DeleteLabelValues(userID)
}
if allActiveBuckets > 0 {
i.metrics.activeNativeHistogramBucketsPerUser.WithLabelValues(userID).Set(float64(allActiveBuckets))
} else {
i.metrics.activeNativeHistogramBucketsPerUser.DeleteLabelValues(userID)
}
AttributedActiveSeriesFailure := userDB.activeSeries.ActiveSeriesAttributionFailureCount()
if AttributedActiveSeriesFailure > 0 {
i.metrics.attributedActiveSeriesFailuresPerUser.WithLabelValues(userID).Add(AttributedActiveSeriesFailure)
}
for idx, name := range userDB.activeSeries.CurrentMatcherNames() {
// We only set the metrics for matchers that actually exist, to avoid increasing cardinality with zero valued metrics.
if activeMatching[idx] > 0 {
i.metrics.activeSeriesCustomTrackersPerUser.WithLabelValues(userID, name).Set(float64(activeMatching[idx]))
} else {
i.metrics.activeSeriesCustomTrackersPerUser.DeleteLabelValues(userID, name)
}
if activeMatchingHistograms[idx] > 0 {
i.metrics.activeSeriesCustomTrackersPerUserNativeHistograms.WithLabelValues(userID, name).Set(float64(activeMatchingHistograms[idx]))
} else {
i.metrics.activeSeriesCustomTrackersPerUserNativeHistograms.DeleteLabelValues(userID, name)
}
if activeMatchingBuckets[idx] > 0 {
i.metrics.activeNativeHistogramBucketsCustomTrackersPerUser.WithLabelValues(userID, name).Set(float64(activeMatchingBuckets[idx]))
} else {
i.metrics.activeNativeHistogramBucketsCustomTrackersPerUser.DeleteLabelValues(userID, name)
}
}
}
}
}
// updateUsageStats updated some anonymous usage statistics tracked by the ingester.
// This function is expected to be called periodically.
func (i *Ingester) updateUsageStats() {
memoryUsersCount := int64(0)
memorySeriesCount := int64(0)
activeSeriesCount := int64(0)
tenantsWithOutOfOrderEnabledCount := int64(0)
minOutOfOrderTimeWindow := time.Duration(0)
maxOutOfOrderTimeWindow := time.Duration(0)
for _, userID := range i.getTSDBUsers() {
userDB := i.getTSDB(userID)
if userDB == nil {
continue
}
// Track only tenants with at least 1 series.
numSeries := userDB.Head().NumSeries()
if numSeries == 0 {
continue
}
memoryUsersCount++
memorySeriesCount += int64(numSeries)
activeSeries, _, _ := userDB.activeSeries.Active()
activeSeriesCount += int64(activeSeries)
oooWindow := i.limits.OutOfOrderTimeWindow(userID)
if oooWindow > 0 {
tenantsWithOutOfOrderEnabledCount++
if minOutOfOrderTimeWindow == 0 || oooWindow < minOutOfOrderTimeWindow {
minOutOfOrderTimeWindow = oooWindow
}
if oooWindow > maxOutOfOrderTimeWindow {
maxOutOfOrderTimeWindow = oooWindow
}
}
}
// Track anonymous usage stats.
memorySeriesStats.Set(memorySeriesCount)
activeSeriesStats.Set(activeSeriesCount)
memoryTenantsStats.Set(memoryUsersCount)
tenantsWithOutOfOrderEnabledStat.Set(tenantsWithOutOfOrderEnabledCount)
minOutOfOrderTimeWindowSecondsStat.Set(int64(minOutOfOrderTimeWindow.Seconds()))
maxOutOfOrderTimeWindowSecondsStat.Set(int64(maxOutOfOrderTimeWindow.Seconds()))
}
// applyTSDBSettings goes through all tenants and applies
// * The current max-exemplars setting. If it changed, tsdb will resize the buffer; if it didn't change tsdb will return quickly.
// * The current out-of-order time window. If it changes from 0 to >0, then a new Write-Behind-Log gets created for that tenant.
func (i *Ingester) applyTSDBSettings() {
for _, userID := range i.getTSDBUsers() {
oooTW := i.limits.OutOfOrderTimeWindow(userID)
if oooTW < 0 {
oooTW = 0
}
// We populate a Config struct with just TSDB related config, which is OK
// because DB.ApplyConfig only looks at the specified config.
// The other fields in Config are things like Rules, Scrape
// settings, which don't apply to Head.
cfg := promcfg.Config{
StorageConfig: promcfg.StorageConfig{
ExemplarsConfig: &promcfg.ExemplarsConfig{
MaxExemplars: int64(i.limiter.maxExemplarsPerUser(userID)),
},
TSDBConfig: &promcfg.TSDBConfig{
OutOfOrderTimeWindow: oooTW.Milliseconds(),
},
},
}
db := i.getTSDB(userID)
if db == nil {
continue
}
if err := db.db.ApplyConfig(&cfg); err != nil {
level.Error(i.logger).Log("msg", "failed to apply config to TSDB", "user", userID, "err", err)
}
if i.limits.NativeHistogramsIngestionEnabled(userID) {
// there is not much overhead involved, so don't keep previous state, just overwrite the current setting
db.db.EnableNativeHistograms()
} else {
db.db.DisableNativeHistograms()
}
if i.limits.OOONativeHistogramsIngestionEnabled(userID) {
db.db.EnableOOONativeHistograms()
} else {
db.db.DisableOOONativeHistograms()
}
}
}
func (i *Ingester) updateLimitMetrics() {
for _, userID := range i.getTSDBUsers() {
db := i.getTSDB(userID)
if db == nil {
continue
}
minLocalSeriesLimit := 0
if i.cfg.UseIngesterOwnedSeriesForLimits || i.cfg.UpdateIngesterOwnedSeries {
os := db.ownedSeriesState()
i.metrics.ownedSeriesPerUser.WithLabelValues(userID).Set(float64(os.ownedSeriesCount))
if i.cfg.UseIngesterOwnedSeriesForLimits {
minLocalSeriesLimit = os.localSeriesLimit
}
}
localLimit := i.limiter.maxSeriesPerUser(userID, minLocalSeriesLimit)
i.metrics.maxLocalSeriesPerUser.WithLabelValues(userID).Set(float64(localLimit))
}
}
// GetRef() is an extra method added to TSDB to let Mimir check before calling Add()
type extendedAppender interface {
storage.Appender
storage.GetRef
}
type pushStats struct {
succeededSamplesCount int
failedSamplesCount int
succeededExemplarsCount int
failedExemplarsCount int
sampleTimestampTooOldCount int
sampleOutOfOrderCount int
sampleTooOldCount int
sampleTooFarInFutureCount int
newValueForTimestampCount int
perUserSeriesLimitCount int
perMetricSeriesLimitCount int
invalidNativeHistogramCount int
}
type ctxKey int