-
Notifications
You must be signed in to change notification settings - Fork 548
/
Copy pathdistributor.go
2784 lines (2350 loc) · 102 KB
/
distributor.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/distributor/distributor.go
// Provenance-includes-license: Apache-2.0
// Provenance-includes-copyright: The Cortex Authors.
package distributor
import (
"context"
"flag"
"fmt"
"io"
"math"
"math/rand"
"net/http"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/grafana/dskit/concurrency"
"github.com/grafana/dskit/grpcutil"
"github.com/grafana/dskit/httpgrpc"
"github.com/grafana/dskit/instrument"
"github.com/grafana/dskit/kv"
"github.com/grafana/dskit/limiter"
"github.com/grafana/dskit/middleware"
"github.com/grafana/dskit/mtime"
"github.com/grafana/dskit/ring"
ring_client "github.com/grafana/dskit/ring/client"
"github.com/grafana/dskit/services"
"github.com/grafana/dskit/tenant"
"github.com/grafana/dskit/user"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/model/relabel"
"github.com/prometheus/prometheus/scrape"
"go.uber.org/atomic"
"golang.org/x/exp/slices"
"golang.org/x/sync/errgroup"
"github.com/grafana/mimir/pkg/cardinality"
ingester_client "github.com/grafana/mimir/pkg/ingester/client"
"github.com/grafana/mimir/pkg/mimirpb"
"github.com/grafana/mimir/pkg/querier/stats"
"github.com/grafana/mimir/pkg/storage/ingest"
"github.com/grafana/mimir/pkg/util"
"github.com/grafana/mimir/pkg/util/globalerror"
mimir_limiter "github.com/grafana/mimir/pkg/util/limiter"
util_math "github.com/grafana/mimir/pkg/util/math"
"github.com/grafana/mimir/pkg/util/pool"
"github.com/grafana/mimir/pkg/util/spanlogger"
"github.com/grafana/mimir/pkg/util/validation"
)
var (
// Validation errors.
errInvalidTenantShardSize = errors.New("invalid tenant shard size, the value must be greater than or equal to zero")
reasonDistributorMaxIngestionRate = globalerror.DistributorMaxIngestionRate.LabelValue()
reasonDistributorMaxInflightPushRequests = globalerror.DistributorMaxInflightPushRequests.LabelValue()
reasonDistributorMaxInflightPushRequestsBytes = globalerror.DistributorMaxInflightPushRequestsBytes.LabelValue()
)
const (
// distributorRingKey is the key under which we store the distributors ring in the KVStore.
distributorRingKey = "distributor"
// ringAutoForgetUnhealthyPeriods is how many consecutive timeout periods an unhealthy instance
// in the ring will be automatically removed after.
ringAutoForgetUnhealthyPeriods = 10
// metaLabelTenantID is the name of the metric_relabel_configs label with tenant ID.
metaLabelTenantID = model.MetaLabelPrefix + "tenant_id"
instanceIngestionRateTickInterval = time.Second
// Size of "slab" when using pooled buffers for marshaling write requests. When handling single Push request
// buffers for multiple write requests sent to ingesters will be allocated from single "slab", if there is enough space.
writeRequestSlabPoolSize = 512 * 1024
)
// Distributor forwards appends and queries to individual ingesters.
type Distributor struct {
services.Service
cfg Config
log log.Logger
ingestersRing ring.ReadRing
ingesterPool *ring_client.Pool
limits *validation.Overrides
// The global rate limiter requires a distributors ring to count
// the number of healthy instances
distributorsLifecycler *ring.BasicLifecycler
distributorsRing *ring.Ring
healthyInstancesCount *atomic.Uint32
// For handling HA replicas.
HATracker *haTracker
// Per-user rate limiters.
requestRateLimiter *limiter.RateLimiter
ingestionRateLimiter *limiter.RateLimiter
// Manager for subservices (HA Tracker, distributor ring and client pool)
subservices *services.Manager
subservicesWatcher *services.FailureWatcher
activeUsers *util.ActiveUsersCleanupService
activeGroups *util.ActiveGroupsCleanupService
ingestionRate *util_math.EwmaRate
inflightPushRequests atomic.Int64
inflightPushRequestsBytes atomic.Int64
// Metrics
queryDuration *instrument.HistogramCollector
receivedRequests *prometheus.CounterVec
receivedSamples *prometheus.CounterVec
receivedExemplars *prometheus.CounterVec
receivedMetadata *prometheus.CounterVec
incomingRequests *prometheus.CounterVec
incomingSamples *prometheus.CounterVec
incomingExemplars *prometheus.CounterVec
incomingMetadata *prometheus.CounterVec
nonHASamples *prometheus.CounterVec
dedupedSamples *prometheus.CounterVec
labelsHistogram prometheus.Histogram
sampleDelayHistogram prometheus.Histogram
latestSeenSampleTimestampPerUser *prometheus.GaugeVec
hashCollisionCount prometheus.Counter
// Metrics for data rejected for hitting per-tenant limits
discardedSamplesTooManyHaClusters *prometheus.CounterVec
discardedSamplesRateLimited *prometheus.CounterVec
discardedRequestsRateLimited *prometheus.CounterVec
discardedExemplarsRateLimited *prometheus.CounterVec
discardedMetadataRateLimited *prometheus.CounterVec
// Metrics for data rejected for hitting per-instance limits
rejectedRequests *prometheus.CounterVec
sampleValidationMetrics *sampleValidationMetrics
exemplarValidationMetrics *exemplarValidationMetrics
metadataValidationMetrics *metadataValidationMetrics
// Metrics to be passed to distributor push handlers
PushMetrics *PushMetrics
PushWithMiddlewares PushFunc
RequestBufferPool util.Pool
// Pool of []byte used when marshalling write requests.
writeRequestBytePool sync.Pool
// doBatchPushWorkers is the Go function passed to ring.DoBatchWithOptions.
// It can be nil, in which case a simple `go f()` will be used.
// See Config.ReusableIngesterPushWorkers on how to configure this.
doBatchPushWorkers func(func())
// ingestStorageWriter is the writer used when ingest storage is enabled.
ingestStorageWriter *ingest.Writer
// partitionsRing is the hash ring holding ingester partitions. It's used when ingest storage is enabled.
partitionsRing *ring.PartitionInstanceRing
}
// Config contains the configuration required to
// create a Distributor
type Config struct {
PoolConfig PoolConfig `yaml:"pool"`
RetryConfig RetryConfig `yaml:"retry_after_header"`
HATrackerConfig HATrackerConfig `yaml:"ha_tracker"`
MaxRecvMsgSize int `yaml:"max_recv_msg_size" category:"advanced"`
MaxRequestPoolBufferSize int `yaml:"max_request_pool_buffer_size" category:"experimental"`
RemoteTimeout time.Duration `yaml:"remote_timeout" category:"advanced"`
// Distributors ring
DistributorRing RingConfig `yaml:"ring"`
// for testing and for extending the ingester by adding calls to the client
IngesterClientFactory ring_client.PoolFactory `yaml:"-"`
// when true the distributor does not validate the label name, Mimir doesn't directly use
// this (and should never use it) but this feature is used by other projects built on top of it
SkipLabelNameValidation bool `yaml:"-"`
// This config is dynamically injected because it is defined in the querier config.
ShuffleShardingLookbackPeriod time.Duration `yaml:"-"`
StreamingChunksPerIngesterSeriesBufferSize uint64 `yaml:"-"`
MinimizeIngesterRequests bool `yaml:"-"`
MinimiseIngesterRequestsHedgingDelay time.Duration `yaml:"-"`
PreferAvailabilityZone string `yaml:"-"`
// IngestStorageConfig is dynamically injected because defined outside of distributor config.
IngestStorageConfig ingest.Config `yaml:"-"`
// Limits for distributor
DefaultLimits InstanceLimits `yaml:"instance_limits"`
InstanceLimitsFn func() *InstanceLimits `yaml:"-"`
// This allows downstream projects to wrap the distributor push function
// and access the deserialized write requests before/after they are pushed.
// These functions will only receive samples that don't get dropped by HA deduplication.
PushWrappers []PushWrapper `yaml:"-"`
WriteRequestsBufferPoolingEnabled bool `yaml:"write_requests_buffer_pooling_enabled" category:"experimental"`
LimitInflightRequestsUsingGrpcMethodLimiter bool `yaml:"limit_inflight_requests_using_grpc_method_limiter" category:"deprecated"` // TODO Remove the configuration option in Mimir 2.14, keeping the same behavior as if it's enabled
ReusableIngesterPushWorkers int `yaml:"reusable_ingester_push_workers" category:"advanced"`
}
// PushWrapper wraps around a push. It is similar to middleware.Interface.
type PushWrapper func(next PushFunc) PushFunc
// RegisterFlags adds the flags required to config this to the given FlagSet
func (cfg *Config) RegisterFlags(f *flag.FlagSet, logger log.Logger) {
cfg.PoolConfig.RegisterFlags(f)
cfg.HATrackerConfig.RegisterFlags(f)
cfg.DistributorRing.RegisterFlags(f, logger)
cfg.RetryConfig.RegisterFlags(f)
f.IntVar(&cfg.MaxRecvMsgSize, "distributor.max-recv-msg-size", 100<<20, "Max message size in bytes that the distributors will accept for incoming push requests to the remote write API. If exceeded, the request will be rejected.")
f.IntVar(&cfg.MaxRequestPoolBufferSize, "distributor.max-request-pool-buffer-size", 0, "Max size of the pooled buffers used for marshaling write requests. If 0, no max size is enforced.")
f.DurationVar(&cfg.RemoteTimeout, "distributor.remote-timeout", 2*time.Second, "Timeout for downstream ingesters.")
f.BoolVar(&cfg.WriteRequestsBufferPoolingEnabled, "distributor.write-requests-buffer-pooling-enabled", true, "Enable pooling of buffers used for marshaling write requests.")
f.BoolVar(&cfg.LimitInflightRequestsUsingGrpcMethodLimiter, "distributor.limit-inflight-requests-using-grpc-method-limiter", true, "When enabled, in-flight write requests limit is checked as soon as the gRPC request is received, before the request is decoded and parsed.")
f.IntVar(&cfg.ReusableIngesterPushWorkers, "distributor.reusable-ingester-push-workers", 2000, "Number of pre-allocated workers used to forward push requests to the ingesters. If 0, no workers will be used and a new goroutine will be spawned for each ingester push request. If not enough workers available, new goroutine will be spawned. (Note: this is a performance optimization, not a limiting feature.)")
cfg.DefaultLimits.RegisterFlags(f)
}
// Validate config and returns error on failure
func (cfg *Config) Validate(limits validation.Limits) error {
if limits.IngestionTenantShardSize < 0 {
return errInvalidTenantShardSize
}
if err := cfg.HATrackerConfig.Validate(); err != nil {
return err
}
return cfg.RetryConfig.Validate()
}
const (
instanceLimitsMetric = "cortex_distributor_instance_limits"
instanceLimitsMetricHelp = "Instance limits used by this distributor." // Must be same for all registrations.
limitLabel = "limit"
)
type PushMetrics struct {
otlpRequestCounter *prometheus.CounterVec
uncompressedBodySize *prometheus.HistogramVec
}
func newPushMetrics(reg prometheus.Registerer) *PushMetrics {
return &PushMetrics{
otlpRequestCounter: promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "cortex_distributor_otlp_requests_total",
Help: "The total number of OTLP requests that have come in to the distributor.",
}, []string{"user"}),
uncompressedBodySize: promauto.With(reg).NewHistogramVec(prometheus.HistogramOpts{
Name: "cortex_distributor_uncompressed_request_body_size_bytes",
Help: "Size of uncompressed request body in bytes.",
NativeHistogramBucketFactor: 1.1,
NativeHistogramMinResetDuration: 1 * time.Hour,
NativeHistogramMaxBucketNumber: 100,
}, []string{"user"}),
}
}
func (m *PushMetrics) IncOTLPRequest(user string) {
if m != nil {
m.otlpRequestCounter.WithLabelValues(user).Inc()
}
}
func (m *PushMetrics) ObserveUncompressedBodySize(user string, size float64) {
if m != nil {
m.uncompressedBodySize.WithLabelValues(user).Observe(size)
}
}
func (m *PushMetrics) deleteUserMetrics(user string) {
m.otlpRequestCounter.DeleteLabelValues(user)
m.uncompressedBodySize.DeleteLabelValues(user)
}
// New constructs a new Distributor
func New(cfg Config, clientConfig ingester_client.Config, limits *validation.Overrides, activeGroupsCleanupService *util.ActiveGroupsCleanupService, ingestersRing ring.ReadRing, partitionsRing *ring.PartitionInstanceRing, canJoinDistributorsRing bool, reg prometheus.Registerer, log log.Logger) (*Distributor, error) {
clientMetrics := ingester_client.NewMetrics(reg)
if cfg.IngesterClientFactory == nil {
cfg.IngesterClientFactory = ring_client.PoolInstFunc(func(inst ring.InstanceDesc) (ring_client.PoolClient, error) {
return ingester_client.MakeIngesterClient(inst, clientConfig, clientMetrics, log)
})
}
cfg.PoolConfig.RemoteTimeout = cfg.RemoteTimeout
haTracker, err := newHATracker(cfg.HATrackerConfig, limits, reg, log)
if err != nil {
return nil, err
}
subservices := []services.Service(nil)
subservices = append(subservices, haTracker)
var requestBufferPool util.Pool
if cfg.MaxRequestPoolBufferSize > 0 {
requestBufferPool = util.NewBucketedBufferPool(1<<10, cfg.MaxRequestPoolBufferSize, 4)
} else {
requestBufferPool = util.NewBufferPool()
}
d := &Distributor{
cfg: cfg,
log: log,
ingestersRing: ingestersRing,
RequestBufferPool: requestBufferPool,
partitionsRing: partitionsRing,
ingesterPool: NewPool(cfg.PoolConfig, ingestersRing, cfg.IngesterClientFactory, log),
healthyInstancesCount: atomic.NewUint32(0),
limits: limits,
HATracker: haTracker,
ingestionRate: util_math.NewEWMARate(0.2, instanceIngestionRateTickInterval),
queryDuration: instrument.NewHistogramCollector(promauto.With(reg).NewHistogramVec(prometheus.HistogramOpts{
Name: "cortex_distributor_query_duration_seconds",
Help: "Time spent executing expression and exemplar queries.",
Buckets: []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10, 20, 30},
}, []string{"method", "status_code"})),
receivedRequests: promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "cortex_distributor_received_requests_total",
Help: "The total number of received requests, excluding rejected and deduped requests.",
}, []string{"user"}),
receivedSamples: promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "cortex_distributor_received_samples_total",
Help: "The total number of received samples, excluding rejected and deduped samples.",
}, []string{"user"}),
receivedExemplars: promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "cortex_distributor_received_exemplars_total",
Help: "The total number of received exemplars, excluding rejected and deduped exemplars.",
}, []string{"user"}),
receivedMetadata: promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "cortex_distributor_received_metadata_total",
Help: "The total number of received metadata, excluding rejected.",
}, []string{"user"}),
incomingRequests: promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "cortex_distributor_requests_in_total",
Help: "The total number of requests that have come in to the distributor, including rejected or deduped requests.",
}, []string{"user"}),
incomingSamples: promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "cortex_distributor_samples_in_total",
Help: "The total number of samples that have come in to the distributor, including rejected or deduped samples.",
}, []string{"user"}),
incomingExemplars: promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "cortex_distributor_exemplars_in_total",
Help: "The total number of exemplars that have come in to the distributor, including rejected or deduped exemplars.",
}, []string{"user"}),
incomingMetadata: promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "cortex_distributor_metadata_in_total",
Help: "The total number of metadata the have come in to the distributor, including rejected.",
}, []string{"user"}),
nonHASamples: promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "cortex_distributor_non_ha_samples_received_total",
Help: "The total number of received samples for a user that has HA tracking turned on, but the sample didn't contain both HA labels.",
}, []string{"user"}),
dedupedSamples: promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "cortex_distributor_deduped_samples_total",
Help: "The total number of deduplicated samples.",
}, []string{"user", "cluster"}),
labelsHistogram: promauto.With(reg).NewHistogram(prometheus.HistogramOpts{
Name: "cortex_labels_per_sample",
Help: "Number of labels per sample.",
Buckets: []float64{5, 10, 15, 20, 25},
}),
sampleDelayHistogram: promauto.With(reg).NewHistogram(prometheus.HistogramOpts{
Name: "cortex_distributor_sample_delay_seconds",
Help: "Number of seconds by which a sample came in late wrt wallclock.",
Buckets: []float64{
-60 * 1, // 1 min early
-15, // 15s early
-5, // 5s early
30, // 30s
60 * 1, // 1 min
60 * 2, // 2 min
60 * 4, // 4 min
60 * 8, // 8 min
60 * 10, // 10 min
60 * 30, // 30 min
60 * 60, // 1h
60 * 60 * 2, // 2h
60 * 60 * 3, // 3h
60 * 60 * 6, // 6h
60 * 60 * 24, // 24h
},
}),
latestSeenSampleTimestampPerUser: promauto.With(reg).NewGaugeVec(prometheus.GaugeOpts{
Name: "cortex_distributor_latest_seen_sample_timestamp_seconds",
Help: "Unix timestamp of latest received sample per user.",
}, []string{"user"}),
discardedSamplesTooManyHaClusters: validation.DiscardedSamplesCounter(reg, reasonTooManyHAClusters),
discardedSamplesRateLimited: validation.DiscardedSamplesCounter(reg, reasonRateLimited),
discardedRequestsRateLimited: validation.DiscardedRequestsCounter(reg, reasonRateLimited),
discardedExemplarsRateLimited: validation.DiscardedExemplarsCounter(reg, reasonRateLimited),
discardedMetadataRateLimited: validation.DiscardedMetadataCounter(reg, reasonRateLimited),
rejectedRequests: promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "cortex_distributor_instance_rejected_requests_total",
Help: "Requests discarded for hitting per-instance limits",
}, []string{"reason"}),
sampleValidationMetrics: newSampleValidationMetrics(reg),
exemplarValidationMetrics: newExemplarValidationMetrics(reg),
metadataValidationMetrics: newMetadataValidationMetrics(reg),
hashCollisionCount: promauto.With(reg).NewCounter(prometheus.CounterOpts{
Name: "cortex_distributor_hash_collisions_total",
Help: "Number of times a hash collision was detected when de-duplicating samples.",
}),
PushMetrics: newPushMetrics(reg),
}
// Initialize expected rejected request labels
d.rejectedRequests.WithLabelValues(reasonDistributorMaxIngestionRate)
d.rejectedRequests.WithLabelValues(reasonDistributorMaxInflightPushRequests)
d.rejectedRequests.WithLabelValues(reasonDistributorMaxInflightPushRequestsBytes)
promauto.With(reg).NewGaugeFunc(prometheus.GaugeOpts{
Name: instanceLimitsMetric,
Help: instanceLimitsMetricHelp,
ConstLabels: map[string]string{limitLabel: "max_inflight_push_requests"},
}, func() float64 {
il := d.getInstanceLimits()
return float64(il.MaxInflightPushRequests)
})
promauto.With(reg).NewGaugeFunc(prometheus.GaugeOpts{
Name: instanceLimitsMetric,
Help: instanceLimitsMetricHelp,
ConstLabels: map[string]string{limitLabel: "max_inflight_push_requests_bytes"},
}, func() float64 {
il := d.getInstanceLimits()
return float64(il.MaxInflightPushRequestsBytes)
})
promauto.With(reg).NewGaugeFunc(prometheus.GaugeOpts{
Name: instanceLimitsMetric,
Help: instanceLimitsMetricHelp,
ConstLabels: map[string]string{limitLabel: "max_ingestion_rate"},
}, func() float64 {
il := d.getInstanceLimits()
return il.MaxIngestionRate
})
promauto.With(reg).NewGaugeFunc(prometheus.GaugeOpts{
Name: "cortex_distributor_inflight_push_requests",
Help: "Current number of inflight push requests in distributor.",
}, func() float64 {
return float64(d.inflightPushRequests.Load())
})
promauto.With(reg).NewGaugeFunc(prometheus.GaugeOpts{
Name: "cortex_distributor_inflight_push_requests_bytes",
Help: "Current sum of inflight push requests in distributor in bytes.",
}, func() float64 {
return float64(d.inflightPushRequestsBytes.Load())
})
promauto.With(reg).NewGaugeFunc(prometheus.GaugeOpts{
Name: "cortex_distributor_ingestion_rate_samples_per_second",
Help: "Current ingestion rate in samples/sec that distributor is using to limit access.",
}, func() float64 {
return d.ingestionRate.Rate()
})
// Create the configured ingestion rate limit strategy (local or global). In case
// it's an internal dependency and we can't join the distributors ring, we skip rate
// limiting.
var ingestionRateStrategy, requestRateStrategy limiter.RateLimiterStrategy
var distributorsLifecycler *ring.BasicLifecycler
var distributorsRing *ring.Ring
if !canJoinDistributorsRing {
requestRateStrategy = newInfiniteRateStrategy()
ingestionRateStrategy = newInfiniteRateStrategy()
} else {
distributorsRing, distributorsLifecycler, err = newRingAndLifecycler(cfg.DistributorRing, d.healthyInstancesCount, log, reg)
if err != nil {
return nil, err
}
subservices = append(subservices, distributorsLifecycler, distributorsRing)
requestRateStrategy = newGlobalRateStrategy(newRequestRateStrategy(limits), d)
ingestionRateStrategy = newGlobalRateStrategyWithBurstFactor(limits, d)
}
d.requestRateLimiter = limiter.NewRateLimiter(requestRateStrategy, 10*time.Second)
d.ingestionRateLimiter = limiter.NewRateLimiter(ingestionRateStrategy, 10*time.Second)
d.distributorsLifecycler = distributorsLifecycler
d.distributorsRing = distributorsRing
d.activeUsers = util.NewActiveUsersCleanupWithDefaultValues(d.cleanupInactiveUser)
d.activeGroups = activeGroupsCleanupService
d.PushWithMiddlewares = d.wrapPushWithMiddlewares(d.push)
subservices = append(subservices, d.ingesterPool, d.activeUsers)
if cfg.ReusableIngesterPushWorkers > 0 {
wp := concurrency.NewReusableGoroutinesPool(cfg.ReusableIngesterPushWorkers)
d.doBatchPushWorkers = wp.Go
// Closing the pool doesn't stop the workload it's running, we're doing this just to avoid leaking goroutines in tests.
subservices = append(subservices, services.NewBasicService(
nil,
func(ctx context.Context) error { <-ctx.Done(); return nil },
func(_ error) error { wp.Close(); return nil },
))
}
if cfg.IngestStorageConfig.Enabled {
d.ingestStorageWriter = ingest.NewWriter(d.cfg.IngestStorageConfig.KafkaConfig, log, reg)
subservices = append(subservices, d.ingestStorageWriter)
}
// Register each metric only if the corresponding storage is enabled.
// Some queries in the mixin use the presence of these metrics as indication whether Mimir is running with ingest storage or not.
exportStorageModeMetrics(reg, cfg.IngestStorageConfig.Migration.DistributorSendToIngestersEnabled || !cfg.IngestStorageConfig.Enabled, cfg.IngestStorageConfig.Enabled, ingestersRing.ReplicationFactor())
d.subservices, err = services.NewManager(subservices...)
if err != nil {
return nil, err
}
d.subservicesWatcher = services.NewFailureWatcher()
d.subservicesWatcher.WatchManager(d.subservices)
d.Service = services.NewBasicService(d.starting, d.running, d.stopping)
return d, nil
}
func exportStorageModeMetrics(reg prometheus.Registerer, classicStorageEnabled, ingestStorageEnabled bool, classicStorageReplicationFactor int) {
ingestStorageEnabledVal := float64(0)
if ingestStorageEnabled {
ingestStorageEnabledVal = 1
}
promauto.With(reg).NewGauge(prometheus.GaugeOpts{
Name: "cortex_distributor_ingest_storage_enabled",
Help: "Whether writes are being processed via ingest storage. Equal to 1 if ingest storage is enabled, 0 if disabled.",
}).Set(ingestStorageEnabledVal)
if classicStorageEnabled {
promauto.With(reg).NewGauge(prometheus.GaugeOpts{
Name: "cortex_distributor_replication_factor",
Help: "The configured replication factor.",
}).Set(float64(classicStorageReplicationFactor))
}
}
// newRingAndLifecycler creates a new distributor ring and lifecycler with all required lifecycler delegates
func newRingAndLifecycler(cfg RingConfig, instanceCount *atomic.Uint32, logger log.Logger, reg prometheus.Registerer) (*ring.Ring, *ring.BasicLifecycler, error) {
reg = prometheus.WrapRegistererWithPrefix("cortex_", reg)
kvStore, err := kv.NewClient(cfg.Common.KVStore, ring.GetCodec(), kv.RegistererWithKVName(reg, "distributor-lifecycler"), logger)
if err != nil {
return nil, nil, errors.Wrap(err, "failed to initialize distributors' KV store")
}
lifecyclerCfg, err := cfg.ToBasicLifecyclerConfig(logger)
if err != nil {
return nil, nil, errors.Wrap(err, "failed to build distributors' lifecycler config")
}
var delegate ring.BasicLifecyclerDelegate
delegate = ring.NewInstanceRegisterDelegate(ring.ACTIVE, lifecyclerCfg.NumTokens)
delegate = newHealthyInstanceDelegate(instanceCount, cfg.Common.HeartbeatTimeout, delegate)
delegate = ring.NewLeaveOnStoppingDelegate(delegate, logger)
delegate = ring.NewAutoForgetDelegate(ringAutoForgetUnhealthyPeriods*cfg.Common.HeartbeatTimeout, delegate, logger)
distributorsLifecycler, err := ring.NewBasicLifecycler(lifecyclerCfg, "distributor", distributorRingKey, kvStore, delegate, logger, reg)
if err != nil {
return nil, nil, errors.Wrap(err, "failed to initialize distributors' lifecycler")
}
distributorsRing, err := ring.New(cfg.toRingConfig(), "distributor", distributorRingKey, logger, reg)
if err != nil {
return nil, nil, errors.Wrap(err, "failed to initialize distributors' ring client")
}
return distributorsRing, distributorsLifecycler, nil
}
func (d *Distributor) starting(ctx context.Context) error {
if err := services.StartManagerAndAwaitHealthy(ctx, d.subservices); err != nil {
return errors.Wrap(err, "unable to start distributor subservices")
}
// Distributors get embedded in rulers and queriers to talk to ingesters on the query path. In that
// case they won't have a distributor lifecycler or ring so don't try to join the distributor ring.
if d.distributorsLifecycler != nil && d.distributorsRing != nil {
level.Info(d.log).Log("msg", "waiting until distributor is ACTIVE in the ring")
if err := ring.WaitInstanceState(ctx, d.distributorsRing, d.distributorsLifecycler.GetInstanceID(), ring.ACTIVE); err != nil {
return err
}
}
return nil
}
func (d *Distributor) running(ctx context.Context) error {
ingestionRateTicker := time.NewTicker(instanceIngestionRateTickInterval)
defer ingestionRateTicker.Stop()
for {
select {
case <-ctx.Done():
return nil
case <-ingestionRateTicker.C:
d.ingestionRate.Tick()
case err := <-d.subservicesWatcher.Chan():
return errors.Wrap(err, "distributor subservice failed")
}
}
}
func (d *Distributor) cleanupInactiveUser(userID string) {
d.ingestersRing.CleanupShuffleShardCache(userID)
d.HATracker.cleanupHATrackerMetricsForUser(userID)
d.receivedRequests.DeleteLabelValues(userID)
d.receivedSamples.DeleteLabelValues(userID)
d.receivedExemplars.DeleteLabelValues(userID)
d.receivedMetadata.DeleteLabelValues(userID)
d.incomingRequests.DeleteLabelValues(userID)
d.incomingSamples.DeleteLabelValues(userID)
d.incomingExemplars.DeleteLabelValues(userID)
d.incomingMetadata.DeleteLabelValues(userID)
d.nonHASamples.DeleteLabelValues(userID)
d.latestSeenSampleTimestampPerUser.DeleteLabelValues(userID)
d.PushMetrics.deleteUserMetrics(userID)
filter := prometheus.Labels{"user": userID}
d.dedupedSamples.DeletePartialMatch(filter)
d.discardedSamplesTooManyHaClusters.DeletePartialMatch(filter)
d.discardedSamplesRateLimited.DeletePartialMatch(filter)
d.discardedRequestsRateLimited.DeleteLabelValues(userID)
d.discardedExemplarsRateLimited.DeleteLabelValues(userID)
d.discardedMetadataRateLimited.DeleteLabelValues(userID)
d.sampleValidationMetrics.deleteUserMetrics(userID)
d.exemplarValidationMetrics.deleteUserMetrics(userID)
d.metadataValidationMetrics.deleteUserMetrics(userID)
}
func (d *Distributor) RemoveGroupMetricsForUser(userID, group string) {
d.dedupedSamples.DeleteLabelValues(userID, group)
d.discardedSamplesTooManyHaClusters.DeleteLabelValues(userID, group)
d.discardedSamplesRateLimited.DeleteLabelValues(userID, group)
d.sampleValidationMetrics.deleteUserMetricsForGroup(userID, group)
}
// Called after distributor is asked to stop via StopAsync.
func (d *Distributor) stopping(_ error) error {
return services.StopManagerAndAwaitStopped(context.Background(), d.subservices)
}
// Returns a boolean that indicates whether or not we want to remove the replica label going forward,
// and an error that indicates whether we want to accept samples based on the cluster/replica found in ts.
// nil for the error means accept the sample.
func (d *Distributor) checkSample(ctx context.Context, userID, cluster, replica string) (removeReplicaLabel bool, _ error) {
// If the sample doesn't have either HA label, accept it.
// At the moment we want to accept these samples by default.
if cluster == "" || replica == "" {
return false, nil
}
// If replica label is too long, don't use it. We accept the sample here, but it will fail validation later anyway.
if len(replica) > d.limits.MaxLabelValueLength(userID) {
return false, nil
}
// At this point we know we have both HA labels, we should lookup
// the cluster/instance here to see if we want to accept this sample.
err := d.HATracker.checkReplica(ctx, userID, cluster, replica, time.Now())
// checkReplica would have returned an error if there was a real error talking to Consul,
// or if the replica is not the currently elected replica.
if err != nil { // Don't accept the sample.
return false, err
}
return true, nil
}
// Validates a single series from a write request.
// May alter timeseries data in-place.
// The returned error may retain the series labels.
// It uses the passed nowt time to observe the delay of sample timestamps.
func (d *Distributor) validateSeries(nowt time.Time, ts *mimirpb.PreallocTimeseries, userID, group string, skipLabelNameValidation bool, minExemplarTS, maxExemplarTS int64) error {
if err := validateLabels(d.sampleValidationMetrics, d.limits, userID, group, ts.Labels, skipLabelNameValidation); err != nil {
return err
}
now := model.TimeFromUnixNano(nowt.UnixNano())
for _, s := range ts.Samples {
delta := now - model.Time(s.TimestampMs)
d.sampleDelayHistogram.Observe(float64(delta) / 1000)
if err := validateSample(d.sampleValidationMetrics, now, d.limits, userID, group, ts.Labels, s); err != nil {
return err
}
}
histogramsUpdated := false
for i, h := range ts.Histograms {
delta := now - model.Time(h.Timestamp)
d.sampleDelayHistogram.Observe(float64(delta) / 1000)
updated, err := validateSampleHistogram(d.sampleValidationMetrics, now, d.limits, userID, group, ts.Labels, &ts.Histograms[i])
if err != nil {
return err
}
histogramsUpdated = histogramsUpdated || updated
}
if histogramsUpdated {
ts.HistogramsUpdated()
}
if d.limits.MaxGlobalExemplarsPerUser(userID) == 0 {
ts.ClearExemplars()
return nil
}
allowedExemplars := d.limits.MaxExemplarsPerSeriesPerRequest(userID)
if allowedExemplars > 0 && len(ts.Exemplars) > allowedExemplars {
d.exemplarValidationMetrics.tooManyExemplars.WithLabelValues(userID).Add(float64(len(ts.Exemplars) - allowedExemplars))
ts.ResizeExemplars(allowedExemplars)
}
var previousExemplarTS int64 = math.MinInt64
isInOrder := true
for i := 0; i < len(ts.Exemplars); {
e := ts.Exemplars[i]
if err := validateExemplar(d.exemplarValidationMetrics, userID, ts.Labels, e); err != nil {
// An exemplar validation error prevents ingesting samples
// in the same series object. However because the current Prometheus
// remote write implementation only populates one or the other,
// there never will be any.
return err
}
if !validateExemplarTimestamp(d.exemplarValidationMetrics, userID, minExemplarTS, maxExemplarTS, e) {
ts.DeleteExemplarByMovingLast(i)
// Don't increase index i. After moving last exemplar to this index, we want to check it again.
continue
}
// We want to check if exemplars are in order. If they are not, we will sort them and invalidate the cache.
if isInOrder && previousExemplarTS > ts.Exemplars[i].TimestampMs {
isInOrder = false
}
previousExemplarTS = ts.Exemplars[i].TimestampMs
i++
}
if !isInOrder {
ts.SortExemplars()
}
return nil
}
// wrapPushWithMiddlewares returns push function wrapped in all Distributor's middlewares.
// push wrappers will be applied to incoming requests in the order in which they are in the slice in the config struct.
func (d *Distributor) wrapPushWithMiddlewares(next PushFunc) PushFunc {
var middlewares []PushWrapper
// The middlewares will be applied to the request (!) in the specified order, from first to last.
// To guarantee that, middleware functions will be called in reversed order, wrapping the
// result from previous call.
middlewares = append(middlewares, d.limitsMiddleware) // should run first because it checks limits before other middlewares need to read the request body
middlewares = append(middlewares, d.metricsMiddleware)
middlewares = append(middlewares, d.prePushHaDedupeMiddleware)
middlewares = append(middlewares, d.prePushRelabelMiddleware)
middlewares = append(middlewares, d.prePushSortAndFilterMiddleware)
middlewares = append(middlewares, d.prePushValidationMiddleware)
middlewares = append(middlewares, d.cfg.PushWrappers...)
for ix := len(middlewares) - 1; ix >= 0; ix-- {
next = middlewares[ix](next)
}
return next
}
func (d *Distributor) prePushHaDedupeMiddleware(next PushFunc) PushFunc {
return func(ctx context.Context, pushReq *Request) error {
next, maybeCleanup := NextOrCleanup(next, pushReq)
defer maybeCleanup()
req, err := pushReq.WriteRequest()
if err != nil {
return err
}
userID, err := tenant.TenantID(ctx)
if err != nil {
return err
}
if len(req.Timeseries) == 0 || !d.limits.AcceptHASamples(userID) {
return next(ctx, pushReq)
}
haReplicaLabel := d.limits.HAReplicaLabel(userID)
cluster, replica := findHALabels(haReplicaLabel, d.limits.HAClusterLabel(userID), req.Timeseries[0].Labels)
// Make a copy of these, since they may be retained as labels on our metrics, e.g. dedupedSamples.
cluster, replica = strings.Clone(cluster), strings.Clone(replica)
span := opentracing.SpanFromContext(ctx)
if span != nil {
span.SetTag("cluster", cluster)
span.SetTag("replica", replica)
}
numSamples := 0
group := d.activeGroups.UpdateActiveGroupTimestamp(userID, validation.GroupLabel(d.limits, userID, req.Timeseries), time.Now())
for _, ts := range req.Timeseries {
numSamples += len(ts.Samples) + len(ts.Histograms)
}
removeReplica, err := d.checkSample(ctx, userID, cluster, replica)
if err != nil {
if errors.As(err, &replicasDidNotMatchError{}) {
// These samples have been deduped.
d.dedupedSamples.WithLabelValues(userID, cluster).Add(float64(numSamples))
}
if errors.As(err, &tooManyClustersError{}) {
d.discardedSamplesTooManyHaClusters.WithLabelValues(userID, group).Add(float64(numSamples))
}
return err
}
if removeReplica {
// If we found both the cluster and replica labels, we only want to include the cluster label when
// storing series in Mimir. If we kept the replica label we would end up with another series for the same
// series we're trying to dedupe when HA tracking moves over to a different replica.
for ix := range req.Timeseries {
req.Timeseries[ix].RemoveLabel(haReplicaLabel)
}
} else {
// If there wasn't an error but removeReplica is false that means we didn't find both HA labels.
d.nonHASamples.WithLabelValues(userID).Add(float64(numSamples))
}
return next(ctx, pushReq)
}
}
func (d *Distributor) prePushRelabelMiddleware(next PushFunc) PushFunc {
return func(ctx context.Context, pushReq *Request) error {
next, maybeCleanup := NextOrCleanup(next, pushReq)
defer maybeCleanup()
userID, err := tenant.TenantID(ctx)
if err != nil {
return err
}
if !d.limits.MetricRelabelingEnabled(userID) {
return next(ctx, pushReq)
}
req, err := pushReq.WriteRequest()
if err != nil {
return err
}
var removeTsIndexes []int
lb := labels.NewBuilder(labels.EmptyLabels())
for tsIdx := 0; tsIdx < len(req.Timeseries); tsIdx++ {
ts := req.Timeseries[tsIdx]
if mrc := d.limits.MetricRelabelConfigs(userID); len(mrc) > 0 {
mimirpb.FromLabelAdaptersToBuilder(ts.Labels, lb)
lb.Set(metaLabelTenantID, userID)
keep := relabel.ProcessBuilder(lb, mrc...)
if !keep {
removeTsIndexes = append(removeTsIndexes, tsIdx)
continue
}
lb.Del(metaLabelTenantID)
req.Timeseries[tsIdx].SetLabels(mimirpb.FromBuilderToLabelAdapters(lb, ts.Labels))
}
for _, labelName := range d.limits.DropLabels(userID) {
req.Timeseries[tsIdx].RemoveLabel(labelName)
}
if len(ts.Labels) == 0 {
removeTsIndexes = append(removeTsIndexes, tsIdx)
continue
}
}
if len(removeTsIndexes) > 0 {
for _, removeTsIndex := range removeTsIndexes {
mimirpb.ReusePreallocTimeseries(&req.Timeseries[removeTsIndex])
}
req.Timeseries = util.RemoveSliceIndexes(req.Timeseries, removeTsIndexes)
}
return next(ctx, pushReq)
}
}
// prePushSortAndFilterMiddleware is responsible for sorting labels and
// filtering empty values. This is a protection mechanism for ingesters.
func (d *Distributor) prePushSortAndFilterMiddleware(next PushFunc) PushFunc {
return func(ctx context.Context, pushReq *Request) error {
next, maybeCleanup := NextOrCleanup(next, pushReq)
defer maybeCleanup()
req, err := pushReq.WriteRequest()
if err != nil {
return err
}
var removeTsIndexes []int
for tsIdx := 0; tsIdx < len(req.Timeseries); tsIdx++ {
ts := req.Timeseries[tsIdx]
// Prometheus strips empty values before storing; drop them now, before sharding to ingesters.
req.Timeseries[tsIdx].RemoveEmptyLabelValues()
if len(ts.Labels) == 0 {
removeTsIndexes = append(removeTsIndexes, tsIdx)
continue
}
// We rely on sorted labels in different places:
// 1) When computing token for labels. Here different order of
// labels returns different tokens, which is bad.
// 2) In validation code, when checking for duplicate label names.
// As duplicate label names are rejected later in the validation
// phase, we ignore them here.
// 3) Ingesters expect labels to be sorted in the Push request.
req.Timeseries[tsIdx].SortLabelsIfNeeded()
}
if len(removeTsIndexes) > 0 {
for _, removeTsIndex := range removeTsIndexes {
mimirpb.ReusePreallocTimeseries(&req.Timeseries[removeTsIndex])
}
req.Timeseries = util.RemoveSliceIndexes(req.Timeseries, removeTsIndexes)
}
return next(ctx, pushReq)
}
}
func (d *Distributor) prePushValidationMiddleware(next PushFunc) PushFunc {
return func(ctx context.Context, pushReq *Request) error {
next, maybeCleanup := NextOrCleanup(next, pushReq)
defer maybeCleanup()
req, err := pushReq.WriteRequest()
if err != nil {
return err
}
userID, err := tenant.TenantID(ctx)
if err != nil {
return err
}
now := mtime.Now()
d.receivedRequests.WithLabelValues(userID).Add(1)
d.activeUsers.UpdateUserTimestamp(userID, now)
group := d.activeGroups.UpdateActiveGroupTimestamp(userID, validation.GroupLabel(d.limits, userID, req.Timeseries), now)
// A WriteRequest can only contain series or metadata but not both. This might change in the future.
validatedMetadata := 0
validatedSamples := 0
validatedExemplars := 0
// Find the earliest and latest samples in the batch.
earliestSampleTimestampMs, latestSampleTimestampMs := int64(math.MaxInt64), int64(0)
for _, ts := range req.Timeseries {
for _, s := range ts.Samples {