-
Notifications
You must be signed in to change notification settings - Fork 810
/
Copy pathdistributor_test.go
4259 lines (3815 loc) · 144 KB
/
distributor_test.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 distributor
import (
"context"
"fmt"
"io"
"math"
"math/rand"
"net/http"
"sort"
"strconv"
"strings"
"sync"
"testing"
"time"
"google.golang.org/grpc/codes"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/model/relabel"
"github.com/prometheus/prometheus/tsdb/chunkenc"
"github.com/prometheus/prometheus/tsdb/tsdbutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
storecache "github.com/thanos-io/thanos/pkg/store/cache"
"github.com/weaveworks/common/httpgrpc"
"github.com/weaveworks/common/user"
"go.uber.org/atomic"
"google.golang.org/grpc"
"google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/status"
promchunk "github.com/cortexproject/cortex/pkg/chunk/encoding"
"github.com/cortexproject/cortex/pkg/cortexpb"
"github.com/cortexproject/cortex/pkg/ha"
"github.com/cortexproject/cortex/pkg/ingester"
"github.com/cortexproject/cortex/pkg/ingester/client"
"github.com/cortexproject/cortex/pkg/ring"
ring_client "github.com/cortexproject/cortex/pkg/ring/client"
"github.com/cortexproject/cortex/pkg/ring/kv"
"github.com/cortexproject/cortex/pkg/ring/kv/consul"
"github.com/cortexproject/cortex/pkg/tenant"
"github.com/cortexproject/cortex/pkg/util"
"github.com/cortexproject/cortex/pkg/util/chunkcompat"
"github.com/cortexproject/cortex/pkg/util/flagext"
"github.com/cortexproject/cortex/pkg/util/limiter"
"github.com/cortexproject/cortex/pkg/util/services"
"github.com/cortexproject/cortex/pkg/util/test"
"github.com/cortexproject/cortex/pkg/util/validation"
)
var (
errFail = httpgrpc.Errorf(http.StatusInternalServerError, "Fail")
emptyResponse = &cortexpb.WriteResponse{}
)
var (
randomStrings = []string{}
)
func init() {
randomStrings = util.GenerateRandomStrings()
}
func TestConfig_Validate(t *testing.T) {
t.Parallel()
tests := map[string]struct {
initConfig func(*Config)
initLimits func(*validation.Limits)
expected error
}{
"default config should pass": {
initConfig: func(_ *Config) {},
initLimits: func(_ *validation.Limits) {},
expected: nil,
},
"should fail on invalid sharding strategy": {
initConfig: func(cfg *Config) {
cfg.ShardingStrategy = "xxx"
},
initLimits: func(_ *validation.Limits) {},
expected: errInvalidShardingStrategy,
},
"should pass sharding strategy when IngestionTenantShardSize = 0": {
initConfig: func(cfg *Config) {
cfg.ShardingStrategy = "shuffle-sharding"
},
initLimits: func(limits *validation.Limits) {
limits.IngestionTenantShardSize = 0
},
expected: nil,
},
"should pass if the default shard size > 0 on when sharding strategy = shuffle-sharding": {
initConfig: func(cfg *Config) {
cfg.ShardingStrategy = "shuffle-sharding"
},
initLimits: func(limits *validation.Limits) {
limits.IngestionTenantShardSize = 3
},
expected: nil,
},
"should fail because the ingestionTenantShardSize is a non-positive number": {
initConfig: func(cfg *Config) {
cfg.ShardingStrategy = "shuffle-sharding"
},
initLimits: func(limits *validation.Limits) {
limits.IngestionTenantShardSize = -1
},
expected: errInvalidTenantShardSize,
},
}
for testName, testData := range tests {
testData := testData // Needed for t.Parallel to work correctly
t.Run(testName, func(t *testing.T) {
t.Parallel()
cfg := Config{}
limits := validation.Limits{}
flagext.DefaultValues(&cfg, &limits)
testData.initConfig(&cfg)
testData.initLimits(&limits)
assert.Equal(t, testData.expected, cfg.Validate(limits))
})
}
}
func TestDistributor_Push(t *testing.T) {
t.Parallel()
// Metrics to assert on.
lastSeenTimestamp := "cortex_distributor_latest_seen_sample_timestamp_seconds"
distributorAppend := "cortex_distributor_ingester_appends_total"
distributorAppendFailure := "cortex_distributor_ingester_append_failures_total"
distributorReceivedSamples := "cortex_distributor_received_samples_total"
ctx := user.InjectOrgID(context.Background(), "userDistributorPush")
type samplesIn struct {
num int
startTimestampMs int64
}
for name, tc := range map[string]struct {
metricNames []string
numIngesters int
happyIngesters int
samples samplesIn
histogramSamples bool
metadata int
expectedResponse *cortexpb.WriteResponse
expectedError error
expectedMetrics string
ingesterError error
}{
"A push of no samples shouldn't block or return error, even if ingesters are sad": {
numIngesters: 3,
happyIngesters: 0,
expectedResponse: emptyResponse,
},
"A push to 3 happy ingesters should succeed": {
numIngesters: 3,
happyIngesters: 3,
samples: samplesIn{num: 5, startTimestampMs: 123456789000},
metadata: 5,
expectedResponse: emptyResponse,
metricNames: []string{lastSeenTimestamp},
expectedMetrics: `
# HELP cortex_distributor_latest_seen_sample_timestamp_seconds Unix timestamp of latest received sample per user.
# TYPE cortex_distributor_latest_seen_sample_timestamp_seconds gauge
cortex_distributor_latest_seen_sample_timestamp_seconds{user="userDistributorPush"} 123456789.004
`,
},
"A push to 2 happy ingesters should succeed": {
numIngesters: 3,
happyIngesters: 2,
samples: samplesIn{num: 5, startTimestampMs: 123456789000},
metadata: 5,
expectedResponse: emptyResponse,
metricNames: []string{lastSeenTimestamp},
expectedMetrics: `
# HELP cortex_distributor_latest_seen_sample_timestamp_seconds Unix timestamp of latest received sample per user.
# TYPE cortex_distributor_latest_seen_sample_timestamp_seconds gauge
cortex_distributor_latest_seen_sample_timestamp_seconds{user="userDistributorPush"} 123456789.004
`,
},
"A push to 1 happy ingesters should fail": {
numIngesters: 3,
happyIngesters: 1,
samples: samplesIn{num: 10, startTimestampMs: 123456789000},
expectedError: errFail,
metricNames: []string{lastSeenTimestamp},
expectedMetrics: `
# HELP cortex_distributor_latest_seen_sample_timestamp_seconds Unix timestamp of latest received sample per user.
# TYPE cortex_distributor_latest_seen_sample_timestamp_seconds gauge
cortex_distributor_latest_seen_sample_timestamp_seconds{user="userDistributorPush"} 123456789.009
`,
},
"A push to 0 happy ingesters should fail": {
numIngesters: 3,
happyIngesters: 0,
samples: samplesIn{num: 10, startTimestampMs: 123456789000},
expectedError: errFail,
metricNames: []string{lastSeenTimestamp},
expectedMetrics: `
# HELP cortex_distributor_latest_seen_sample_timestamp_seconds Unix timestamp of latest received sample per user.
# TYPE cortex_distributor_latest_seen_sample_timestamp_seconds gauge
cortex_distributor_latest_seen_sample_timestamp_seconds{user="userDistributorPush"} 123456789.009
`,
},
"A push exceeding burst size should fail": {
numIngesters: 3,
happyIngesters: 3,
samples: samplesIn{num: 25, startTimestampMs: 123456789000},
metadata: 5,
expectedError: httpgrpc.Errorf(http.StatusTooManyRequests, "ingestion rate limit (20) exceeded while adding 25 samples and 5 metadata"),
metricNames: []string{lastSeenTimestamp},
expectedMetrics: `
# HELP cortex_distributor_latest_seen_sample_timestamp_seconds Unix timestamp of latest received sample per user.
# TYPE cortex_distributor_latest_seen_sample_timestamp_seconds gauge
cortex_distributor_latest_seen_sample_timestamp_seconds{user="userDistributorPush"} 123456789.024
`,
},
"A push to ingesters should report the correct metrics with no metadata": {
numIngesters: 3,
happyIngesters: 2,
samples: samplesIn{num: 1, startTimestampMs: 123456789000},
metadata: 0,
metricNames: []string{distributorAppend, distributorAppendFailure},
expectedResponse: emptyResponse,
expectedMetrics: `
# HELP cortex_distributor_ingester_append_failures_total The total number of failed batch appends sent to ingesters.
# TYPE cortex_distributor_ingester_append_failures_total counter
cortex_distributor_ingester_append_failures_total{ingester="ingester-2",status="5xx",type="samples"} 1
# HELP cortex_distributor_ingester_appends_total The total number of batch appends sent to ingesters.
# TYPE cortex_distributor_ingester_appends_total counter
cortex_distributor_ingester_appends_total{ingester="ingester-0",type="samples"} 1
cortex_distributor_ingester_appends_total{ingester="ingester-1",type="samples"} 1
cortex_distributor_ingester_appends_total{ingester="ingester-2",type="samples"} 1
`,
},
"A push to ingesters should report the correct metrics with no samples": {
numIngesters: 3,
happyIngesters: 2,
samples: samplesIn{num: 0, startTimestampMs: 123456789000},
metadata: 1,
metricNames: []string{distributorAppend, distributorAppendFailure},
expectedResponse: emptyResponse,
ingesterError: httpgrpc.Errorf(http.StatusInternalServerError, "Fail"),
expectedMetrics: `
# HELP cortex_distributor_ingester_append_failures_total The total number of failed batch appends sent to ingesters.
# TYPE cortex_distributor_ingester_append_failures_total counter
cortex_distributor_ingester_append_failures_total{ingester="ingester-2",status="5xx",type="metadata"} 1
# HELP cortex_distributor_ingester_appends_total The total number of batch appends sent to ingesters.
# TYPE cortex_distributor_ingester_appends_total counter
cortex_distributor_ingester_appends_total{ingester="ingester-0",type="metadata"} 1
cortex_distributor_ingester_appends_total{ingester="ingester-1",type="metadata"} 1
cortex_distributor_ingester_appends_total{ingester="ingester-2",type="metadata"} 1
`,
},
"A push to overloaded ingesters should report the correct metrics": {
numIngesters: 3,
happyIngesters: 2,
samples: samplesIn{num: 0, startTimestampMs: 123456789000},
metadata: 1,
metricNames: []string{distributorAppend, distributorAppendFailure},
expectedResponse: emptyResponse,
ingesterError: httpgrpc.Errorf(http.StatusTooManyRequests, "Fail"),
expectedMetrics: `
# HELP cortex_distributor_ingester_appends_total The total number of batch appends sent to ingesters.
# TYPE cortex_distributor_ingester_appends_total counter
cortex_distributor_ingester_appends_total{ingester="ingester-0",type="metadata"} 1
cortex_distributor_ingester_appends_total{ingester="ingester-1",type="metadata"} 1
cortex_distributor_ingester_appends_total{ingester="ingester-2",type="metadata"} 1
# HELP cortex_distributor_ingester_append_failures_total The total number of failed batch appends sent to ingesters.
# TYPE cortex_distributor_ingester_append_failures_total counter
cortex_distributor_ingester_append_failures_total{ingester="ingester-2",status="4xx",type="metadata"} 1
`,
},
"A push to 3 happy ingesters should succeed, histograms": {
numIngesters: 3,
happyIngesters: 3,
samples: samplesIn{num: 5, startTimestampMs: 123456789000},
histogramSamples: true,
metadata: 5,
expectedResponse: emptyResponse,
metricNames: []string{lastSeenTimestamp, distributorReceivedSamples},
expectedMetrics: `
# HELP cortex_distributor_latest_seen_sample_timestamp_seconds Unix timestamp of latest received sample per user.
# TYPE cortex_distributor_latest_seen_sample_timestamp_seconds gauge
cortex_distributor_latest_seen_sample_timestamp_seconds{user="userDistributorPush"} 123456789.004
# HELP cortex_distributor_received_samples_total The total number of received samples, excluding rejected and deduped samples.
# TYPE cortex_distributor_received_samples_total counter
cortex_distributor_received_samples_total{type="float",user="userDistributorPush"} 0
cortex_distributor_received_samples_total{type="histogram",user="userDistributorPush"} 5
`,
},
"A push to 2 happy ingesters should succeed, histograms": {
numIngesters: 3,
happyIngesters: 2,
samples: samplesIn{num: 5, startTimestampMs: 123456789000},
histogramSamples: true,
metadata: 5,
expectedResponse: emptyResponse,
metricNames: []string{lastSeenTimestamp, distributorReceivedSamples},
expectedMetrics: `
# HELP cortex_distributor_latest_seen_sample_timestamp_seconds Unix timestamp of latest received sample per user.
# TYPE cortex_distributor_latest_seen_sample_timestamp_seconds gauge
cortex_distributor_latest_seen_sample_timestamp_seconds{user="userDistributorPush"} 123456789.004
# HELP cortex_distributor_received_samples_total The total number of received samples, excluding rejected and deduped samples.
# TYPE cortex_distributor_received_samples_total counter
cortex_distributor_received_samples_total{type="float",user="userDistributorPush"} 0
cortex_distributor_received_samples_total{type="histogram",user="userDistributorPush"} 5
`,
},
"A push to 1 happy ingesters should fail, histograms": {
numIngesters: 3,
happyIngesters: 1,
samples: samplesIn{num: 10, startTimestampMs: 123456789000},
histogramSamples: true,
expectedError: errFail,
metricNames: []string{lastSeenTimestamp, distributorReceivedSamples},
expectedMetrics: `
# HELP cortex_distributor_latest_seen_sample_timestamp_seconds Unix timestamp of latest received sample per user.
# TYPE cortex_distributor_latest_seen_sample_timestamp_seconds gauge
cortex_distributor_latest_seen_sample_timestamp_seconds{user="userDistributorPush"} 123456789.009
# HELP cortex_distributor_received_samples_total The total number of received samples, excluding rejected and deduped samples.
# TYPE cortex_distributor_received_samples_total counter
cortex_distributor_received_samples_total{type="float",user="userDistributorPush"} 0
cortex_distributor_received_samples_total{type="histogram",user="userDistributorPush"} 10
`,
},
"A push exceeding burst size should fail, histograms": {
numIngesters: 3,
happyIngesters: 3,
samples: samplesIn{num: 25, startTimestampMs: 123456789000},
histogramSamples: true,
metadata: 5,
expectedError: httpgrpc.Errorf(http.StatusTooManyRequests, "ingestion rate limit (20) exceeded while adding 25 samples and 5 metadata"),
metricNames: []string{lastSeenTimestamp, distributorReceivedSamples},
expectedMetrics: `
# HELP cortex_distributor_latest_seen_sample_timestamp_seconds Unix timestamp of latest received sample per user.
# TYPE cortex_distributor_latest_seen_sample_timestamp_seconds gauge
cortex_distributor_latest_seen_sample_timestamp_seconds{user="userDistributorPush"} 123456789.024
# HELP cortex_distributor_received_samples_total The total number of received samples, excluding rejected and deduped samples.
# TYPE cortex_distributor_received_samples_total counter
cortex_distributor_received_samples_total{type="float",user="userDistributorPush"} 0
cortex_distributor_received_samples_total{type="histogram",user="userDistributorPush"} 25
`,
},
} {
for _, shardByAllLabels := range []bool{true, false} {
tc := tc
name := name
shardByAllLabels := shardByAllLabels
t.Run(fmt.Sprintf("[%s](shardByAllLabels=%v)", name, shardByAllLabels), func(t *testing.T) {
t.Parallel()
limits := &validation.Limits{}
flagext.DefaultValues(limits)
limits.IngestionRate = 20
limits.IngestionBurstSize = 20
ds, _, regs, _ := prepare(t, prepConfig{
numIngesters: tc.numIngesters,
happyIngesters: tc.happyIngesters,
numDistributors: 1,
shardByAllLabels: shardByAllLabels,
limits: limits,
errFail: tc.ingesterError,
})
var request *cortexpb.WriteRequest
if !tc.histogramSamples {
request = makeWriteRequest(tc.samples.startTimestampMs, tc.samples.num, tc.metadata, 0)
} else {
request = makeWriteRequest(tc.samples.startTimestampMs, 0, tc.metadata, tc.samples.num)
}
response, err := ds[0].Push(ctx, request)
assert.Equal(t, tc.expectedResponse, response)
assert.Equal(t, status.Code(tc.expectedError), status.Code(err))
// Check tracked Prometheus metrics. Since the Push() response is sent as soon as the quorum
// is reached, when we reach this point the 3rd ingester may not have received series/metadata
// yet. To avoid flaky test we retry metrics assertion until we hit the desired state (no error)
// within a reasonable timeout.
if tc.expectedMetrics != "" {
test.Poll(t, time.Second, nil, func() interface{} {
return testutil.GatherAndCompare(regs[0], strings.NewReader(tc.expectedMetrics), tc.metricNames...)
})
}
})
}
}
}
func TestDistributor_MetricsCleanup(t *testing.T) {
t.Parallel()
dists, _, regs, r := prepare(t, prepConfig{
numDistributors: 1,
numIngesters: 2,
happyIngesters: 2,
})
d := dists[0]
reg := regs[0]
permanentMetrics := []string{
"cortex_distributor_received_samples_total",
"cortex_distributor_received_exemplars_total",
"cortex_distributor_received_metadata_total",
"cortex_distributor_samples_in_total",
"cortex_distributor_ingester_append_failures_total",
"cortex_distributor_ingester_appends_total",
"cortex_distributor_ingester_query_failures_total",
"cortex_distributor_ingester_queries_total",
}
removedMetrics := []string{
"cortex_distributor_deduped_samples_total",
"cortex_distributor_exemplars_in_total",
"cortex_distributor_metadata_in_total",
"cortex_distributor_non_ha_samples_received_total",
"cortex_distributor_latest_seen_sample_timestamp_seconds",
"cortex_distributor_received_samples_per_labelset_total",
}
allMetrics := append(removedMetrics, permanentMetrics...)
d.receivedSamples.WithLabelValues("userA", sampleMetricTypeFloat).Add(5)
d.receivedSamples.WithLabelValues("userB", sampleMetricTypeFloat).Add(10)
d.receivedSamples.WithLabelValues("userC", sampleMetricTypeHistogram).Add(15)
d.receivedExemplars.WithLabelValues("userA").Add(5)
d.receivedExemplars.WithLabelValues("userB").Add(10)
d.receivedMetadata.WithLabelValues("userA").Add(5)
d.receivedMetadata.WithLabelValues("userB").Add(10)
d.incomingSamples.WithLabelValues("userA", sampleMetricTypeFloat).Add(5)
d.incomingSamples.WithLabelValues("userB", sampleMetricTypeHistogram).Add(6)
d.incomingExemplars.WithLabelValues("userA").Add(5)
d.incomingMetadata.WithLabelValues("userA").Add(5)
d.nonHASamples.WithLabelValues("userA").Add(5)
d.dedupedSamples.WithLabelValues("userA", "cluster1").Inc() // We cannot clean this metric
d.latestSeenSampleTimestampPerUser.WithLabelValues("userA").Set(1111)
d.receivedSamplesPerLabelSet.WithLabelValues("userA", sampleMetricTypeFloat, "{}").Add(5)
d.receivedSamplesPerLabelSet.WithLabelValues("userA", sampleMetricTypeHistogram, "{}").Add(10)
h, _, _ := r.GetAllInstanceDescs(ring.WriteNoExtend)
ingId0, _ := r.GetInstanceIdByAddr(h[0].Addr)
ingId1, _ := r.GetInstanceIdByAddr(h[1].Addr)
d.ingesterAppends.WithLabelValues(ingId0, typeMetadata).Inc()
d.ingesterAppendFailures.WithLabelValues(ingId0, typeMetadata, "2xx").Inc()
d.ingesterAppends.WithLabelValues(ingId1, typeMetadata).Inc()
d.ingesterAppendFailures.WithLabelValues(ingId1, typeMetadata, "2xx").Inc()
d.ingesterQueries.WithLabelValues(ingId0).Inc()
d.ingesterQueries.WithLabelValues(ingId1).Inc()
d.ingesterQueryFailures.WithLabelValues(ingId0).Inc()
d.ingesterQueryFailures.WithLabelValues(ingId1).Inc()
require.NoError(t, testutil.GatherAndCompare(reg, strings.NewReader(`
# HELP cortex_distributor_deduped_samples_total The total number of deduplicated samples.
# TYPE cortex_distributor_deduped_samples_total counter
cortex_distributor_deduped_samples_total{cluster="cluster1",user="userA"} 1
# HELP cortex_distributor_latest_seen_sample_timestamp_seconds Unix timestamp of latest received sample per user.
# TYPE cortex_distributor_latest_seen_sample_timestamp_seconds gauge
cortex_distributor_latest_seen_sample_timestamp_seconds{user="userA"} 1111
# HELP cortex_distributor_metadata_in_total The total number of metadata that have come in to the distributor, including rejected.
# TYPE cortex_distributor_metadata_in_total counter
cortex_distributor_metadata_in_total{user="userA"} 5
# HELP cortex_distributor_non_ha_samples_received_total The total number of received samples for a user that has HA tracking turned on, but the sample didn't contain both HA labels.
# TYPE cortex_distributor_non_ha_samples_received_total counter
cortex_distributor_non_ha_samples_received_total{user="userA"} 5
# HELP cortex_distributor_received_metadata_total The total number of received metadata, excluding rejected.
# TYPE cortex_distributor_received_metadata_total counter
cortex_distributor_received_metadata_total{user="userA"} 5
cortex_distributor_received_metadata_total{user="userB"} 10
# HELP cortex_distributor_received_samples_per_labelset_total The total number of received samples per label set, excluding rejected and deduped samples.
# TYPE cortex_distributor_received_samples_per_labelset_total counter
cortex_distributor_received_samples_per_labelset_total{labelset="{}",type="float",user="userA"} 5
cortex_distributor_received_samples_per_labelset_total{labelset="{}",type="histogram",user="userA"} 10
# HELP cortex_distributor_received_samples_total The total number of received samples, excluding rejected and deduped samples.
# TYPE cortex_distributor_received_samples_total counter
cortex_distributor_received_samples_total{type="float",user="userA"} 5
cortex_distributor_received_samples_total{type="float",user="userB"} 10
cortex_distributor_received_samples_total{type="histogram",user="userC"} 15
# HELP cortex_distributor_received_exemplars_total The total number of received exemplars, excluding rejected and deduped exemplars.
# TYPE cortex_distributor_received_exemplars_total counter
cortex_distributor_received_exemplars_total{user="userA"} 5
cortex_distributor_received_exemplars_total{user="userB"} 10
# HELP cortex_distributor_samples_in_total The total number of samples that have come in to the distributor, including rejected or deduped samples.
# TYPE cortex_distributor_samples_in_total counter
cortex_distributor_samples_in_total{type="float",user="userA"} 5
cortex_distributor_samples_in_total{type="histogram",user="userB"} 6
# HELP cortex_distributor_exemplars_in_total The total number of exemplars that have come in to the distributor, including rejected or deduped exemplars.
# TYPE cortex_distributor_exemplars_in_total counter
cortex_distributor_exemplars_in_total{user="userA"} 5
# HELP cortex_distributor_ingester_append_failures_total The total number of failed batch appends sent to ingesters.
# TYPE cortex_distributor_ingester_append_failures_total counter
cortex_distributor_ingester_append_failures_total{ingester="ingester-0",status="2xx",type="metadata"} 1
cortex_distributor_ingester_append_failures_total{ingester="ingester-1",status="2xx",type="metadata"} 1
# HELP cortex_distributor_ingester_appends_total The total number of batch appends sent to ingesters.
# TYPE cortex_distributor_ingester_appends_total counter
cortex_distributor_ingester_appends_total{ingester="ingester-0",type="metadata"} 1
cortex_distributor_ingester_appends_total{ingester="ingester-1",type="metadata"} 1
# HELP cortex_distributor_ingester_queries_total The total number of queries sent to ingesters.
# TYPE cortex_distributor_ingester_queries_total counter
cortex_distributor_ingester_queries_total{ingester="ingester-0"} 1
cortex_distributor_ingester_queries_total{ingester="ingester-1"} 1
# HELP cortex_distributor_ingester_query_failures_total The total number of failed queries sent to ingesters.
# TYPE cortex_distributor_ingester_query_failures_total counter
cortex_distributor_ingester_query_failures_total{ingester="ingester-0"} 1
cortex_distributor_ingester_query_failures_total{ingester="ingester-1"} 1
`), allMetrics...))
d.cleanupInactiveUser("userA")
err := r.KVClient.CAS(context.Background(), ingester.RingKey, func(in interface{}) (interface{}, bool, error) {
r := in.(*ring.Desc)
delete(r.Ingesters, "ingester-0")
return in, true, nil
})
test.Poll(t, time.Second, true, func() interface{} {
ings, _, _ := r.GetAllInstanceDescs(ring.Write)
return len(ings) == 1
})
require.NoError(t, err)
d.cleanStaleIngesterMetrics()
require.NoError(t, testutil.GatherAndCompare(reg, strings.NewReader(`
# HELP cortex_distributor_received_metadata_total The total number of received metadata, excluding rejected.
# TYPE cortex_distributor_received_metadata_total counter
cortex_distributor_received_metadata_total{user="userB"} 10
# HELP cortex_distributor_received_samples_total The total number of received samples, excluding rejected and deduped samples.
# TYPE cortex_distributor_received_samples_total counter
cortex_distributor_received_samples_total{type="float",user="userB"} 10
cortex_distributor_received_samples_total{type="histogram",user="userC"} 15
# HELP cortex_distributor_samples_in_total The total number of samples that have come in to the distributor, including rejected or deduped samples.
# TYPE cortex_distributor_samples_in_total counter
cortex_distributor_samples_in_total{type="histogram",user="userB"} 6
# HELP cortex_distributor_received_exemplars_total The total number of received exemplars, excluding rejected and deduped exemplars.
# TYPE cortex_distributor_received_exemplars_total counter
cortex_distributor_received_exemplars_total{user="userB"} 10
# HELP cortex_distributor_ingester_append_failures_total The total number of failed batch appends sent to ingesters.
# TYPE cortex_distributor_ingester_append_failures_total counter
cortex_distributor_ingester_append_failures_total{ingester="ingester-1",status="2xx",type="metadata"} 1
# HELP cortex_distributor_ingester_appends_total The total number of batch appends sent to ingesters.
# TYPE cortex_distributor_ingester_appends_total counter
cortex_distributor_ingester_appends_total{ingester="ingester-1",type="metadata"} 1
# HELP cortex_distributor_ingester_queries_total The total number of queries sent to ingesters.
# TYPE cortex_distributor_ingester_queries_total counter
cortex_distributor_ingester_queries_total{ingester="ingester-1"} 1
# HELP cortex_distributor_ingester_query_failures_total The total number of failed queries sent to ingesters.
# TYPE cortex_distributor_ingester_query_failures_total counter
cortex_distributor_ingester_query_failures_total{ingester="ingester-1"} 1
`), permanentMetrics...))
require.NoError(t, testutil.GatherAndCompare(reg, strings.NewReader(""), removedMetrics...))
}
func TestDistributor_PushIngestionRateLimiter(t *testing.T) {
t.Parallel()
type testPush struct {
samples int
metadata int
expectedError error
}
ctx := user.InjectOrgID(context.Background(), "user")
tests := map[string]struct {
distributors int
ingestionRateStrategy string
ingestionRate float64
ingestionBurstSize int
pushes []testPush
}{
"local strategy: limit should be set to each distributor": {
distributors: 2,
ingestionRateStrategy: validation.LocalIngestionRateStrategy,
ingestionRate: 10,
ingestionBurstSize: 10,
pushes: []testPush{
{samples: 4, expectedError: nil},
{metadata: 1, expectedError: nil},
{samples: 6, expectedError: httpgrpc.Errorf(http.StatusTooManyRequests, "ingestion rate limit (10) exceeded while adding 6 samples and 0 metadata")},
{samples: 4, metadata: 1, expectedError: nil},
{samples: 1, expectedError: httpgrpc.Errorf(http.StatusTooManyRequests, "ingestion rate limit (10) exceeded while adding 1 samples and 0 metadata")},
{metadata: 1, expectedError: httpgrpc.Errorf(http.StatusTooManyRequests, "ingestion rate limit (10) exceeded while adding 0 samples and 1 metadata")},
},
},
"global strategy: limit should be evenly shared across distributors": {
distributors: 2,
ingestionRateStrategy: validation.GlobalIngestionRateStrategy,
ingestionRate: 10,
ingestionBurstSize: 5,
pushes: []testPush{
{samples: 2, expectedError: nil},
{samples: 1, expectedError: nil},
{samples: 2, metadata: 1, expectedError: httpgrpc.Errorf(http.StatusTooManyRequests, "ingestion rate limit (5) exceeded while adding 2 samples and 1 metadata")},
{samples: 2, expectedError: nil},
{samples: 1, expectedError: httpgrpc.Errorf(http.StatusTooManyRequests, "ingestion rate limit (5) exceeded while adding 1 samples and 0 metadata")},
{metadata: 1, expectedError: httpgrpc.Errorf(http.StatusTooManyRequests, "ingestion rate limit (5) exceeded while adding 0 samples and 1 metadata")},
},
},
"global strategy: burst should set to each distributor": {
distributors: 2,
ingestionRateStrategy: validation.GlobalIngestionRateStrategy,
ingestionRate: 10,
ingestionBurstSize: 20,
pushes: []testPush{
{samples: 10, expectedError: nil},
{samples: 5, expectedError: nil},
{samples: 5, metadata: 1, expectedError: httpgrpc.Errorf(http.StatusTooManyRequests, "ingestion rate limit (5) exceeded while adding 5 samples and 1 metadata")},
{samples: 5, expectedError: nil},
{samples: 1, expectedError: httpgrpc.Errorf(http.StatusTooManyRequests, "ingestion rate limit (5) exceeded while adding 1 samples and 0 metadata")},
{metadata: 1, expectedError: httpgrpc.Errorf(http.StatusTooManyRequests, "ingestion rate limit (5) exceeded while adding 0 samples and 1 metadata")},
},
},
}
for testName, testData := range tests {
testData := testData
for _, enableHistogram := range []bool{false, true} {
enableHistogram := enableHistogram
t.Run(fmt.Sprintf("%s, histogram=%s", testName, strconv.FormatBool(enableHistogram)), func(t *testing.T) {
t.Parallel()
limits := &validation.Limits{}
flagext.DefaultValues(limits)
limits.IngestionRateStrategy = testData.ingestionRateStrategy
limits.IngestionRate = testData.ingestionRate
limits.IngestionBurstSize = testData.ingestionBurstSize
// Start all expected distributors
distributors, _, _, _ := prepare(t, prepConfig{
numIngesters: 3,
happyIngesters: 3,
numDistributors: testData.distributors,
shardByAllLabels: true,
limits: limits,
})
// Push samples in multiple requests to the first distributor
for _, push := range testData.pushes {
var request *cortexpb.WriteRequest
if !enableHistogram {
request = makeWriteRequest(0, push.samples, push.metadata, 0)
} else {
request = makeWriteRequest(0, 0, push.metadata, push.samples)
}
response, err := distributors[0].Push(ctx, request)
if push.expectedError == nil {
assert.Equal(t, emptyResponse, response)
assert.Nil(t, err)
} else {
assert.Nil(t, response)
assert.Equal(t, push.expectedError, err)
}
}
})
}
}
}
func TestPush_QuorumError(t *testing.T) {
t.Parallel()
var limits validation.Limits
flagext.DefaultValues(&limits)
limits.IngestionRate = math.MaxFloat64
dists, ingesters, _, r := prepare(t, prepConfig{
numDistributors: 1,
numIngesters: 3,
happyIngesters: 0,
shuffleShardSize: 3,
shardByAllLabels: true,
shuffleShardEnabled: true,
limits: &limits,
})
ctx := user.InjectOrgID(context.Background(), "user")
d := dists[0]
// we should run several write request to make sure we dont have any race condition on the batchTracker#record code
numberOfWrites := 10000
// Using 429 just to make sure we are not hitting the &limits
// Simulating 2 4xx and 1 5xx -> Should return 4xx
ingesters[0].failResp.Store(httpgrpc.Errorf(429, "Throttling"))
ingesters[1].failResp.Store(httpgrpc.Errorf(500, "InternalServerError"))
ingesters[2].failResp.Store(httpgrpc.Errorf(429, "Throttling"))
for i := 0; i < numberOfWrites; i++ {
request := makeWriteRequest(0, 30, 20, 10)
_, err := d.Push(ctx, request)
status, ok := status.FromError(err)
require.True(t, ok)
require.Equal(t, codes.Code(429), status.Code())
}
// Simulating 2 5xx and 1 4xx -> Should return 5xx
ingesters[0].failResp.Store(httpgrpc.Errorf(500, "InternalServerError"))
ingesters[1].failResp.Store(httpgrpc.Errorf(429, "Throttling"))
ingesters[2].failResp.Store(httpgrpc.Errorf(500, "InternalServerError"))
for i := 0; i < numberOfWrites; i++ {
request := makeWriteRequest(0, 300, 200, 10)
_, err := d.Push(ctx, request)
status, ok := status.FromError(err)
require.True(t, ok)
require.Equal(t, codes.Code(500), status.Code())
}
// Simulating 2 different errors and 1 success -> This case we may return any of the errors
ingesters[0].failResp.Store(httpgrpc.Errorf(500, "InternalServerError"))
ingesters[1].failResp.Store(httpgrpc.Errorf(429, "Throttling"))
ingesters[2].happy.Store(true)
for i := 0; i < numberOfWrites; i++ {
request := makeWriteRequest(0, 30, 20, 10)
_, err := d.Push(ctx, request)
status, ok := status.FromError(err)
require.True(t, ok)
require.Equal(t, codes.Code(429), status.Code())
}
// Simulating 1 error -> Should return 2xx
ingesters[0].failResp.Store(httpgrpc.Errorf(500, "InternalServerError"))
ingesters[1].happy.Store(true)
ingesters[2].happy.Store(true)
for i := 0; i < 1; i++ {
request := makeWriteRequest(0, 30, 20, 10)
_, err := d.Push(ctx, request)
require.NoError(t, err)
}
// Simulating an unhealthy ingester (ingester 2)
ingesters[0].failResp.Store(httpgrpc.Errorf(500, "InternalServerError"))
ingesters[1].happy.Store(true)
ingesters[2].happy.Store(true)
err := r.KVClient.CAS(context.Background(), ingester.RingKey, func(in interface{}) (interface{}, bool, error) {
r := in.(*ring.Desc)
ingester2 := r.Ingesters["ingester-2"]
ingester2.State = ring.LEFT
ingester2.Timestamp = time.Now().Unix()
r.Ingesters["ingester-2"] = ingester2
return in, true, nil
})
require.NoError(t, err)
// Give time to the ring get updated with the KV value
test.Poll(t, 15*time.Second, true, func() interface{} {
replicationSet, _ := r.GetAllHealthy(ring.Read)
return len(replicationSet.Instances) == 2
})
for i := 0; i < numberOfWrites; i++ {
request := makeWriteRequest(0, 30, 20, 10)
_, err := d.Push(ctx, request)
require.Error(t, err)
status, ok := status.FromError(err)
require.True(t, ok)
require.Equal(t, codes.Code(500), status.Code())
}
}
func TestDistributor_PushInstanceLimits(t *testing.T) {
t.Parallel()
type testPush struct {
samples int
metadata int
expectedError error
}
ctx := user.InjectOrgID(context.Background(), "user")
tests := map[string]struct {
preInflight int
preInflightClient int
preRateSamples int // initial rate before first push
pushes []testPush // rate is recomputed after each push
// limits
inflightLimit int
inflightClientLimit int
ingestionRateLimit float64
metricNames []string
expectedMetrics string
}{
"no limits limit": {
preInflight: 100,
preRateSamples: 1000,
pushes: []testPush{
{samples: 100, expectedError: nil},
},
metricNames: []string{instanceLimitsMetric},
expectedMetrics: `
# HELP cortex_distributor_instance_limits Instance limits used by this distributor.
# TYPE cortex_distributor_instance_limits gauge
cortex_distributor_instance_limits{limit="max_inflight_client_requests"} 0
cortex_distributor_instance_limits{limit="max_inflight_push_requests"} 0
cortex_distributor_instance_limits{limit="max_ingestion_rate"} 0
`,
},
"below inflight limit": {
preInflight: 100,
inflightLimit: 101,
pushes: []testPush{
{samples: 100, expectedError: nil},
},
metricNames: []string{instanceLimitsMetric, "cortex_distributor_inflight_push_requests"},
expectedMetrics: `
# HELP cortex_distributor_inflight_push_requests Current number of inflight push requests in distributor.
# TYPE cortex_distributor_inflight_push_requests gauge
cortex_distributor_inflight_push_requests 100
# HELP cortex_distributor_instance_limits Instance limits used by this distributor.
# TYPE cortex_distributor_instance_limits gauge
cortex_distributor_instance_limits{limit="max_inflight_client_requests"} 0
cortex_distributor_instance_limits{limit="max_inflight_push_requests"} 101
cortex_distributor_instance_limits{limit="max_ingestion_rate"} 0
`,
},
"hits inflight limit": {
preInflight: 101,
inflightLimit: 101,
pushes: []testPush{
{samples: 100, expectedError: httpgrpc.Errorf(http.StatusServiceUnavailable, "too many inflight push requests in distributor")},
},
},
"below inflight client limit": {
preInflightClient: 90,
inflightClientLimit: 101,
pushes: []testPush{
{samples: 100, expectedError: nil},
},
metricNames: []string{instanceLimitsMetric},
expectedMetrics: `
# HELP cortex_distributor_instance_limits Instance limits used by this distributor.
# TYPE cortex_distributor_instance_limits gauge
cortex_distributor_instance_limits{limit="max_inflight_client_requests"} 101
cortex_distributor_instance_limits{limit="max_inflight_push_requests"} 0
cortex_distributor_instance_limits{limit="max_ingestion_rate"} 0
`,
},
"hits inflight client limit": {
preInflightClient: 103,
inflightClientLimit: 101,
pushes: []testPush{
{samples: 100, expectedError: httpgrpc.Errorf(http.StatusServiceUnavailable,
"too many inflight ingester client requests in distributor")},
},
},
"below ingestion rate limit": {
preRateSamples: 500,
ingestionRateLimit: 1000,
pushes: []testPush{
{samples: 1000, expectedError: nil},
},
metricNames: []string{instanceLimitsMetric, "cortex_distributor_ingestion_rate_samples_per_second"},
expectedMetrics: `
# HELP cortex_distributor_ingestion_rate_samples_per_second Current ingestion rate in samples/sec that distributor is using to limit access.
# TYPE cortex_distributor_ingestion_rate_samples_per_second gauge
cortex_distributor_ingestion_rate_samples_per_second 600
# HELP cortex_distributor_instance_limits Instance limits used by this distributor.
# TYPE cortex_distributor_instance_limits gauge
cortex_distributor_instance_limits{limit="max_inflight_client_requests"} 0
cortex_distributor_instance_limits{limit="max_inflight_push_requests"} 0
cortex_distributor_instance_limits{limit="max_ingestion_rate"} 1000
`,
},
"hits rate limit on first request, but second request can proceed": {
preRateSamples: 1200,
ingestionRateLimit: 1000,
pushes: []testPush{
{samples: 100, expectedError: httpgrpc.Errorf(http.StatusServiceUnavailable, "distributor's samples push rate limit reached")},
{samples: 100, expectedError: nil},
},
},
"below rate limit on first request, but hits the rate limit afterwards": {
preRateSamples: 500,
ingestionRateLimit: 1000,
pushes: []testPush{
{samples: 5000, expectedError: nil}, // after push, rate = 500 + 0.2*(5000-500) = 1400
{samples: 5000, expectedError: httpgrpc.Errorf(http.StatusServiceUnavailable, "distributor's samples push rate limit reached")}, // after push, rate = 1400 + 0.2*(0 - 1400) = 1120
{samples: 5000, expectedError: httpgrpc.Errorf(http.StatusServiceUnavailable, "distributor's samples push rate limit reached")}, // after push, rate = 1120 + 0.2*(0 - 1120) = 896
{samples: 5000, expectedError: nil}, // 896 is below 1000, so this push succeeds, new rate = 896 + 0.2*(5000-896) = 1716.8
},
},
}
for testName, testData := range tests {
testData := testData
for _, enableHistogram := range []bool{true, false} {
enableHistogram := enableHistogram
t.Run(fmt.Sprintf("%s, histogram=%s", testName, strconv.FormatBool(enableHistogram)), func(t *testing.T) {
t.Parallel()
limits := &validation.Limits{}
flagext.DefaultValues(limits)
// Start all expected distributors
distributors, _, regs, _ := prepare(t, prepConfig{
numIngesters: 3,
happyIngesters: 3,
numDistributors: 1,
shardByAllLabels: true,
limits: limits,
maxInflightRequests: testData.inflightLimit,
maxInflightClientRequests: testData.inflightClientLimit,
maxIngestionRate: testData.ingestionRateLimit,
})
d := distributors[0]
d.inflightPushRequests.Add(int64(testData.preInflight))
d.inflightClientRequests.Add(int64(testData.preInflightClient))
d.ingestionRate.Add(int64(testData.preRateSamples))
d.ingestionRate.Tick()
for _, push := range testData.pushes {
var request *cortexpb.WriteRequest
if enableHistogram {
request = makeWriteRequest(0, 0, push.metadata, push.samples)
} else {
request = makeWriteRequest(0, push.samples, push.metadata, 0)
}
_, err := d.Push(ctx, request)
if push.expectedError == nil {
assert.Nil(t, err)
} else {
assert.Equal(t, push.expectedError, err)
}
d.ingestionRate.Tick()
if testData.expectedMetrics != "" {
assert.NoError(t, testutil.GatherAndCompare(regs[0], strings.NewReader(testData.expectedMetrics), testData.metricNames...))
}
}
})
}
}
}
func TestDistributor_PushHAInstances(t *testing.T) {
t.Parallel()
ctx := user.InjectOrgID(context.Background(), "user")
for i, tc := range []struct {
enableTracker bool
acceptedReplica string
testReplica string
cluster string
samples int
expectedResponse *cortexpb.WriteResponse
expectedCode int32
}{
{
enableTracker: true,
acceptedReplica: "instance0",
testReplica: "instance0",
cluster: "cluster0",
samples: 5,
expectedResponse: emptyResponse,
},
// The 202 indicates that we didn't accept this sample.
{