Debian Codegraph @

receiver/receivertest/contract_checker.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package receivertest // import "go.opentelemetry.io/collector/receiver/receivertest"
5
6 import (
7 "context"
8 "errors"
9 "fmt"
10 "maps"
11 "math/rand/v2"
12 "sync"
13 "sync/atomic"
14 "testing"
15 "time"
16
17 "github.com/stretchr/testify/assert"
18 "github.com/stretchr/testify/require"
19
20 "go.opentelemetry.io/collector/component"
21 "go.opentelemetry.io/collector/component/componenttest"
22 "go.opentelemetry.io/collector/consumer"
23 "go.opentelemetry.io/collector/consumer/consumererror"
24 "go.opentelemetry.io/collector/pdata/pcommon"
25 "go.opentelemetry.io/collector/pdata/plog"
26 "go.opentelemetry.io/collector/pdata/pmetric"
27 "go.opentelemetry.io/collector/pdata/ptrace"
28 "go.opentelemetry.io/collector/pipeline"
29 "go.opentelemetry.io/collector/receiver"
30 )
31
32 // UniqueIDAttrName is the attribute name that is used in log records/spans/datapoints as the unique identifier.
33 const UniqueIDAttrName = "test_id"
34
35 // UniqueIDAttrVal is the value type of the UniqueIDAttrName.
36 type UniqueIDAttrVal string
37
38 type Generator interface {
39 // Start the generator and prepare to generate. Will be followed by calls to Generate().
40 // Start() may be called again after Stop() is called to begin a new test scenario.
41 Start()
42
43 // Stop generating. There will be no more calls to Generate() until Start() is called again.
44 Stop()
45
46 // Generate must generate and send at least one data element (span, log record or metric data point)
47 // to the receiver and return a copy of generated element ids.
48 // The generated data must contain uniquely identifiable elements, each with a
49 // different value of attribute named UniqueIDAttrName.
50 // CreateOneLogWithID() can be used a helper to create such logs.
51 // May be called concurrently from multiple goroutines.
52 Generate() []UniqueIDAttrVal
53 }
54
55 type CheckConsumeContractParams struct {
56 T *testing.T
57 // Factory that allows to create a receiver.
58 Factory receiver.Factory
59 Signal pipeline.Signal
60 // Config of the receiver to use.
61 Config component.Config
62 // Generator that can send data to the receiver.
63 Generator Generator
64 // GenerateCount specifies the number of times to call the generator.Generate()
65 // for each test scenario.
66 GenerateCount int
67 // prevent unkeyed literal initialization
68 _ struct{}
69 }
70
71 // CheckConsumeContract checks the contract between the receiver and its next consumer. For the contract
72 // description see ../doc.go. The checker will detect violations of contract on different scenarios: on success,
73 // on permanent and non-permanent errors and mix of error types.
74 func CheckConsumeContract(params CheckConsumeContractParams) {
75 // Different scenarios to test for.
76 // The decision function defines the testing scenario (i.e. to test for
77 // success case or for error case or a mix of both). See for example randomErrorsConsumeDecision.
78 scenarios := []struct {
79 name string
80 decisionFunc func(ids idSet) error
81 }{
82 {
83 name: "always_succeed",
84 // Always succeed. We expect all data to be delivered as is.
85 decisionFunc: func(idSet) error { return nil },
86 },
87 {
88 name: "random_non_permanent_error",
89 decisionFunc: randomNonPermanentErrorConsumeDecision,
90 },
91 {
92 name: "random_permanent_error",
93 decisionFunc: randomPermanentErrorConsumeDecision,
94 },
95 {
96 name: "random_error",
97 decisionFunc: randomErrorsConsumeDecision,
98 },
99 }
100
101 for _, scenario := range scenarios {
102 params.T.Run(
103 scenario.name, func(*testing.T) {
104 checkConsumeContractScenario(params, scenario.decisionFunc)
105 },
106 )
107 }
108 }
109
110 func checkConsumeContractScenario(params CheckConsumeContractParams, decisionFunc func(ids idSet) error) {
111 consumer := &mockConsumer{t: params.T, consumeDecisionFunc: decisionFunc, acceptedIDs: make(idSet), droppedIDs: make(idSet)}
112 ctx := context.Background()
113
114 // Create and start the receiver.
115 var receiver component.Component
116 var err error
117 switch params.Signal {
118 case pipeline.SignalLogs:
119 receiver, err = params.Factory.CreateLogs(ctx, NewNopSettings(params.Factory.Type()), params.Config, consumer)
120 case pipeline.SignalTraces:
121 receiver, err = params.Factory.CreateTraces(ctx, NewNopSettings(params.Factory.Type()), params.Config, consumer)
122 case pipeline.SignalMetrics:
123 receiver, err = params.Factory.CreateMetrics(ctx, NewNopSettings(params.Factory.Type()), params.Config, consumer)
124 default:
125 require.FailNow(params.T, "must specify a valid DataType to test for")
126 }
127
128 require.NoError(params.T, err)
129
130 err = receiver.Start(ctx, componenttest.NewNopHost())
131 require.NoError(params.T, err)
132
133 // Begin generating data to the receiver.
134
135 generatedIDs := make(idSet)
136 var generatedIndex int64
137 var mux sync.Mutex
138 var wg sync.WaitGroup
139
140 const concurrency = 4
141
142 params.Generator.Start()
143 defer params.Generator.Stop()
144
145 // Create concurrent goroutines that use the generator.
146 // The total number of generator calls will be equal to params.GenerateCount.
147
148 for range concurrency {
149 wg.Add(1)
150 go func() {
151 defer wg.Done()
152 for atomic.AddInt64(&generatedIndex, 1) <= int64(params.GenerateCount) {
153 ids := params.Generator.Generate()
154 require.NotEmpty(params.T, ids)
155
156 mux.Lock()
157 duplicates := generatedIDs.mergeSlice(ids)
158 mux.Unlock()
159
160 // Check that the generator works correctly. There may not be any duplicates in the
161 // generated data set.
162 require.Empty(params.T, duplicates)
163 }
164 }()
165 }
166
167 // Wait until all generator goroutines are done.
168 wg.Wait()
169
170 // Wait until all data is seen by the consumer.
171 assert.Eventually(params.T, func() bool {
172 // Calculate the union of accepted and dropped data.
173 acceptedAndDropped, duplicates := consumer.acceptedAndDropped()
174 if len(duplicates) != 0 {
175 assert.Failf(params.T, "found duplicate elements in received and dropped data", "keys=%v", duplicates)
176 }
177 // Compare accepted+dropped with generated. Once they are equal it means all data is seen by the consumer.
178 missingInOther, onlyInOther := generatedIDs.compare(acceptedAndDropped)
179 return len(missingInOther) == 0 && len(onlyInOther) == 0
180 }, 5*time.Second, 10*time.Millisecond)
181
182 // Do some final checks. Need the union of accepted and dropped data again.
183 acceptedAndDropped, duplicates := consumer.acceptedAndDropped()
184 if len(duplicates) != 0 {
185 assert.Failf(params.T, "found duplicate elements in accepted and dropped data", "keys=%v", duplicates)
186 }
187
188 // Make sure generated and accepted+dropped are exactly the same.
189
190 missingInOther, onlyInOther := generatedIDs.compare(acceptedAndDropped)
191 if len(missingInOther) != 0 {
192 assert.Failf(params.T, "found elements sent that were not delivered", "keys=%v", missingInOther)
193 }
194 if len(onlyInOther) != 0 {
195 assert.Failf(params.T, "found elements in accepted and dropped data that was never sent", "keys=%v", onlyInOther)
196 }
197
198 err = receiver.Shutdown(ctx)
199 require.NoError(params.T, err)
200
201 // Print some stats to help debug test failures.
202 fmt.Printf(
203 "Sent %d, accepted=%d, expected dropped=%d, non-permanent errors retried=%d\n",
204 len(generatedIDs),
205 len(consumer.acceptedIDs),
206 len(consumer.droppedIDs),
207 consumer.nonPermanentFailures,
208 )
209 }
210
211 // idSet is a set of unique ids of data elements used in the test (logs, spans or metric data points).
212 type idSet map[UniqueIDAttrVal]bool
213
214 // compare to another set and calculate the differences from this set.
215 func (ds idSet) compare(other idSet) (missingInOther, onlyInOther []UniqueIDAttrVal) {
216 for k := range ds {
217 if _, ok := other[k]; !ok {
218 missingInOther = append(missingInOther, k)
219 }
220 }
221 for k := range other {
222 if _, ok := ds[k]; !ok {
223 onlyInOther = append(onlyInOther, k)
224 }
225 }
226 return missingInOther, onlyInOther
227 }
228
229 // merge another set into this one and return a list of duplicate ids.
230 func (ds idSet) merge(other idSet) (duplicates []UniqueIDAttrVal) {
231 for k, v := range other {
232 if _, ok := ds[k]; ok {
233 duplicates = append(duplicates, k)
234 } else {
235 ds[k] = v
236 }
237 }
238 return duplicates
239 }
240
241 // mergeSlice merges another set into this one and return a list of duplicate ids.
242 func (ds idSet) mergeSlice(other []UniqueIDAttrVal) (duplicates []UniqueIDAttrVal) {
243 for _, id := range other {
244 if _, ok := ds[id]; ok {
245 duplicates = append(duplicates, id)
246 } else {
247 ds[id] = true
248 }
249 }
250 return duplicates
251 }
252
253 // union computes the union of this and another sets. A new set if created to return the result.
254 // Also returns a list of any duplicate ids found.
255 func (ds idSet) union(other idSet) (union idSet, duplicates []UniqueIDAttrVal) {
256 union = map[UniqueIDAttrVal]bool{}
257 maps.Copy(union, ds)
258 for k, v := range other {
259 if _, ok := union[k]; ok {
260 duplicates = append(duplicates, k)
261 } else {
262 union[k] = v
263 }
264 }
265 return union, duplicates
266 }
267
268 // A function that returns a value indicating what the receiver's next consumer decides
269 // to do as a result of ConsumeLogs/Trace/Metrics call.
270 // The result of the decision function becomes the return value of ConsumeLogs/Trace/Metrics.
271 // Supplying different decision functions allows to test different scenarios of the contract
272 // between the receiver and it next consumer.
273 type consumeDecisionFunc func(ids idSet) error
274
275 var (
276 errNonPermanent = errors.New("non permanent error")
277 errPermanent = errors.New("permanent error")
278 )
279
280 // randomNonPermanentErrorConsumeDecision is a decision function that succeeds approximately
281 // half of the time and fails with a non-permanent error the rest of the time.
282 func randomNonPermanentErrorConsumeDecision(idSet) error {
283 if rand.Float32() < 0.5 {
284 return errNonPermanent
285 }
286 return nil
287 }
288
289 // randomPermanentErrorConsumeDecision is a decision function that succeeds approximately
290 // half of the time and fails with a permanent error the rest of the time.
291 func randomPermanentErrorConsumeDecision(idSet) error {
292 if rand.Float32() < 0.5 {
293 return consumererror.NewPermanent(errPermanent)
294 }
295 return nil
296 }
297
298 // randomErrorsConsumeDecision is a decision function that succeeds approximately
299 // a third of the time, fails with a permanent error the third of the time and fails with
300 // a non-permanent error the rest of the time.
301 func randomErrorsConsumeDecision(idSet) error {
302 r := rand.Float64()
303 third := 1.0 / 3.0
304 if r < third {
305 return consumererror.NewPermanent(errPermanent)
306 }
307 if r < 2*third {
308 return errNonPermanent
309 }
310 return nil
311 }
312
313 // mockConsumer accepts or drops the data from the receiver based on the decision made by
314 // consumeDecisionFunc and remembers the accepted and dropped data sets for later checks.
315 // mockConsumer implements all 3 consume functions: ConsumeLogs/ConsumeTraces/ConsumeMetrics
316 // and can be used for testing any of the 3 signals.
317 type mockConsumer struct {
318 t *testing.T
319 consumeDecisionFunc consumeDecisionFunc
320 mux sync.Mutex
321 acceptedIDs idSet
322 droppedIDs idSet
323 nonPermanentFailures int
324 }
325
326 func (m *mockConsumer) Capabilities() consumer.Capabilities {
327 return consumer.Capabilities{}
328 }
329
330 func (m *mockConsumer) ConsumeTraces(_ context.Context, data ptrace.Traces) error {
331 ids, err := idSetFromTraces(data)
332 require.NoError(m.t, err)
333 return m.consume(ids)
334 }
335
336 // idSetFromTraces computes an idSet from given ptrace.Traces. The idSet will contain ids of all spans.
337 func idSetFromTraces(data ptrace.Traces) (idSet, error) {
338 ds := map[UniqueIDAttrVal]bool{}
339 rss := data.ResourceSpans()
340 for i := 0; i < rss.Len(); i++ {
341 ils := rss.At(i).ScopeSpans()
342 for j := 0; j < ils.Len(); j++ {
343 ss := ils.At(j).Spans()
344 for k := 0; k < ss.Len(); k++ {
345 elem := ss.At(k)
346 key, exists := elem.Attributes().Get(UniqueIDAttrName)
347 if !exists {
348 return ds, fmt.Errorf("invalid data element, attribute %q is missing", UniqueIDAttrName)
349 }
350 if key.Type() != pcommon.ValueTypeStr {
351 return ds, fmt.Errorf("invalid data element, attribute %q is wrong type %v", UniqueIDAttrName, key.Type())
352 }
353 ds[UniqueIDAttrVal(key.Str())] = true
354 }
355 }
356 }
357 return ds, nil
358 }
359
360 func (m *mockConsumer) ConsumeLogs(_ context.Context, data plog.Logs) error {
361 ids, err := idSetFromLogs(data)
362 require.NoError(m.t, err)
363 return m.consume(ids)
364 }
365
366 // idSetFromLogs computes an idSet from given plog.Logs. The idSet will contain ids of all log records.
367 func idSetFromLogs(data plog.Logs) (idSet, error) {
368 ds := map[UniqueIDAttrVal]bool{}
369 rss := data.ResourceLogs()
370 for i := 0; i < rss.Len(); i++ {
371 ils := rss.At(i).ScopeLogs()
372 for j := 0; j < ils.Len(); j++ {
373 ss := ils.At(j).LogRecords()
374 for k := 0; k < ss.Len(); k++ {
375 elem := ss.At(k)
376 key, exists := elem.Attributes().Get(UniqueIDAttrName)
377 if !exists {
378 return ds, fmt.Errorf("invalid data element, attribute %q is missing", UniqueIDAttrName)
379 }
380 if key.Type() != pcommon.ValueTypeStr {
381 return ds, fmt.Errorf("invalid data element, attribute %q is wrong type %v", UniqueIDAttrName, key.Type())
382 }
383 ds[UniqueIDAttrVal(key.Str())] = true
384 }
385 }
386 }
387 return ds, nil
388 }
389
390 func (m *mockConsumer) ConsumeMetrics(_ context.Context, data pmetric.Metrics) error {
391 ids, err := idSetFromMetrics(data)
392 require.NoError(m.t, err)
393 return m.consume(ids)
394 }
395
396 // idSetFromMetrics computes an idSet from given pmetric.Metrics. The idSet will contain ids of all metric data points.
397 func idSetFromMetrics(data pmetric.Metrics) (idSet, error) {
398 ds := map[UniqueIDAttrVal]bool{}
399 rss := data.ResourceMetrics()
400 for i := 0; i < rss.Len(); i++ {
401 ils := rss.At(i).ScopeMetrics()
402 for j := 0; j < ils.Len(); j++ {
403 ss := ils.At(j).Metrics()
404 for k := 0; k < ss.Len(); k++ {
405 elem := ss.At(k)
406 switch elem.Type() {
407 case pmetric.MetricTypeGauge:
408 for l := 0; l < elem.Gauge().DataPoints().Len(); l++ {
409 dp := elem.Gauge().DataPoints().At(l)
410 if err := idSetFromDataPoint(ds, dp.Attributes()); err != nil {
411 return ds, err
412 }
413 }
414 case pmetric.MetricTypeSum:
415 for l := 0; l < elem.Sum().DataPoints().Len(); l++ {
416 dp := elem.Sum().DataPoints().At(l)
417 if err := idSetFromDataPoint(ds, dp.Attributes()); err != nil {
418 return ds, err
419 }
420 }
421 case pmetric.MetricTypeSummary:
422 for l := 0; l < elem.Summary().DataPoints().Len(); l++ {
423 dp := elem.Summary().DataPoints().At(l)
424 if err := idSetFromDataPoint(ds, dp.Attributes()); err != nil {
425 return ds, err
426 }
427 }
428 case pmetric.MetricTypeHistogram:
429 for l := 0; l < elem.Histogram().DataPoints().Len(); l++ {
430 dp := elem.Histogram().DataPoints().At(l)
431 if err := idSetFromDataPoint(ds, dp.Attributes()); err != nil {
432 return ds, err
433 }
434 }
435 case pmetric.MetricTypeExponentialHistogram:
436 for l := 0; l < elem.ExponentialHistogram().DataPoints().Len(); l++ {
437 dp := elem.ExponentialHistogram().DataPoints().At(l)
438 if err := idSetFromDataPoint(ds, dp.Attributes()); err != nil {
439 return ds, err
440 }
441 }
442 }
443 }
444 }
445 }
446 return ds, nil
447 }
448
449 func idSetFromDataPoint(ds map[UniqueIDAttrVal]bool, attributes pcommon.Map) error {
450 key, exists := attributes.Get(UniqueIDAttrName)
451 if !exists {
452 return fmt.Errorf("invalid data element, attribute %q is missing", UniqueIDAttrName)
453 }
454 if key.Type() != pcommon.ValueTypeStr {
455 return fmt.Errorf("invalid data element, attribute %q is wrong type %v", UniqueIDAttrName, key.Type())
456 }
457 ds[UniqueIDAttrVal(key.Str())] = true
458 return nil
459 }
460
461 // consume the elements with the specified ids, regardless of the element data type.
462 func (m *mockConsumer) consume(ids idSet) error {
463 m.mux.Lock()
464 defer m.mux.Unlock()
465
466 // Consult with user-defined decision function to decide what to do with the data.
467 if err := m.consumeDecisionFunc(ids); err != nil {
468 // The decision is to return an error to the receiver.
469
470 if consumererror.IsPermanent(err) {
471 // It is a permanent error, which means we need to drop the data.
472 // Remember the ids of dropped elements.
473 duplicates := m.droppedIDs.merge(ids)
474 require.Empty(m.t, duplicates, "elements that were dropped previously were sent again")
475 } else {
476 // It is a non-permanent error. Don't add it to the drop list. Remember the number of
477 // failures to print at the end of the test.
478 m.nonPermanentFailures++
479 }
480 // Return the error to the receiver.
481 return err
482 }
483
484 // The decision is a success. Remember the ids of the data in the accepted list.
485 duplicates := m.acceptedIDs.merge(ids)
486 require.Empty(m.t, duplicates, "elements that were accepted previously were sent again")
487 return nil
488 }
489
490 // Calculate union of accepted and dropped ids.
491 // Returns the union and the list of duplicates between the two sets (if any)
492 func (m *mockConsumer) acceptedAndDropped() (acceptedAndDropped idSet, duplicates []UniqueIDAttrVal) {
493 m.mux.Lock()
494 defer m.mux.Unlock()
495 return m.acceptedIDs.union(m.droppedIDs)
496 }
497
498 func CreateOneLogWithID(id UniqueIDAttrVal) plog.Logs {
499 data := plog.NewLogs()
500 data.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty().Attributes().PutStr(
501 UniqueIDAttrName,
502 string(id),
503 )
504 return data
505 }
506
507 func CreateGaugeMetricWithID(id UniqueIDAttrVal) pmetric.Metrics {
508 data := pmetric.NewMetrics()
509 gauge := data.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
510 gauge.AppendEmpty().SetEmptyGauge().DataPoints().AppendEmpty().Attributes().PutStr(
511 UniqueIDAttrName,
512 string(id),
513 )
514 return data
515 }
516
517 func CreateSumMetricWithID(id UniqueIDAttrVal) pmetric.Metrics {
518 data := pmetric.NewMetrics()
519 sum := data.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
520 sum.AppendEmpty().SetEmptySum().DataPoints().AppendEmpty().Attributes().PutStr(
521 UniqueIDAttrName,
522 string(id),
523 )
524 return data
525 }
526
527 func CreateSummaryMetricWithID(id UniqueIDAttrVal) pmetric.Metrics {
528 data := pmetric.NewMetrics()
529 summary := data.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
530 summary.AppendEmpty().SetEmptySummary().DataPoints().AppendEmpty().Attributes().PutStr(
531 UniqueIDAttrName,
532 string(id),
533 )
534 return data
535 }
536
537 func CreateHistogramMetricWithID(id UniqueIDAttrVal) pmetric.Metrics {
538 data := pmetric.NewMetrics()
539 histogram := data.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
540 histogram.AppendEmpty().SetEmptyHistogram().DataPoints().AppendEmpty().Attributes().PutStr(
541 UniqueIDAttrName,
542 string(id),
543 )
544 return data
545 }
546
547 func CreateExponentialHistogramMetricWithID(id UniqueIDAttrVal) pmetric.Metrics {
548 data := pmetric.NewMetrics()
549 exponentialHistogram := data.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()
550 exponentialHistogram.AppendEmpty().SetEmptyExponentialHistogram().DataPoints().AppendEmpty().Attributes().PutStr(
551 UniqueIDAttrName,
552 string(id),
553 )
554 return data
555 }
556
557 func CreateOneSpanWithID(id UniqueIDAttrVal) ptrace.Traces {
558 data := ptrace.NewTraces()
559 data.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans().AppendEmpty().Attributes().PutStr(
560 UniqueIDAttrName,
561 string(id),
562 )
563 return data
564 }