forked from open-telemetry/opentelemetry-collector-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_utils.go
348 lines (307 loc) · 9.35 KB
/
test_utils.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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Package testutil contains the test util functions
package testutil // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/datadogexporter/internal/testutil"
import (
"context"
"encoding/json"
"io"
"log"
"net/http"
"net/http/httptest"
pb "github.com/DataDog/datadog-agent/pkg/proto/pbgo/trace"
"github.com/DataDog/opentelemetry-mapping-go/pkg/otlp/attributes/source"
"github.com/DataDog/sketches-go/ddsketch"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/pmetric"
"go.opentelemetry.io/collector/pdata/ptrace"
"google.golang.org/protobuf/proto"
)
var (
testAttributes = map[string]string{"datadog.host.name": "custom-hostname"}
// TestMetrics metrics for tests.
TestMetrics = newMetricsWithAttributeMap(testAttributes)
// TestTraces traces for tests.
TestTraces = newTracesWithAttributeMap(testAttributes)
)
type DatadogServer struct {
*httptest.Server
MetadataChan chan []byte
}
/* #nosec G101 -- This is a false positive, these are API endpoints rather than credentials */
const (
ValidateAPIKeyEndpoint = "/api/v1/validate" // nolint G101
MetricV1Endpoint = "/api/v1/series"
MetricV2Endpoint = "/api/v2/series"
SketchesMetricEndpoint = "/api/beta/sketches"
MetadataEndpoint = "/intake"
TraceEndpoint = "/api/v0.2/traces"
APMStatsEndpoint = "/api/v0.2/stats"
)
// DatadogServerMock mocks a Datadog backend server
func DatadogServerMock(overwriteHandlerFuncs ...OverwriteHandleFunc) *DatadogServer {
metadataChan := make(chan []byte)
mux := http.NewServeMux()
handlers := map[string]http.HandlerFunc{
ValidateAPIKeyEndpoint: validateAPIKeyEndpoint,
MetricV1Endpoint: metricsEndpoint,
MetricV2Endpoint: metricsV2Endpoint,
MetadataEndpoint: newMetadataEndpoint(metadataChan),
"/": func(_ http.ResponseWriter, _ *http.Request) {},
}
for _, f := range overwriteHandlerFuncs {
p, hf := f()
handlers[p] = hf
}
for pattern, handler := range handlers {
mux.HandleFunc(pattern, handler)
}
srv := httptest.NewServer(mux)
return &DatadogServer{
srv,
metadataChan,
}
}
// OverwriteHandleFuncs allows to overwrite the default handler functions
type OverwriteHandleFunc func() (string, http.HandlerFunc)
// HTTPRequestRecorder records a HTTP request.
type HTTPRequestRecorder struct {
Pattern string
Header http.Header
ByteBody []byte
}
func (rec *HTTPRequestRecorder) HandlerFunc() (string, http.HandlerFunc) {
return rec.Pattern, func(_ http.ResponseWriter, r *http.Request) {
rec.Header = r.Header
rec.ByteBody, _ = io.ReadAll(r.Body)
}
}
// HTTPRequestRecorderWithChan puts all incoming HTTP request bytes to the given channel.
type HTTPRequestRecorderWithChan struct {
Pattern string
ReqChan chan []byte
}
func (rec *HTTPRequestRecorderWithChan) HandlerFunc() (string, http.HandlerFunc) {
return rec.Pattern, func(_ http.ResponseWriter, r *http.Request) {
bytesBody, _ := io.ReadAll(r.Body)
rec.ReqChan <- bytesBody
}
}
// ValidateAPIKeyEndpointInvalid returns a handler function that returns an invalid API key response
func ValidateAPIKeyEndpointInvalid() (string, http.HandlerFunc) {
return "/api/v1/validate", validateAPIKeyEndpointInvalid
}
type validateAPIKeyResponse struct {
Valid bool `json:"valid"`
}
func validateAPIKeyEndpoint(w http.ResponseWriter, _ *http.Request) {
res := validateAPIKeyResponse{Valid: true}
resJSON, _ := json.Marshal(res)
w.Header().Set("Content-Type", "application/json")
_, err := w.Write(resJSON)
if err != nil {
log.Fatalln(err)
}
}
func validateAPIKeyEndpointInvalid(w http.ResponseWriter, _ *http.Request) {
res := validateAPIKeyResponse{Valid: false}
resJSON, _ := json.Marshal(res)
w.Header().Set("Content-Type", "application/json")
_, err := w.Write(resJSON)
if err != nil {
log.Fatalln(err)
}
}
type metricsResponse struct {
Status string `json:"status"`
}
func metricsEndpoint(w http.ResponseWriter, _ *http.Request) {
res := metricsResponse{Status: "ok"}
resJSON, _ := json.Marshal(res)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
_, err := w.Write(resJSON)
if err != nil {
log.Fatalln(err)
}
}
func metricsV2Endpoint(w http.ResponseWriter, _ *http.Request) {
res := metricsResponse{Status: "ok"}
resJSON, _ := json.Marshal(res)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
_, err := w.Write(resJSON)
if err != nil {
log.Fatalln(err)
}
}
func newMetadataEndpoint(c chan []byte) func(http.ResponseWriter, *http.Request) {
return func(_ http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
c <- body
}
}
func fillAttributeMap(attrs pcommon.Map, mp map[string]string) {
attrs.EnsureCapacity(len(mp))
for k, v := range mp {
attrs.PutStr(k, v)
}
}
// NewAttributeMap creates a new attribute map (string only)
// from a Go map
func NewAttributeMap(mp map[string]string) pcommon.Map {
attrs := pcommon.NewMap()
fillAttributeMap(attrs, mp)
return attrs
}
// TestGauge holds the definition of a basic gauge.
type TestGauge struct {
Name string
DataPoints []DataPoint
}
// DataPoint specifies a DoubleVal data point and its attributes.
type DataPoint struct {
Value float64
Attributes map[string]string
}
// NewGaugeMetrics creates a set of pmetric.Metrics containing all the specified
// test gauges.
func NewGaugeMetrics(tgs []TestGauge) pmetric.Metrics {
metrics := pmetric.NewMetrics()
all := metrics.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
for _, tg := range tgs {
m := all.AppendEmpty()
m.SetName(tg.Name)
g := m.SetEmptyGauge()
for _, dp := range tg.DataPoints {
d := g.DataPoints().AppendEmpty()
d.SetDoubleValue(dp.Value)
fillAttributeMap(d.Attributes(), dp.Attributes)
}
}
return metrics
}
func newMetricsWithAttributeMap(mp map[string]string) pmetric.Metrics {
md := pmetric.NewMetrics()
fillAttributeMap(md.ResourceMetrics().AppendEmpty().Resource().Attributes(), mp)
return md
}
func newTracesWithAttributeMap(mp map[string]string) ptrace.Traces {
traces := ptrace.NewTraces()
resourceSpans := traces.ResourceSpans()
rs := resourceSpans.AppendEmpty()
fillAttributeMap(rs.Resource().Attributes(), mp)
rs.ScopeSpans().AppendEmpty().Spans().AppendEmpty()
return traces
}
type MockSourceProvider struct {
Src source.Source
}
func (s *MockSourceProvider) Source(_ context.Context) (source.Source, error) {
return s.Src, nil
}
type MockStatsProcessor struct {
In []*pb.ClientStatsPayload
}
func (s *MockStatsProcessor) ProcessStats(in *pb.ClientStatsPayload, _, _ string) {
s.In = append(s.In, in)
}
// StatsPayloads contains a couple of *pb.ClientStatsPayloads used for testing.
var StatsPayloads = []*pb.ClientStatsPayload{
{
Hostname: "host",
Env: "prod",
Version: "v1.2",
Lang: "go",
TracerVersion: "v44",
RuntimeID: "123jkl",
Sequence: 2,
AgentAggregation: "blah",
Service: "mysql",
ContainerID: "abcdef123456",
Tags: []string{"a:b", "c:d"},
Stats: []*pb.ClientStatsBucket{
{
Start: 10,
Duration: 1,
Stats: []*pb.ClientGroupedStats{
{
Service: "kafka",
Name: "queue.add",
Resource: "append",
HTTPStatusCode: 220,
Type: "queue",
Hits: 15,
Errors: 3,
Duration: 143,
OkSummary: testSketchBytes(1, 2, 3),
ErrorSummary: testSketchBytes(4, 5, 6),
TopLevelHits: 5,
},
},
},
},
},
{
Hostname: "host2",
Env: "prod2",
Version: "v1.22",
Lang: "go2",
TracerVersion: "v442",
RuntimeID: "123jkl2",
Sequence: 22,
AgentAggregation: "blah2",
Service: "mysql2",
ContainerID: "abcdef1234562",
Tags: []string{"a:b2", "c:d2"},
Stats: []*pb.ClientStatsBucket{
{
Start: 102,
Duration: 12,
Stats: []*pb.ClientGroupedStats{
{
Service: "kafka2",
Name: "queue.add2",
Resource: "append2",
HTTPStatusCode: 2202,
Type: "queue2",
Hits: 152,
Errors: 32,
Duration: 1432,
OkSummary: testSketchBytes(7, 8),
ErrorSummary: testSketchBytes(9, 10, 11),
TopLevelHits: 52,
},
},
},
},
},
}
// The sketch's relative accuracy and maximum number of bins is identical
// to the one used in the trace-agent for consistency:
// https://github.com/DataDog/datadog-agent/blob/cbac965/pkg/trace/stats/statsraw.go#L18-L26
const (
sketchRelativeAccuracy = 0.01
sketchMaxBins = 2048
)
// testSketchBytes returns the proto-encoded version of a DDSketch containing the
// points in nums.
func testSketchBytes(nums ...float64) []byte {
sketch, err := ddsketch.LogCollapsingLowestDenseDDSketch(sketchRelativeAccuracy, sketchMaxBins)
if err != nil {
// the only possible error is if the relative accuracy is < 0 or > 1;
// we know that's not the case because it's a constant defined as 0.01
panic(err)
}
for _, num := range nums {
if err2 := sketch.Add(num); err2 != nil {
panic(err2)
}
}
buf, err := proto.Marshal(sketch.ToProto())
if err != nil {
// there should be no error under any circumstances here
panic(err)
}
return buf
}