forked from open-telemetry/opentelemetry-collector-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
metrics_translator_test.go
1576 lines (1406 loc) · 51.6 KB
/
metrics_translator_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
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http:https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// nolint:gocritic
package translator
import (
"context"
"fmt"
"math"
"testing"
"time"
"github.com/DataDog/datadog-agent/pkg/quantile"
"github.com/DataDog/datadog-agent/pkg/quantile/summary"
gocache "github.com/patrickmn/go-cache"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/pmetric"
conventions "go.opentelemetry.io/collector/semconv/v1.6.1"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest/observer"
"github.com/open-telemetry/opentelemetry-collector-contrib/exporter/datadogexporter/internal/model/attributes"
)
func TestIsCumulativeMonotonic(t *testing.T) {
// Some of these examples are from the hostmetrics receiver
// and reflect the semantic meaning of the metrics there.
//
// If the receiver changes these examples should be added here too
{ // Sum: Cumulative but not monotonic
metric := pmetric.NewMetric()
metric.SetName("system.filesystem.usage")
metric.SetDescription("Filesystem bytes used.")
metric.SetUnit("bytes")
metric.SetDataType(pmetric.MetricDataTypeSum)
sum := metric.Sum()
sum.SetIsMonotonic(false)
sum.SetAggregationTemporality(pmetric.MetricAggregationTemporalityCumulative)
assert.False(t, isCumulativeMonotonic(metric))
}
{ // Sum: Cumulative and monotonic
metric := pmetric.NewMetric()
metric.SetName("system.network.packets")
metric.SetDescription("The number of packets transferred.")
metric.SetUnit("1")
metric.SetDataType(pmetric.MetricDataTypeSum)
sum := metric.Sum()
sum.SetIsMonotonic(true)
sum.SetAggregationTemporality(pmetric.MetricAggregationTemporalityCumulative)
assert.True(t, isCumulativeMonotonic(metric))
}
{ // DoubleSumL Cumulative and monotonic
metric := pmetric.NewMetric()
metric.SetName("metric.example")
metric.SetDataType(pmetric.MetricDataTypeSum)
sum := metric.Sum()
sum.SetIsMonotonic(true)
sum.SetAggregationTemporality(pmetric.MetricAggregationTemporalityCumulative)
assert.True(t, isCumulativeMonotonic(metric))
}
{ // Not IntSum
metric := pmetric.NewMetric()
metric.SetName("system.cpu.load_average.1m")
metric.SetDescription("Average CPU Load over 1 minute.")
metric.SetUnit("1")
metric.SetDataType(pmetric.MetricDataTypeGauge)
assert.False(t, isCumulativeMonotonic(metric))
}
}
type testProvider string
func (t testProvider) Hostname(context.Context) (string, error) {
return string(t), nil
}
func newTranslator(t *testing.T, logger *zap.Logger, opts ...Option) *Translator {
options := append([]Option{
WithFallbackHostnameProvider(testProvider("fallbackHostname")),
WithHistogramMode(HistogramModeDistributions),
WithNumberMode(NumberModeCumulativeToDelta),
}, opts...)
tr, err := New(
logger,
options...,
)
require.NoError(t, err)
return tr
}
type metric struct {
name string
typ MetricDataType
timestamp uint64
value float64
tags []string
host string
}
type sketch struct {
name string
basic summary.Summary
timestamp uint64
tags []string
host string
}
func testMatchingSketches(t *testing.T, expected, actual []sketch) {
assert.Equal(t, len(expected), len(actual), "sketches list doesn't have the expected size")
if len(expected) == len(actual) {
for i := 0; i < len(expected); i++ {
expectedSketch := expected[i]
actualSketch := actual[i]
assert.Equal(t, expectedSketch.name, actualSketch.name, "expected and actual sketch names do not match")
assert.Equal(t, expectedSketch.host, actualSketch.host, "expected and actual sketch hosts do not match")
assert.Equal(t, expectedSketch.timestamp, actualSketch.timestamp, "expected and actual sketch timestamps do not match")
assert.Equal(t, expectedSketch.basic.Sum, actualSketch.basic.Sum, "expected and actual sketch sums do not match")
assert.Equal(t, expectedSketch.basic.Cnt, actualSketch.basic.Cnt, "expected and actual sketch counts do not match")
assert.Equal(t, expectedSketch.basic.Avg, actualSketch.basic.Avg, "expected and actual sketch averages do not match")
assert.ElementsMatch(t, expectedSketch.tags, actualSketch.tags, "expected and actual sketch tags do not match")
// For ExponentialHistograms, we can't do exact comparisons for Min and Max, given that they're inferred from the sketch
// TODO: once exact min and max are provided, use them: https://github.com/open-telemetry/opentelemetry-proto/pull/279
// Note: 0.01 delta taken at random, may not work with any exponential histogram input
assert.InDelta(t, expectedSketch.basic.Max, actualSketch.basic.Max, 0.01, "expected and actual sketch maximums do not match")
assert.InDelta(t, expectedSketch.basic.Min, actualSketch.basic.Min, 0.01, "expected and actual sketch minimums do not match")
}
}
}
var _ TimeSeriesConsumer = (*mockTimeSeriesConsumer)(nil)
type mockTimeSeriesConsumer struct {
metrics []metric
}
func (m *mockTimeSeriesConsumer) ConsumeTimeSeries(
_ context.Context,
dimensions *Dimensions,
typ MetricDataType,
ts uint64,
val float64,
) {
m.metrics = append(m.metrics,
metric{
name: dimensions.Name(),
typ: typ,
timestamp: ts,
value: val,
tags: dimensions.Tags(),
host: dimensions.Host(),
},
)
}
func newDims(name string) *Dimensions {
return &Dimensions{name: name, tags: []string{}}
}
func newGauge(dims *Dimensions, ts uint64, val float64) metric {
return metric{name: dims.name, typ: Gauge, timestamp: ts, value: val, tags: dims.tags}
}
func newCount(dims *Dimensions, ts uint64, val float64) metric {
return metric{name: dims.name, typ: Count, timestamp: ts, value: val, tags: dims.tags}
}
func newSketch(dims *Dimensions, ts uint64, s summary.Summary) sketch {
return sketch{name: dims.name, basic: s, timestamp: ts, tags: dims.tags}
}
func TestMapIntMetrics(t *testing.T) {
ts := pcommon.NewTimestampFromTime(time.Now())
slice := pmetric.NewNumberDataPointSlice()
point := slice.AppendEmpty()
point.SetIntVal(17)
point.SetTimestamp(ts)
ctx := context.Background()
tr := newTranslator(t, zap.NewNop())
consumer := &mockTimeSeriesConsumer{}
dims := newDims("int64.test")
tr.mapNumberMetrics(ctx, consumer, dims, Gauge, slice)
assert.ElementsMatch(t,
consumer.metrics,
[]metric{newGauge(dims, uint64(ts), 17)},
)
consumer = &mockTimeSeriesConsumer{}
dims = newDims("int64.delta.test")
tr.mapNumberMetrics(ctx, consumer, dims, Count, slice)
assert.ElementsMatch(t,
consumer.metrics,
[]metric{newCount(dims, uint64(ts), 17)},
)
// With attribute tags
consumer = &mockTimeSeriesConsumer{}
dims = &Dimensions{name: "int64.test", tags: []string{"attribute_tag:attribute_value"}}
tr.mapNumberMetrics(ctx, consumer, dims, Gauge, slice)
assert.ElementsMatch(t,
consumer.metrics,
[]metric{newGauge(dims, uint64(ts), 17)},
)
}
func TestMapDoubleMetrics(t *testing.T) {
ts := pcommon.NewTimestampFromTime(time.Now())
slice := pmetric.NewNumberDataPointSlice()
point := slice.AppendEmpty()
point.SetDoubleVal(math.Pi)
point.SetTimestamp(ts)
ctx := context.Background()
tr := newTranslator(t, zap.NewNop())
consumer := &mockTimeSeriesConsumer{}
dims := newDims("float64.test")
tr.mapNumberMetrics(ctx, consumer, dims, Gauge, slice)
assert.ElementsMatch(t,
consumer.metrics,
[]metric{newGauge(dims, uint64(ts), math.Pi)},
)
consumer = &mockTimeSeriesConsumer{}
dims = newDims("float64.delta.test")
tr.mapNumberMetrics(ctx, consumer, dims, Count, slice)
assert.ElementsMatch(t,
consumer.metrics,
[]metric{newCount(dims, uint64(ts), math.Pi)},
)
// With attribute tags
consumer = &mockTimeSeriesConsumer{}
dims = &Dimensions{name: "float64.test", tags: []string{"attribute_tag:attribute_value"}}
tr.mapNumberMetrics(ctx, consumer, dims, Gauge, slice)
assert.ElementsMatch(t,
consumer.metrics,
[]metric{newGauge(dims, uint64(ts), math.Pi)},
)
}
func seconds(i int) pcommon.Timestamp {
return pcommon.NewTimestampFromTime(time.Unix(int64(i), 0))
}
var exampleDims = newDims("metric.example")
func TestMapIntMonotonicMetrics(t *testing.T) {
// Create list of values
deltas := []int64{1, 2, 200, 3, 7, 0}
cumulative := make([]int64, len(deltas)+1)
cumulative[0] = 0
for i := 1; i < len(cumulative); i++ {
cumulative[i] = cumulative[i-1] + deltas[i-1]
}
//Map to OpenTelemetry format
slice := pmetric.NewNumberDataPointSlice()
slice.EnsureCapacity(len(cumulative))
for i, val := range cumulative {
point := slice.AppendEmpty()
point.SetIntVal(val)
point.SetTimestamp(seconds(i))
}
// Map to Datadog format
expected := make([]metric, len(deltas))
for i, val := range deltas {
expected[i] = newCount(exampleDims, uint64(seconds(i+1)), float64(val))
}
ctx := context.Background()
consumer := &mockTimeSeriesConsumer{}
tr := newTranslator(t, zap.NewNop())
tr.mapNumberMonotonicMetrics(ctx, consumer, exampleDims, slice)
assert.ElementsMatch(t, expected, consumer.metrics)
}
func TestMapIntMonotonicDifferentDimensions(t *testing.T) {
slice := pmetric.NewNumberDataPointSlice()
// No tags
point := slice.AppendEmpty()
point.SetTimestamp(seconds(0))
point = slice.AppendEmpty()
point.SetIntVal(20)
point.SetTimestamp(seconds(1))
// One tag: valA
point = slice.AppendEmpty()
point.SetTimestamp(seconds(0))
point.Attributes().InsertString("key1", "valA")
point = slice.AppendEmpty()
point.SetIntVal(30)
point.SetTimestamp(seconds(1))
point.Attributes().InsertString("key1", "valA")
// same tag: valB
point = slice.AppendEmpty()
point.SetTimestamp(seconds(0))
point.Attributes().InsertString("key1", "valB")
point = slice.AppendEmpty()
point.SetIntVal(40)
point.SetTimestamp(seconds(1))
point.Attributes().InsertString("key1", "valB")
ctx := context.Background()
tr := newTranslator(t, zap.NewNop())
consumer := &mockTimeSeriesConsumer{}
tr.mapNumberMonotonicMetrics(ctx, consumer, exampleDims, slice)
assert.ElementsMatch(t,
consumer.metrics,
[]metric{
newCount(exampleDims, uint64(seconds(1)), 20),
newCount(exampleDims.AddTags("key1:valA"), uint64(seconds(1)), 30),
newCount(exampleDims.AddTags("key1:valB"), uint64(seconds(1)), 40),
},
)
}
func TestMapIntMonotonicWithReboot(t *testing.T) {
values := []int64{0, 30, 0, 20}
slice := pmetric.NewNumberDataPointSlice()
slice.EnsureCapacity(len(values))
for i, val := range values {
point := slice.AppendEmpty()
point.SetTimestamp(seconds(i))
point.SetIntVal(val)
}
ctx := context.Background()
tr := newTranslator(t, zap.NewNop())
consumer := &mockTimeSeriesConsumer{}
tr.mapNumberMonotonicMetrics(ctx, consumer, exampleDims, slice)
assert.ElementsMatch(t,
consumer.metrics,
[]metric{
newCount(exampleDims, uint64(seconds(1)), 30),
newCount(exampleDims, uint64(seconds(3)), 20),
},
)
}
func TestMapIntMonotonicOutOfOrder(t *testing.T) {
stamps := []int{1, 0, 2, 3}
values := []int64{0, 1, 2, 3}
slice := pmetric.NewNumberDataPointSlice()
slice.EnsureCapacity(len(values))
for i, val := range values {
point := slice.AppendEmpty()
point.SetTimestamp(seconds(stamps[i]))
point.SetIntVal(val)
}
ctx := context.Background()
tr := newTranslator(t, zap.NewNop())
consumer := &mockTimeSeriesConsumer{}
tr.mapNumberMonotonicMetrics(ctx, consumer, exampleDims, slice)
assert.ElementsMatch(t,
consumer.metrics,
[]metric{
newCount(exampleDims, uint64(seconds(2)), 2),
newCount(exampleDims, uint64(seconds(3)), 1),
},
)
}
func TestMapDoubleMonotonicMetrics(t *testing.T) {
deltas := []float64{1, 2, 200, 3, 7, 0}
cumulative := make([]float64, len(deltas)+1)
cumulative[0] = 0
for i := 1; i < len(cumulative); i++ {
cumulative[i] = cumulative[i-1] + deltas[i-1]
}
//Map to OpenTelemetry format
slice := pmetric.NewNumberDataPointSlice()
slice.EnsureCapacity(len(cumulative))
for i, val := range cumulative {
point := slice.AppendEmpty()
point.SetDoubleVal(val)
point.SetTimestamp(seconds(i))
}
// Map to Datadog format
expected := make([]metric, len(deltas))
for i, val := range deltas {
expected[i] = newCount(exampleDims, uint64(seconds(i+1)), val)
}
ctx := context.Background()
consumer := &mockTimeSeriesConsumer{}
tr := newTranslator(t, zap.NewNop())
tr.mapNumberMonotonicMetrics(ctx, consumer, exampleDims, slice)
assert.ElementsMatch(t, expected, consumer.metrics)
}
func TestMapDoubleMonotonicDifferentDimensions(t *testing.T) {
slice := pmetric.NewNumberDataPointSlice()
// No tags
point := slice.AppendEmpty()
point.SetTimestamp(seconds(0))
point = slice.AppendEmpty()
point.SetDoubleVal(20)
point.SetTimestamp(seconds(1))
// One tag: valA
point = slice.AppendEmpty()
point.SetTimestamp(seconds(0))
point.Attributes().InsertString("key1", "valA")
point = slice.AppendEmpty()
point.SetDoubleVal(30)
point.SetTimestamp(seconds(1))
point.Attributes().InsertString("key1", "valA")
// one tag: valB
point = slice.AppendEmpty()
point.SetTimestamp(seconds(0))
point.Attributes().InsertString("key1", "valB")
point = slice.AppendEmpty()
point.SetDoubleVal(40)
point.SetTimestamp(seconds(1))
point.Attributes().InsertString("key1", "valB")
ctx := context.Background()
tr := newTranslator(t, zap.NewNop())
consumer := &mockTimeSeriesConsumer{}
tr.mapNumberMonotonicMetrics(ctx, consumer, exampleDims, slice)
assert.ElementsMatch(t,
consumer.metrics,
[]metric{
newCount(exampleDims, uint64(seconds(1)), 20),
newCount(exampleDims.AddTags("key1:valA"), uint64(seconds(1)), 30),
newCount(exampleDims.AddTags("key1:valB"), uint64(seconds(1)), 40),
},
)
}
func TestMapDoubleMonotonicWithReboot(t *testing.T) {
values := []float64{0, 30, 0, 20}
slice := pmetric.NewNumberDataPointSlice()
slice.EnsureCapacity(len(values))
for i, val := range values {
point := slice.AppendEmpty()
point.SetTimestamp(seconds(2 * i))
point.SetDoubleVal(val)
}
ctx := context.Background()
tr := newTranslator(t, zap.NewNop())
consumer := &mockTimeSeriesConsumer{}
tr.mapNumberMonotonicMetrics(ctx, consumer, exampleDims, slice)
assert.ElementsMatch(t,
consumer.metrics,
[]metric{
newCount(exampleDims, uint64(seconds(2)), 30),
newCount(exampleDims, uint64(seconds(6)), 20),
},
)
}
func TestMapDoubleMonotonicOutOfOrder(t *testing.T) {
stamps := []int{1, 0, 2, 3}
values := []float64{0, 1, 2, 3}
slice := pmetric.NewNumberDataPointSlice()
slice.EnsureCapacity(len(values))
for i, val := range values {
point := slice.AppendEmpty()
point.SetTimestamp(seconds(stamps[i]))
point.SetDoubleVal(val)
}
ctx := context.Background()
tr := newTranslator(t, zap.NewNop())
consumer := &mockTimeSeriesConsumer{}
tr.mapNumberMonotonicMetrics(ctx, consumer, exampleDims, slice)
assert.ElementsMatch(t,
consumer.metrics,
[]metric{
newCount(exampleDims, uint64(seconds(2)), 2),
newCount(exampleDims, uint64(seconds(3)), 1),
},
)
}
var _ SketchConsumer = (*mockFullConsumer)(nil)
type mockFullConsumer struct {
mockTimeSeriesConsumer
sketches []sketch
}
func (c *mockFullConsumer) ConsumeSketch(_ context.Context, dimensions *Dimensions, ts uint64, sk *quantile.Sketch) {
c.sketches = append(c.sketches,
sketch{
name: dimensions.Name(),
basic: sk.Basic,
timestamp: ts,
tags: dimensions.Tags(),
host: dimensions.Host(),
},
)
}
func dimsWithBucket(dims *Dimensions, lowerBound string, upperBound string) *Dimensions {
dims = dims.WithSuffix("bucket")
return dims.AddTags(
fmt.Sprintf("lower_bound:%s", lowerBound),
fmt.Sprintf("upper_bound:%s", upperBound),
)
}
func TestMapDeltaHistogramMetrics(t *testing.T) {
ts := pcommon.NewTimestampFromTime(time.Now())
slice := pmetric.NewHistogramDataPointSlice()
point := slice.AppendEmpty()
point.SetCount(20)
point.SetSum(math.Pi)
point.SetMBucketCounts([]uint64{2, 18})
point.SetMExplicitBounds([]float64{0})
point.SetTimestamp(ts)
dims := newDims("doubleHist.test")
dimsTags := dims.AddTags("attribute_tag:attribute_value")
counts := []metric{
newCount(dims.WithSuffix("count"), uint64(ts), 20),
newCount(dims.WithSuffix("sum"), uint64(ts), math.Pi),
}
countsAttributeTags := []metric{
newCount(dimsTags.WithSuffix("count"), uint64(ts), 20),
newCount(dimsTags.WithSuffix("sum"), uint64(ts), math.Pi),
}
bucketsCounts := []metric{
newCount(dimsWithBucket(dims, "-inf", "0"), uint64(ts), 2),
newCount(dimsWithBucket(dims, "0", "inf"), uint64(ts), 18),
}
bucketsCountsAttributeTags := []metric{
newCount(dimsWithBucket(dimsTags, "-inf", "0"), uint64(ts), 2),
newCount(dimsWithBucket(dimsTags, "0", "inf"), uint64(ts), 18),
}
sketches := []sketch{
newSketch(dims, uint64(ts), summary.Summary{
Min: 0,
Max: 0,
Sum: point.Sum(),
Avg: point.Sum() / float64(point.Count()),
Cnt: int64(point.Count()),
}),
}
sketchesAttributeTags := []sketch{
newSketch(dimsTags, uint64(ts), summary.Summary{
Min: 0,
Max: 0,
Sum: point.Sum(),
Avg: point.Sum() / float64(point.Count()),
Cnt: 20,
}),
}
ctx := context.Background()
delta := true
tests := []struct {
name string
histogramMode HistogramMode
sendCountSum bool
tags []string
expectedMetrics []metric
expectedSketches []sketch
}{
{
name: "No buckets: send count & sum metrics, no attribute tags",
histogramMode: HistogramModeNoBuckets,
sendCountSum: true,
expectedMetrics: counts,
expectedSketches: []sketch{},
},
{
name: "No buckets: send count & sum metrics, attribute tags",
histogramMode: HistogramModeNoBuckets,
sendCountSum: true,
tags: []string{"attribute_tag:attribute_value"},
expectedMetrics: countsAttributeTags,
expectedSketches: []sketch{},
},
{
name: "Counters: do not send count & sum metrics, no tags",
histogramMode: HistogramModeCounters,
sendCountSum: false,
tags: []string{},
expectedMetrics: bucketsCounts,
expectedSketches: []sketch{},
},
{
name: "Counters: do not send count & sum metrics, attribute tags",
histogramMode: HistogramModeCounters,
sendCountSum: false,
tags: []string{"attribute_tag:attribute_value"},
expectedMetrics: bucketsCountsAttributeTags,
expectedSketches: []sketch{},
},
{
name: "Counters: send count & sum metrics, no tags",
histogramMode: HistogramModeCounters,
sendCountSum: true,
tags: []string{},
expectedMetrics: append(counts, bucketsCounts...),
expectedSketches: []sketch{},
},
{
name: "Counters: send count & sum metrics, attribute tags",
histogramMode: HistogramModeCounters,
sendCountSum: true,
tags: []string{"attribute_tag:attribute_value"},
expectedMetrics: append(countsAttributeTags, bucketsCountsAttributeTags...),
expectedSketches: []sketch{},
},
{
name: "Distributions: do not send count & sum metrics, no tags",
histogramMode: HistogramModeDistributions,
sendCountSum: false,
tags: []string{},
expectedMetrics: []metric{},
expectedSketches: sketches,
},
{
name: "Distributions: do not send count & sum metrics, attribute tags",
histogramMode: HistogramModeDistributions,
sendCountSum: false,
tags: []string{"attribute_tag:attribute_value"},
expectedMetrics: []metric{},
expectedSketches: sketchesAttributeTags,
},
{
name: "Distributions: send count & sum metrics, no tags",
histogramMode: HistogramModeDistributions,
sendCountSum: true,
tags: []string{},
expectedMetrics: counts,
expectedSketches: sketches,
},
{
name: "Distributions: send count & sum metrics, attribute tags",
histogramMode: HistogramModeDistributions,
sendCountSum: true,
tags: []string{"attribute_tag:attribute_value"},
expectedMetrics: countsAttributeTags,
expectedSketches: sketchesAttributeTags,
},
}
for _, testInstance := range tests {
t.Run(testInstance.name, func(t *testing.T) {
tr := newTranslator(t, zap.NewNop())
tr.cfg.HistMode = testInstance.histogramMode
tr.cfg.SendCountSum = testInstance.sendCountSum
consumer := &mockFullConsumer{}
dims := &Dimensions{name: "doubleHist.test", tags: testInstance.tags}
tr.mapHistogramMetrics(ctx, consumer, dims, slice, delta)
assert.ElementsMatch(t, consumer.metrics, testInstance.expectedMetrics)
assert.ElementsMatch(t, consumer.sketches, testInstance.expectedSketches)
})
}
}
func TestMapCumulativeHistogramMetrics(t *testing.T) {
slice := pmetric.NewHistogramDataPointSlice()
point := slice.AppendEmpty()
point.SetCount(20)
point.SetSum(math.Pi)
point.SetMBucketCounts([]uint64{2, 18})
point.SetMExplicitBounds([]float64{0})
point.SetTimestamp(seconds(0))
point = slice.AppendEmpty()
point.SetCount(20 + 30)
point.SetSum(math.Pi + 20)
point.SetMBucketCounts([]uint64{2 + 11, 18 + 19})
point.SetMExplicitBounds([]float64{0})
point.SetTimestamp(seconds(2))
dims := newDims("doubleHist.test")
counts := []metric{
newCount(dims.WithSuffix("count"), uint64(seconds(2)), 30),
newCount(dims.WithSuffix("sum"), uint64(seconds(2)), 20),
}
bucketsCounts := []metric{
newCount(dimsWithBucket(dims, "-inf", "0"), uint64(seconds(2)), 11),
newCount(dimsWithBucket(dims, "0", "inf"), uint64(seconds(2)), 19),
}
sketches := []sketch{
newSketch(dims, uint64(seconds(2)), summary.Summary{
Min: 0,
Max: 0,
Sum: 20,
Avg: 20.0 / 30.0,
Cnt: 30,
}),
}
ctx := context.Background()
delta := false
tests := []struct {
name string
histogramMode HistogramMode
sendCountSum bool
expectedMetrics []metric
expectedSketches []sketch
}{
{
name: "No buckets: send count & sum metrics",
histogramMode: HistogramModeNoBuckets,
sendCountSum: true,
expectedMetrics: counts,
expectedSketches: []sketch{},
},
{
name: "Counters: do not send count & sum metrics",
histogramMode: HistogramModeCounters,
sendCountSum: false,
expectedMetrics: bucketsCounts,
expectedSketches: []sketch{},
},
{
name: "Counters: send count & sum metrics",
histogramMode: HistogramModeCounters,
sendCountSum: true,
expectedMetrics: append(counts, bucketsCounts...),
expectedSketches: []sketch{},
},
{
name: "Distributions: do not send count & sum metrics",
histogramMode: HistogramModeDistributions,
sendCountSum: false,
expectedMetrics: []metric{},
expectedSketches: sketches,
},
{
name: "Distributions: send count & sum metrics",
histogramMode: HistogramModeDistributions,
sendCountSum: true,
expectedMetrics: counts,
expectedSketches: sketches,
},
}
for _, testInstance := range tests {
t.Run(testInstance.name, func(t *testing.T) {
tr := newTranslator(t, zap.NewNop())
tr.cfg.HistMode = testInstance.histogramMode
tr.cfg.SendCountSum = testInstance.sendCountSum
consumer := &mockFullConsumer{}
dims := newDims("doubleHist.test")
tr.mapHistogramMetrics(ctx, consumer, dims, slice, delta)
assert.ElementsMatch(t, consumer.metrics, testInstance.expectedMetrics)
assert.ElementsMatch(t, consumer.sketches, testInstance.expectedSketches)
})
}
}
func TestLegacyBucketsTags(t *testing.T) {
// Test that passing the same tags slice doesn't reuse the slice.
ctx := context.Background()
tr := newTranslator(t, zap.NewNop())
tags := make([]string, 0, 10)
pointOne := pmetric.NewHistogramDataPoint()
pointOne.SetMBucketCounts([]uint64{2, 18})
pointOne.SetMExplicitBounds([]float64{0})
pointOne.SetTimestamp(seconds(0))
consumer := &mockTimeSeriesConsumer{}
dims := &Dimensions{name: "test.histogram.one", tags: tags}
tr.getLegacyBuckets(ctx, consumer, dims, pointOne, true)
seriesOne := consumer.metrics
pointTwo := pmetric.NewHistogramDataPoint()
pointTwo.SetMBucketCounts([]uint64{2, 18})
pointTwo.SetMExplicitBounds([]float64{1})
pointTwo.SetTimestamp(seconds(0))
consumer = &mockTimeSeriesConsumer{}
dims = &Dimensions{name: "test.histogram.two", tags: tags}
tr.getLegacyBuckets(ctx, consumer, dims, pointTwo, true)
seriesTwo := consumer.metrics
assert.ElementsMatch(t, seriesOne[0].tags, []string{"lower_bound:-inf", "upper_bound:0"})
assert.ElementsMatch(t, seriesTwo[0].tags, []string{"lower_bound:-inf", "upper_bound:1.0"})
}
func TestFormatFloat(t *testing.T) {
tests := []struct {
f float64
s string
}{
{f: 0, s: "0"},
{f: 0.001, s: "0.001"},
{f: 0.9, s: "0.9"},
{f: 0.95, s: "0.95"},
{f: 0.99, s: "0.99"},
{f: 0.999, s: "0.999"},
{f: 1, s: "1.0"},
{f: 2, s: "2.0"},
{f: math.Inf(1), s: "inf"},
{f: math.Inf(-1), s: "-inf"},
{f: math.NaN(), s: "nan"},
{f: 1e-10, s: "1e-10"},
}
for _, test := range tests {
assert.Equal(t, test.s, formatFloat(test.f))
}
}
func exampleSummaryDataPointSlice(ts pcommon.Timestamp, sum float64, count uint64) pmetric.SummaryDataPointSlice {
slice := pmetric.NewSummaryDataPointSlice()
point := slice.AppendEmpty()
point.SetCount(count)
point.SetSum(sum)
qSlice := point.QuantileValues()
qMin := qSlice.AppendEmpty()
qMin.SetQuantile(0.0)
qMin.SetValue(0)
qMedian := qSlice.AppendEmpty()
qMedian.SetQuantile(0.5)
qMedian.SetValue(100)
q999 := qSlice.AppendEmpty()
q999.SetQuantile(0.999)
q999.SetValue(500)
qMax := qSlice.AppendEmpty()
qMax.SetQuantile(1)
qMax.SetValue(600)
point.SetTimestamp(ts)
return slice
}
func TestMapSummaryMetrics(t *testing.T) {
ts := pcommon.NewTimestampFromTime(time.Now())
slice := exampleSummaryDataPointSlice(ts, 10_001, 101)
newTranslator := func(tags []string, quantiles bool) *Translator {
c := newTestCache()
c.cache.Set((&Dimensions{name: "summary.example.count", tags: tags}).String(), numberCounter{0, 0, 1}, gocache.NoExpiration)
c.cache.Set((&Dimensions{name: "summary.example.sum", tags: tags}).String(), numberCounter{0, 0, 1}, gocache.NoExpiration)
options := []Option{WithFallbackHostnameProvider(testProvider("fallbackHostname"))}
if quantiles {
options = append(options, WithQuantiles())
}
tr, err := New(zap.NewNop(), options...)
require.NoError(t, err)
tr.prevPts = c
return tr
}
dims := newDims("summary.example")
noQuantiles := []metric{
newCount(dims.WithSuffix("count"), uint64(ts), 100),
newCount(dims.WithSuffix("sum"), uint64(ts), 10_000),
}
qBaseDims := dims.WithSuffix("quantile")
quantiles := []metric{
newGauge(qBaseDims.AddTags("quantile:0"), uint64(ts), 0),
newGauge(qBaseDims.AddTags("quantile:0.5"), uint64(ts), 100),
newGauge(qBaseDims.AddTags("quantile:0.999"), uint64(ts), 500),
newGauge(qBaseDims.AddTags("quantile:1.0"), uint64(ts), 600),
}
ctx := context.Background()
tr := newTranslator([]string{}, false)
consumer := &mockTimeSeriesConsumer{}
tr.mapSummaryMetrics(ctx, consumer, dims, slice)
assert.ElementsMatch(t,
consumer.metrics,
noQuantiles,
)
tr = newTranslator([]string{}, true)
consumer = &mockTimeSeriesConsumer{}
tr.mapSummaryMetrics(ctx, consumer, dims, slice)
assert.ElementsMatch(t,
consumer.metrics,
append(noQuantiles, quantiles...),
)
dimsTags := dims.AddTags("attribute_tag:attribute_value")
noQuantilesAttr := []metric{
newCount(dimsTags.WithSuffix("count"), uint64(ts), 100),
newCount(dimsTags.WithSuffix("sum"), uint64(ts), 10_000),
}
qBaseDimsTags := dimsTags.WithSuffix("quantile")
quantilesAttr := []metric{
newGauge(qBaseDimsTags.AddTags("quantile:0"), uint64(ts), 0),
newGauge(qBaseDimsTags.AddTags("quantile:0.5"), uint64(ts), 100),
newGauge(qBaseDimsTags.AddTags("quantile:0.999"), uint64(ts), 500),
newGauge(qBaseDimsTags.AddTags("quantile:1.0"), uint64(ts), 600),
}
tr = newTranslator([]string{"attribute_tag:attribute_value"}, false)
consumer = &mockTimeSeriesConsumer{}
tr.mapSummaryMetrics(ctx, consumer, dimsTags, slice)
assert.ElementsMatch(t,
consumer.metrics,
noQuantilesAttr,
)
tr = newTranslator([]string{"attribute_tag:attribute_value"}, true)
consumer = &mockTimeSeriesConsumer{}
tr.mapSummaryMetrics(ctx, consumer, dimsTags, slice)
assert.ElementsMatch(t,
consumer.metrics,
append(noQuantilesAttr, quantilesAttr...),
)
}
const (
testHostname = "res-hostname"
)
func createTestMetrics(additionalAttributes map[string]string, name, version string) pmetric.Metrics {
md := pmetric.NewMetrics()
rms := md.ResourceMetrics()
rm := rms.AppendEmpty()
attrs := rm.Resource().Attributes()
attrs.InsertString(attributes.AttributeDatadogHostname, testHostname)
for attr, val := range additionalAttributes {
attrs.InsertString(attr, val)
}
ilms := rm.ScopeMetrics()
ilm := ilms.AppendEmpty()
ilm.Scope().SetName(name)
ilm.Scope().SetVersion(version)
metricsArray := ilm.Metrics()
metricsArray.AppendEmpty() // first one is TypeNone to test that it's ignored
// IntGauge
met := metricsArray.AppendEmpty()
met.SetName("int.gauge")
met.SetDataType(pmetric.MetricDataTypeGauge)
dpsInt := met.Gauge().DataPoints()
dpInt := dpsInt.AppendEmpty()
dpInt.SetTimestamp(seconds(0))
dpInt.SetIntVal(1)
// DoubleGauge
met = metricsArray.AppendEmpty()
met.SetName("double.gauge")
met.SetDataType(pmetric.MetricDataTypeGauge)
dpsDouble := met.Gauge().DataPoints()