Debian Codegraph @

processor/batchprocessor/batch_processor.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package batchprocessor // import "go.opentelemetry.io/collector/processor/batchprocessor"
5
6 import (
7 "context"
8 "errors"
9 "fmt"
10 "runtime"
11 "sort"
12 "strings"
13 "sync"
14 "time"
15
16 "go.opentelemetry.io/otel/attribute"
17 "go.uber.org/zap"
18
19 "go.opentelemetry.io/collector/client"
20 "go.opentelemetry.io/collector/component"
21 "go.opentelemetry.io/collector/consumer"
22 "go.opentelemetry.io/collector/consumer/consumererror"
23 "go.opentelemetry.io/collector/pdata/plog"
24 "go.opentelemetry.io/collector/pdata/pmetric"
25 "go.opentelemetry.io/collector/pdata/ptrace"
26 "go.opentelemetry.io/collector/pdata/xpdata/pref"
27 "go.opentelemetry.io/collector/processor"
28 )
29
30 // errTooManyBatchers is returned when the MetadataCardinalityLimit has been reached.
31 var errTooManyBatchers = consumererror.NewPermanent(errors.New("too many batcher metadata-value combinations"))
32
33 // batch_processor is a component that accepts spans and metrics, places them
34 // into batches and sends downstream.
35 //
36 // batch_processor implements consumer.Traces and consumer.Metrics
37 //
38 // Batches are sent out with any of the following conditions:
39 // - batch size reaches cfg.SendBatchSize
40 // - cfg.Timeout is elapsed since the timestamp when the previous batch was sent out.
41 type batchProcessor[T any] struct {
42 logger *zap.Logger
43 timeout time.Duration
44 sendBatchSize int
45 sendBatchMaxSize int
46
47 // batchFunc is a factory for new batch objects corresponding
48 // with the appropriate signal.
49 batchFunc func() batch[T]
50
51 shutdownC chan struct{}
52 goroutines sync.WaitGroup
53
54 telemetry *batchProcessorTelemetry
55
56 // batcher will be either *singletonBatcher or *multiBatcher
57 batcher batcher[T]
58 }
59
60 // batcher is describes a *singletonBatcher or *multiBatcher.
61 type batcher[T any] interface {
62 // start initializes background resources used by this batcher.
63 start(ctx context.Context) error
64
65 // consume incorporates a new item of data into the pending batch.
66 consume(ctx context.Context, data T) error
67
68 // currentMetadataCardinality returns the number of shards.
69 currentMetadataCardinality() int
70 }
71
72 // shard is a single instance of the batch logic. When metadata
73 // keys are in use, one of these is created per distinct combination
74 // of values.
75 type shard[T any] struct {
76 // processor refers to this processor, for access to common
77 // configuration.
78 processor *batchProcessor[T]
79
80 // exportCtx is a context with the metadata key-values
81 // corresponding with this shard set.
82 exportCtx context.Context
83
84 // timer informs the shard send a batch.
85 timer *time.Timer
86
87 // newItem is used to receive data items from producers.
88 newItem chan T
89
90 // batch is an in-flight data item containing one of the
91 // underlying data types.
92 batch batch[T]
93 }
94
95 // batch is an interface generalizing the individual signal types.
96 type batch[T any] interface {
97 // export the current batch
98 export(ctx context.Context, req T) error
99
100 // split returns a full request built from pending items.
101 split(sendBatchMaxSize int) (sentBatchSize int, req T)
102
103 // itemCount returns the size of the current batch
104 itemCount() int
105
106 // add item to the current batch
107 add(item T)
108
109 // sizeBytes counts the OTLP encoding size of the batch
110 sizeBytes(item T) int
111 }
112
113 // newBatchProcessor returns a new batch processor component.
114 func newBatchProcessor[T any](set processor.Settings, cfg *Config, batchFunc func() batch[T]) (*batchProcessor[T], error) {
115 // use lower-case, to be consistent with http/2 headers.
116 mks := make([]string, len(cfg.MetadataKeys))
117 for i, k := range cfg.MetadataKeys {
118 mks[i] = strings.ToLower(k)
119 }
120 sort.Strings(mks)
121 bp := &batchProcessor[T]{
122 logger: set.Logger,
123
124 sendBatchSize: int(cfg.SendBatchSize),
125 sendBatchMaxSize: int(cfg.SendBatchMaxSize),
126 timeout: cfg.Timeout,
127 batchFunc: batchFunc,
128 shutdownC: make(chan struct{}, 1),
129 }
130 if len(mks) == 0 {
131 bp.batcher = &singleShardBatcher[T]{
132 processor: bp,
133 single: bp.newShard(nil),
134 }
135 } else {
136 bp.batcher = &multiShardBatcher[T]{
137 metadataKeys: mks,
138 metadataLimit: int(cfg.MetadataCardinalityLimit),
139 processor: bp,
140 }
141 }
142
143 bpt, err := newBatchProcessorTelemetry(set, bp.batcher.currentMetadataCardinality)
144 if err != nil {
145 return nil, fmt.Errorf("error creating batch processor telemetry: %w", err)
146 }
147 bp.telemetry = bpt
148
149 return bp, nil
150 }
151
152 // newShard gets or creates a batcher corresponding with attrs.
153 func (bp *batchProcessor[T]) newShard(md map[string][]string) *shard[T] {
154 exportCtx := client.NewContext(context.Background(), client.Info{
155 Metadata: client.NewMetadata(md),
156 })
157 b := &shard[T]{
158 processor: bp,
159 newItem: make(chan T, runtime.NumCPU()),
160 exportCtx: exportCtx,
161 batch: bp.batchFunc(),
162 }
163 return b
164 }
165
166 func (bp *batchProcessor[T]) Capabilities() consumer.Capabilities {
167 return consumer.Capabilities{MutatesData: true}
168 }
169
170 // Start is invoked during service startup.
171 func (bp *batchProcessor[T]) Start(ctx context.Context, _ component.Host) error {
172 return bp.batcher.start(ctx)
173 }
174
175 // Shutdown is invoked during service shutdown.
176 func (bp *batchProcessor[T]) Shutdown(context.Context) error {
177 close(bp.shutdownC)
178
179 // Wait until all goroutines are done.
180 bp.goroutines.Wait()
181
182 return nil
183 }
184
185 func (b *shard[T]) start() {
186 b.processor.goroutines.Add(1)
187 go b.startLoop()
188 }
189
190 func (b *shard[T]) startLoop() {
191 defer b.processor.goroutines.Done()
192
193 // timerCh ensures we only block when there is a
194 // timer, since <- from a nil channel is blocking.
195 var timerCh <-chan time.Time
196 if b.processor.timeout != 0 && b.processor.sendBatchSize != 0 {
197 b.timer = time.NewTimer(b.processor.timeout)
198 timerCh = b.timer.C
199 }
200 for {
201 select {
202 case <-b.processor.shutdownC:
203 DONE:
204 for {
205 select {
206 case item := <-b.newItem:
207 b.processItem(item)
208 default:
209 break DONE
210 }
211 }
212 // This is the close of the channel
213 if b.batch.itemCount() > 0 {
214 // TODO: Set a timeout on sendTraces or
215 // make it cancellable using the context that Shutdown gets as a parameter
216 b.sendItems(triggerTimeout)
217 }
218 return
219 case item := <-b.newItem:
220 b.processItem(item)
221 case <-timerCh:
222 if b.batch.itemCount() > 0 {
223 b.sendItems(triggerTimeout)
224 }
225 b.resetTimer()
226 }
227 }
228 }
229
230 func (b *shard[T]) processItem(item T) {
231 b.batch.add(item)
232 sent := false
233 for b.batch.itemCount() > 0 && (!b.hasTimer() || b.batch.itemCount() >= b.processor.sendBatchSize) {
234 sent = true
235 b.sendItems(triggerBatchSize)
236 }
237
238 if sent {
239 b.stopTimer()
240 b.resetTimer()
241 }
242 }
243
244 func (b *shard[T]) hasTimer() bool {
245 return b.timer != nil
246 }
247
248 func (b *shard[T]) stopTimer() {
249 if b.hasTimer() && !b.timer.Stop() {
250 <-b.timer.C
251 }
252 }
253
254 func (b *shard[T]) resetTimer() {
255 if b.hasTimer() {
256 b.timer.Reset(b.processor.timeout)
257 }
258 }
259
260 func (b *shard[T]) sendItems(trigger trigger) {
261 sent, req := b.batch.split(b.processor.sendBatchMaxSize)
262
263 bpt := b.processor.telemetry
264 var bytes int
265 // Check if the instrument is enabled to calculate the size of the batch in bytes.
266 // See https://pkg.go.dev/go.opentelemetry.io/otel/sdk/metric/internal/x#readme-instrument-enabled
267 batchSendSizeBytes := bpt.telemetryBuilder.ProcessorBatchBatchSendSizeBytes
268 instr, ok := batchSendSizeBytes.(interface{ Enabled(context.Context) bool })
269 if !ok || instr.Enabled(bpt.exportCtx) {
270 bytes = b.batch.sizeBytes(req)
271 }
272
273 err := b.batch.export(b.exportCtx, req)
274 if err != nil {
275 b.processor.logger.Warn("Sender failed", zap.Error(err))
276 return
277 }
278 bpt.record(trigger, int64(sent), int64(bytes))
279 }
280
281 // singleShardBatcher is used when metadataKeys is empty, to avoid the
282 // additional lock and map operations used in multiBatcher.
283 type singleShardBatcher[T any] struct {
284 processor *batchProcessor[T]
285 single *shard[T]
286 }
287
288 func (sb *singleShardBatcher[T]) start(context.Context) error {
289 sb.single.start()
290 return nil
291 }
292
293 func (sb *singleShardBatcher[T]) consume(_ context.Context, data T) error {
294 sb.single.newItem <- data
295 return nil
296 }
297
298 func (sb *singleShardBatcher[T]) currentMetadataCardinality() int {
299 return 1
300 }
301
302 // multiShardBatcher is used when metadataKeys is not empty.
303 type multiShardBatcher[T any] struct {
304 // metadataKeys is the configured list of metadata keys. When
305 // empty, the `singleton` batcher is used. When non-empty,
306 // each distinct combination of metadata keys and values
307 // triggers a new batcher, counted in `goroutines`.
308 metadataKeys []string
309
310 // metadataLimit is the limiting size of the batchers map.
311 metadataLimit int
312
313 processor *batchProcessor[T]
314 batchers sync.Map
315
316 // Guards the size and the storing logic to ensure no more than limit items are stored.
317 // If we are willing to allow "some" extra items than the limit this can be removed and size can be made atomic.
318 lock sync.Mutex
319 size int
320 }
321
322 func (mb *multiShardBatcher[T]) start(context.Context) error {
323 return nil
324 }
325
326 func (mb *multiShardBatcher[T]) consume(ctx context.Context, data T) error {
327 // Get each metadata key value, form the corresponding
328 // attribute set for use as a map lookup key.
329 info := client.FromContext(ctx)
330 md := map[string][]string{}
331 var attrs []attribute.KeyValue
332 for _, k := range mb.metadataKeys {
333 // Lookup the value in the incoming metadata, copy it
334 // into the outgoing metadata, and create a unique
335 // value for the attributeSet.
336 vs := info.Metadata.Get(k)
337 md[k] = vs
338 if len(vs) == 1 {
339 attrs = append(attrs, attribute.String(k, vs[0]))
340 } else {
341 attrs = append(attrs, attribute.StringSlice(k, vs))
342 }
343 }
344 aset := attribute.NewSet(attrs...)
345
346 b, ok := mb.batchers.Load(aset)
347 if !ok {
348 mb.lock.Lock()
349 if mb.metadataLimit != 0 && mb.size >= mb.metadataLimit {
350 mb.lock.Unlock()
351 return errTooManyBatchers
352 }
353
354 // aset.ToSlice() returns the sorted, deduplicated,
355 // and name-lowercased list of attributes.
356 var loaded bool
357 b, loaded = mb.batchers.LoadOrStore(aset, mb.processor.newShard(md))
358 if !loaded {
359 // Start the goroutine only if we added the object to the map, otherwise is already started.
360 b.(*shard[T]).start()
361 mb.size++
362 }
363 mb.lock.Unlock()
364 }
365 b.(*shard[T]).newItem <- data
366 return nil
367 }
368
369 func (mb *multiShardBatcher[T]) currentMetadataCardinality() int {
370 mb.lock.Lock()
371 defer mb.lock.Unlock()
372 return mb.size
373 }
374
375 type tracesBatchProcessor struct {
376 *batchProcessor[ptrace.Traces]
377 }
378
379 // newTracesBatchProcessor creates a new batch processor that batches traces by size or with timeout
380 func newTracesBatchProcessor(set processor.Settings, next consumer.Traces, cfg *Config) (processor.Traces, error) {
381 bp, err := newBatchProcessor(set, cfg, func() batch[ptrace.Traces] { return newBatchTraces(next) })
382 if err != nil {
383 return nil, err
384 }
385 return &tracesBatchProcessor{batchProcessor: bp}, nil
386 }
387
388 func (t *tracesBatchProcessor) ConsumeTraces(ctx context.Context, td ptrace.Traces) error {
389 pref.RefTraces(td)
390 return t.batcher.consume(ctx, td)
391 }
392
393 type metricsBatchProcessor struct {
394 *batchProcessor[pmetric.Metrics]
395 }
396
397 // newMetricsBatchProcessor creates a new batch processor that batches metrics by size or with timeout
398 func newMetricsBatchProcessor(set processor.Settings, next consumer.Metrics, cfg *Config) (processor.Metrics, error) {
399 bp, err := newBatchProcessor(set, cfg, func() batch[pmetric.Metrics] { return newMetricsBatch(next) })
400 if err != nil {
401 return nil, err
402 }
403 return &metricsBatchProcessor{batchProcessor: bp}, nil
404 }
405
406 // ConsumeMetrics implements processor.Metrics
407 func (m *metricsBatchProcessor) ConsumeMetrics(ctx context.Context, md pmetric.Metrics) error {
408 pref.RefMetrics(md)
409 return m.batcher.consume(ctx, md)
410 }
411
412 type logsBatchProcessor struct {
413 *batchProcessor[plog.Logs]
414 }
415
416 // newLogsBatchProcessor creates a new batch processor that batches logs by size or with timeout
417 func newLogsBatchProcessor(set processor.Settings, next consumer.Logs, cfg *Config) (processor.Logs, error) {
418 bp, err := newBatchProcessor(set, cfg, func() batch[plog.Logs] { return newBatchLogs(next) })
419 if err != nil {
420 return nil, err
421 }
422 return &logsBatchProcessor{batchProcessor: bp}, nil
423 }
424
425 // ConsumeLogs implements processor.Logs
426 func (l *logsBatchProcessor) ConsumeLogs(ctx context.Context, ld plog.Logs) error {
427 pref.RefLogs(ld)
428 return l.batcher.consume(ctx, ld)
429 }
430
431 type batchTraces struct {
432 nextConsumer consumer.Traces
433 traceData ptrace.Traces
434 spanCount int
435 sizer ptrace.Sizer
436 }
437
438 func newBatchTraces(nextConsumer consumer.Traces) *batchTraces {
439 return &batchTraces{nextConsumer: nextConsumer, traceData: ptrace.NewTraces(), sizer: &ptrace.ProtoMarshaler{}}
440 }
441
442 // add updates current batchTraces by adding new TraceData object
443 func (bt *batchTraces) add(td ptrace.Traces) {
444 defer pref.UnrefTraces(td)
445 newSpanCount := td.SpanCount()
446 if newSpanCount == 0 {
447 return
448 }
449
450 bt.spanCount += newSpanCount
451 td.ResourceSpans().MoveAndAppendTo(bt.traceData.ResourceSpans())
452 }
453
454 func (bt *batchTraces) sizeBytes(td ptrace.Traces) int {
455 return bt.sizer.TracesSize(td)
456 }
457
458 func (bt *batchTraces) export(ctx context.Context, td ptrace.Traces) error {
459 return bt.nextConsumer.ConsumeTraces(ctx, td)
460 }
461
462 func (bt *batchTraces) split(sendBatchMaxSize int) (int, ptrace.Traces) {
463 var td ptrace.Traces
464 var sent int
465 if sendBatchMaxSize > 0 && bt.itemCount() > sendBatchMaxSize {
466 td = splitTraces(sendBatchMaxSize, bt.traceData)
467 bt.spanCount -= sendBatchMaxSize
468 sent = sendBatchMaxSize
469 } else {
470 td = bt.traceData
471 sent = bt.spanCount
472 bt.traceData = ptrace.NewTraces()
473 bt.spanCount = 0
474 }
475 return sent, td
476 }
477
478 func (bt *batchTraces) itemCount() int {
479 return bt.spanCount
480 }
481
482 type batchMetrics struct {
483 nextConsumer consumer.Metrics
484 metricData pmetric.Metrics
485 dataPointCount int
486 sizer pmetric.Sizer
487 }
488
489 func newMetricsBatch(nextConsumer consumer.Metrics) *batchMetrics {
490 return &batchMetrics{nextConsumer: nextConsumer, metricData: pmetric.NewMetrics(), sizer: &pmetric.ProtoMarshaler{}}
491 }
492
493 func (bm *batchMetrics) sizeBytes(md pmetric.Metrics) int {
494 return bm.sizer.MetricsSize(md)
495 }
496
497 func (bm *batchMetrics) export(ctx context.Context, md pmetric.Metrics) error {
498 return bm.nextConsumer.ConsumeMetrics(ctx, md)
499 }
500
501 func (bm *batchMetrics) split(sendBatchMaxSize int) (int, pmetric.Metrics) {
502 var md pmetric.Metrics
503 var sent int
504 if sendBatchMaxSize > 0 && bm.dataPointCount > sendBatchMaxSize {
505 md = splitMetrics(sendBatchMaxSize, bm.metricData)
506 bm.dataPointCount -= sendBatchMaxSize
507 sent = sendBatchMaxSize
508 } else {
509 md = bm.metricData
510 sent = bm.dataPointCount
511 bm.metricData = pmetric.NewMetrics()
512 bm.dataPointCount = 0
513 }
514
515 return sent, md
516 }
517
518 func (bm *batchMetrics) itemCount() int {
519 return bm.dataPointCount
520 }
521
522 func (bm *batchMetrics) add(md pmetric.Metrics) {
523 defer pref.UnrefMetrics(md)
524 newDataPointCount := md.DataPointCount()
525 if newDataPointCount == 0 {
526 return
527 }
528 bm.dataPointCount += newDataPointCount
529 md.ResourceMetrics().MoveAndAppendTo(bm.metricData.ResourceMetrics())
530 }
531
532 type batchLogs struct {
533 nextConsumer consumer.Logs
534 logData plog.Logs
535 logCount int
536 sizer plog.Sizer
537 }
538
539 func newBatchLogs(nextConsumer consumer.Logs) *batchLogs {
540 return &batchLogs{nextConsumer: nextConsumer, logData: plog.NewLogs(), sizer: &plog.ProtoMarshaler{}}
541 }
542
543 func (bl *batchLogs) sizeBytes(ld plog.Logs) int {
544 return bl.sizer.LogsSize(ld)
545 }
546
547 func (bl *batchLogs) export(ctx context.Context, ld plog.Logs) error {
548 return bl.nextConsumer.ConsumeLogs(ctx, ld)
549 }
550
551 func (bl *batchLogs) split(sendBatchMaxSize int) (int, plog.Logs) {
552 var ld plog.Logs
553 var sent int
554
555 if sendBatchMaxSize > 0 && bl.logCount > sendBatchMaxSize {
556 ld = splitLogs(sendBatchMaxSize, bl.logData)
557 bl.logCount -= sendBatchMaxSize
558 sent = sendBatchMaxSize
559 } else {
560 ld = bl.logData
561 sent = bl.logCount
562 bl.logData = plog.NewLogs()
563 bl.logCount = 0
564 }
565 return sent, ld
566 }
567
568 func (bl *batchLogs) itemCount() int {
569 return bl.logCount
570 }
571
572 func (bl *batchLogs) add(ld plog.Logs) {
573 defer pref.UnrefLogs(ld)
574 newLogsCount := ld.LogRecordCount()
575 if newLogsCount == 0 {
576 return
577 }
578 bl.logCount += newLogsCount
579 ld.ResourceLogs().MoveAndAppendTo(bl.logData.ResourceLogs())
580 }