| 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/ptrace" |
| 16 |
"go.opentelemetry.io/collector/pipeline" |
| 17 |
"go.opentelemetry.io/collector/processor" |
| 18 |
) |
| 19 |
|
| 20 |
// ProcessTracesFunc 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 ProcessTracesFunc func(context.Context, ptrace.Traces) (ptrace.Traces, error) |
| 23 |
|
| 24 |
type traces struct { |
| 25 |
component.StartFunc |
| 26 |
component.ShutdownFunc |
| 27 |
consumer.Traces |
| 28 |
} |
| 29 |
|
| 30 |
// NewTraces creates a processor.Traces that ensure context propagation and the right tags are set. |
| 31 |
func NewTraces( |
| 32 |
_ context.Context, |
| 33 |
set processor.Settings, |
| 34 |
_ component.Config, |
| 35 |
nextConsumer consumer.Traces, |
| 36 |
tracesFunc ProcessTracesFunc, |
| 37 |
options ...Option, |
| 38 |
) (processor.Traces, error) { |
| 39 |
if tracesFunc == nil { |
| 40 |
return nil, errors.New("nil tracesFunc") |
| 41 |
} |
| 42 |
|
| 43 |
obs, err := newObsReport(set, pipeline.SignalTraces) |
| 44 |
if err != nil { |
| 45 |
return nil, err |
| 46 |
} |
| 47 |
|
| 48 |
eventOptions := spanAttributes(set.ID) |
| 49 |
bs := fromOptions(options) |
| 50 |
traceConsumer, err := consumer.NewTraces(func(ctx context.Context, td ptrace.Traces) error { |
| 51 |
span := trace.SpanFromContext(ctx) |
| 52 |
span.AddEvent("Start processing.", eventOptions) |
| 53 |
|
| 54 |
startTime := time.Now() |
| 55 |
|
| 56 |
spansIn := td.SpanCount() |
| 57 |
|
| 58 |
var errFunc error |
| 59 |
td, errFunc = tracesFunc(ctx, td) |
| 60 |
obs.recordInternalDuration(ctx, startTime) |
| 61 |
span.AddEvent("End processing.", eventOptions) |
| 62 |
if errFunc != nil { |
| 63 |
obs.recordInOut(ctx, spansIn, 0) |
| 64 |
if errors.Is(errFunc, ErrSkipProcessingData) { |
| 65 |
return nil |
| 66 |
} |
| 67 |
return errFunc |
| 68 |
} |
| 69 |
spansOut := td.SpanCount() |
| 70 |
obs.recordInOut(ctx, spansIn, spansOut) |
| 71 |
return nextConsumer.ConsumeTraces(ctx, td) |
| 72 |
}, bs.consumerOptions...) |
| 73 |
if err != nil { |
| 74 |
return nil, err |
| 75 |
} |
| 76 |
|
| 77 |
return &traces{ |
| 78 |
StartFunc: bs.StartFunc, |
| 79 |
ShutdownFunc: bs.ShutdownFunc, |
| 80 |
Traces: traceConsumer, |
| 81 |
}, nil |
| 82 |
} |