| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
package fanoutconsumer |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
|
| 9 |
"go.uber.org/multierr" |
| 10 |
|
| 11 |
"go.opentelemetry.io/collector/consumer" |
| 12 |
"go.opentelemetry.io/collector/pdata/ptrace" |
| 13 |
) |
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
func NewTraces(tcs []consumer.Traces) consumer.Traces { |
| 20 |
|
| 21 |
if len(tcs) == 1 && !tcs[0].Capabilities().MutatesData { |
| 22 |
return tcs[0] |
| 23 |
} |
| 24 |
|
| 25 |
tc := &tracesConsumer{} |
| 26 |
for i := range tcs { |
| 27 |
if tcs[i].Capabilities().MutatesData { |
| 28 |
tc.mutable = append(tc.mutable, tcs[i]) |
| 29 |
} else { |
| 30 |
tc.readonly = append(tc.readonly, tcs[i]) |
| 31 |
} |
| 32 |
} |
| 33 |
return tc |
| 34 |
} |
| 35 |
|
| 36 |
type tracesConsumer struct { |
| 37 |
mutable []consumer.Traces |
| 38 |
readonly []consumer.Traces |
| 39 |
} |
| 40 |
|
| 41 |
func (tsc *tracesConsumer) Capabilities() consumer.Capabilities { |
| 42 |
|
| 43 |
return consumer.Capabilities{MutatesData: len(tsc.mutable) > 0 && len(tsc.readonly) == 0} |
| 44 |
} |
| 45 |
|
| 46 |
|
| 47 |
func (tsc *tracesConsumer) ConsumeTraces(ctx context.Context, td ptrace.Traces) error { |
| 48 |
var errs error |
| 49 |
|
| 50 |
if len(tsc.mutable) > 0 { |
| 51 |
|
| 52 |
for i := 0; i < len(tsc.mutable)-1; i++ { |
| 53 |
errs = multierr.Append(errs, tsc.mutable[i].ConsumeTraces(ctx, cloneTraces(td))) |
| 54 |
} |
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
lastConsumer := tsc.mutable[len(tsc.mutable)-1] |
| 59 |
if len(tsc.readonly) == 0 && !td.IsReadOnly() { |
| 60 |
errs = multierr.Append(errs, lastConsumer.ConsumeTraces(ctx, td)) |
| 61 |
} else { |
| 62 |
errs = multierr.Append(errs, lastConsumer.ConsumeTraces(ctx, cloneTraces(td))) |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
|
| 67 |
if len(tsc.readonly) > 1 && !td.IsReadOnly() { |
| 68 |
td.MarkReadOnly() |
| 69 |
} |
| 70 |
for _, tc := range tsc.readonly { |
| 71 |
errs = multierr.Append(errs, tc.ConsumeTraces(ctx, td)) |
| 72 |
} |
| 73 |
|
| 74 |
return errs |
| 75 |
} |
| 76 |
|
| 77 |
func cloneTraces(td ptrace.Traces) ptrace.Traces { |
| 78 |
clonedTraces := ptrace.NewTraces() |
| 79 |
td.CopyTo(clonedTraces) |
| 80 |
return clonedTraces |
| 81 |
} |