Debian Codegraph @

processor/processorhelper/metrics.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package processorhelper // import "go.opentelemetry.io/collector/processor/processorhelper"
5
6 import (
7 "context"
8 "errors"
9 "time"
10
11 "go.opentelemetry.io/otel/trace"
12
13 "go.opentelemetry.io/collector/component"
14 "go.opentelemetry.io/collector/consumer"
15 "go.opentelemetry.io/collector/pdata/pmetric"
16 "go.opentelemetry.io/collector/pipeline"
17 "go.opentelemetry.io/collector/processor"
18 )
19
20 // ProcessMetricsFunc is a helper function that processes the incoming data and returns the data to be sent to the next component.
21 // If error is returned then returned data are ignored. It MUST not call the next component.
22 type ProcessMetricsFunc func(context.Context, pmetric.Metrics) (pmetric.Metrics, error)
23
24 type metrics struct {
25 component.StartFunc
26 component.ShutdownFunc
27 consumer.Metrics
28 }
29
30 // NewMetrics creates a processor.Metrics that ensure context propagation and the right tags are set.
31 func NewMetrics(
32 _ context.Context,
33 set processor.Settings,
34 _ component.Config,
35 nextConsumer consumer.Metrics,
36 metricsFunc ProcessMetricsFunc,
37 options ...Option,
38 ) (processor.Metrics, error) {
39 if metricsFunc == nil {
40 return nil, errors.New("nil metricsFunc")
41 }
42
43 obs, err := newObsReport(set, pipeline.SignalMetrics)
44 if err != nil {
45 return nil, err
46 }
47
48 eventOptions := spanAttributes(set.ID)
49 bs := fromOptions(options)
50 metricsConsumer, err := consumer.NewMetrics(func(ctx context.Context, md pmetric.Metrics) error {
51 span := trace.SpanFromContext(ctx)
52 span.AddEvent("Start processing.", eventOptions)
53
54 startTime := time.Now()
55
56 pointsIn := md.DataPointCount()
57
58 var errFunc error
59 md, errFunc = metricsFunc(ctx, md)
60 obs.recordInternalDuration(ctx, startTime)
61 span.AddEvent("End processing.", eventOptions)
62 if errFunc != nil {
63 obs.recordInOut(ctx, pointsIn, 0)
64 if errors.Is(errFunc, ErrSkipProcessingData) {
65 return nil
66 }
67 return errFunc
68 }
69 pointsOut := md.DataPointCount()
70 obs.recordInOut(ctx, pointsIn, pointsOut)
71 return nextConsumer.ConsumeMetrics(ctx, md)
72 }, bs.consumerOptions...)
73 if err != nil {
74 return nil, err
75 }
76
77 return &metrics{
78 StartFunc: bs.StartFunc,
79 ShutdownFunc: bs.ShutdownFunc,
80 Metrics: metricsConsumer,
81 }, nil
82 }