package log
import (
"context"
"errors"
"math"
"sync"
"sync/atomic"
"time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/internal/global"
"go.opentelemetry.io/otel/sdk/log/internal/counter"
"go.opentelemetry.io/otel/sdk/log/internal/observ"
)
const (
dfltMaxQSize = 2048
dfltExpInterval = time .Second
dfltExpTimeout = 30 * time .Second
dfltExpMaxBatchSize = 512
envarMaxQSize = "OTEL_BLRP_MAX_QUEUE_SIZE"
envarExpInterval = "OTEL_BLRP_SCHEDULE_DELAY"
envarExpTimeout = "OTEL_BLRP_EXPORT_TIMEOUT"
envarExpMaxBatchSize = "OTEL_BLRP_MAX_EXPORT_BATCH_SIZE"
)
var _ Processor = (*BatchProcessor )(nil )
type BatchProcessor struct {
exporter Exporter
q *queue
batchSize int
exportTrigger chan struct {}
flush chan batchProcessorRequest
shutdown chan batchProcessorRequest
done chan struct {}
stopped atomic .Bool
inst *observ .BLP
noCmp [0 ]func ()
}
type batchProcessorRequest struct {
ctx context .Context
resp chan <- error
}
func (r batchProcessorRequest ) respond (err error ) {
r .resp <- err
}
func NewBatchProcessor (exporter Exporter , opts ...BatchProcessorOption ) *BatchProcessor {
cfg := newBatchConfig (opts )
if exporter == nil {
exporter = defaultNoopExporter
}
b := &BatchProcessor {
q : newQueue (cfg .maxQSize .Value ),
batchSize : cfg .expMaxBatchSize .Value ,
exportTrigger : make (chan struct {}, 1 ),
flush : make (chan batchProcessorRequest ),
shutdown : make (chan batchProcessorRequest , 1 ),
done : make (chan struct {}),
}
var err error
b .inst , err = observ .NewBLP (
counter .NextExporterID (),
func () int64 { return int64 (b .q .Len ()) },
int64 (cfg .maxQSize .Value ),
)
if err != nil {
otel .Handle (err )
}
if b .inst != nil {
exporter = newMetricsExporter (exporter , b .inst )
}
exporter = newTimeoutExporter (exporter , cfg .expTimeout .Value )
exporter = newChunkExporter (exporter , cfg .expMaxBatchSize .Value )
b .exporter = exporter
b .process (cfg .expInterval .Value )
return b
}
func (b *BatchProcessor ) process (interval time .Duration ) {
go func () {
timer := time .NewTimer (interval )
defer timer .Stop ()
buf := make ([]Record , b .batchSize )
for {
select {
case req := <- b .shutdown :
err := b .shutdownExporter (req .ctx )
close (b .done )
req .respond (err )
return
default :
}
select {
case req := <- b .shutdown :
err := b .shutdownExporter (req .ctx )
close (b .done )
req .respond (err )
return
case req := <- b .flush :
err := b .flushExporter (req .ctx )
req .respond (err )
continue
default :
}
select {
case req := <- b .shutdown :
err := b .shutdownExporter (req .ctx )
close (b .done )
req .respond (err )
return
case req := <- b .flush :
err := b .flushExporter (req .ctx )
req .respond (err )
case <- timer .C :
resetTimer (timer , interval )
b .exportBatch (buf )
case <- b .exportTrigger :
resetTimer (timer , interval )
b .exportBatch (buf )
}
}
}()
}
func resetTimer(timer *time .Timer , interval time .Duration ) {
if !timer .Stop () {
select {
case <- timer .C :
default :
}
}
timer .Reset (interval )
}
func (b *BatchProcessor ) exportBatch (buf []Record ) {
b .logDroppedRecords ()
n , remaining := b .q .Dequeue (buf )
if n == 0 {
return
}
err := b .exporter .Export (context .Background (), buf [:n ])
clear (buf [:n ])
if err != nil {
otel .Handle (err )
}
if remaining >= b .batchSize {
b .triggerExport ()
}
}
func (b *BatchProcessor ) flushExporter (ctx context .Context ) error {
if err := ctx .Err (); err != nil {
return err
}
b .logDroppedRecords ()
records := b .q .Flush ()
err := b .exporter .Export (ctx , records )
clear (records )
if ctxErr := ctx .Err (); ctxErr != nil {
return errors .Join (err , ctxErr )
}
return errors .Join (err , b .exporter .ForceFlush (ctx ))
}
func (b *BatchProcessor ) shutdownExporter (ctx context .Context ) error {
b .logDroppedRecords ()
records := b .q .Flush ()
err := b .exporter .Export (ctx , records )
clear (records )
if ctxErr := ctx .Err (); ctxErr != nil {
err = errors .Join (err , ctxErr )
} else {
err = errors .Join (err , b .exporter .ForceFlush (ctx ))
}
err = errors .Join (err , b .exporter .Shutdown (ctx ))
if b .inst != nil {
err = errors .Join (err , b .inst .Shutdown ())
}
return err
}
func (b *BatchProcessor ) logDroppedRecords () {
if d := b .q .Dropped (); d > 0 {
if b .inst != nil {
b .inst .ProcessedQueueFull (context .Background (), int64 (min (math .MaxInt64 , d )))
}
global .Warn ("dropped log records" , "dropped" , d )
}
}
func (b *BatchProcessor ) triggerExport () {
select {
case b .exportTrigger <- struct {}{}:
default :
}
}
func (*BatchProcessor ) Enabled (context .Context , EnabledParameters ) bool {
return true
}
func (b *BatchProcessor ) OnEmit (_ context .Context , r *Record ) error {
if b .stopped .Load () || b .q == nil {
return nil
}
if n , accepted := b .q .Enqueue (r .Clone ()); accepted && n >= b .batchSize {
b .triggerExport ()
}
return nil
}
func (b *BatchProcessor ) Shutdown (ctx context .Context ) error {
if b .stopped .Swap (true ) || b .q == nil {
return nil
}
b .q .Close ()
resp := make (chan error , 1 )
b .shutdown <- batchProcessorRequest {ctx : ctx , resp : resp }
if err := ctx .Err (); err != nil {
return err
}
select {
case err := <- resp :
return err
case <- ctx .Done ():
return ctx .Err ()
}
}
func (b *BatchProcessor ) ForceFlush (ctx context .Context ) error {
if b .stopped .Load () || b .q == nil {
return nil
}
if err := ctx .Err (); err != nil {
return err
}
resp := make (chan error , 1 )
req := batchProcessorRequest {ctx : ctx , resp : resp }
select {
case b .flush <- req :
case <- b .done :
return nil
case <- ctx .Done ():
return ctx .Err ()
}
select {
case err := <- resp :
return err
case <- ctx .Done ():
return ctx .Err ()
}
}
type queue struct {
sync .Mutex
dropped atomic .Uint64
cap, len int
read, write *ring
closed bool
}
func newQueue(size int ) *queue {
r := newRing (size )
return &queue {
cap : size ,
read : r ,
write : r ,
}
}
func (q *queue ) Len () int {
q .Lock ()
defer q .Unlock ()
return q .len
}
func (q *queue ) Dropped () uint64 {
return q .dropped .Swap (0 )
}
func (q *queue ) Enqueue (r Record ) (int , bool ) {
q .Lock ()
defer q .Unlock ()
if q .closed {
return q .len , false
}
q .write .Value = r
q .write = q .write .Next ()
q .len ++
if q .len > q .cap {
q .len = q .cap
q .read = q .read .Next ()
q .dropped .Add (1 )
}
return q .len , true
}
func (q *queue ) Dequeue (buf []Record ) (int , int ) {
q .Lock ()
defer q .Unlock ()
n := min (len (buf ), q .len )
for i := range n {
buf [i ] = q .read .Value
q .read .Value = Record {}
q .read = q .read .Next ()
}
q .len -= n
return n , q .len
}
func (q *queue ) Flush () []Record {
q .Lock ()
defer q .Unlock ()
return q .flush ()
}
func (q *queue ) Close () {
q .Lock ()
defer q .Unlock ()
q .closed = true
}
func (q *queue ) flush () []Record {
out := make ([]Record , q .len )
for i := range out {
out [i ] = q .read .Value
q .read .Value = Record {}
q .read = q .read .Next ()
}
q .len = 0
return out
}
type batchConfig struct {
maxQSize setting [int ]
expInterval setting [time .Duration ]
expTimeout setting [time .Duration ]
expMaxBatchSize setting [int ]
}
func newBatchConfig(options []BatchProcessorOption ) batchConfig {
var c batchConfig
for _ , o := range options {
c = o .apply (c )
}
c .maxQSize = c .maxQSize .Resolve (
clearLessThanOne [int ](),
getenv [int ](envarMaxQSize ),
clearLessThanOne [int ](),
fallback [int ](dfltMaxQSize ),
)
c .expInterval = c .expInterval .Resolve (
clearLessThanOne [time .Duration ](),
getenv [time .Duration ](envarExpInterval ),
clearLessThanOne [time .Duration ](),
fallback [time .Duration ](dfltExpInterval ),
)
c .expTimeout = c .expTimeout .Resolve (
clearLessThanOne [time .Duration ](),
getenv [time .Duration ](envarExpTimeout ),
clearLessThanOne [time .Duration ](),
fallback [time .Duration ](dfltExpTimeout ),
)
c .expMaxBatchSize = c .expMaxBatchSize .Resolve (
clearLessThanOne [int ](),
getenv [int ](envarExpMaxBatchSize ),
clearLessThanOne [int ](),
fallback [int ](dfltExpMaxBatchSize ),
clampMax [int ](c .maxQSize .Value ),
)
return c
}
type BatchProcessorOption interface {
apply(batchConfig ) batchConfig
}
type batchOptionFunc func (batchConfig ) batchConfig
func (fn batchOptionFunc ) apply (c batchConfig ) batchConfig {
return fn (c )
}
func WithMaxQueueSize (size int ) BatchProcessorOption {
return batchOptionFunc (func (cfg batchConfig ) batchConfig {
cfg .maxQSize = newSetting (size )
return cfg
})
}
func WithExportInterval (d time .Duration ) BatchProcessorOption {
return batchOptionFunc (func (cfg batchConfig ) batchConfig {
cfg .expInterval = newSetting (d )
return cfg
})
}
func WithExportTimeout (d time .Duration ) BatchProcessorOption {
return batchOptionFunc (func (cfg batchConfig ) batchConfig {
cfg .expTimeout = newSetting (d )
return cfg
})
}
func WithExportMaxBatchSize (size int ) BatchProcessorOption {
return batchOptionFunc (func (cfg batchConfig ) batchConfig {
cfg .expMaxBatchSize = newSetting (size )
return cfg
})
}
func WithExportBufferSize (_ int ) BatchProcessorOption {
return batchOptionFunc (func (cfg batchConfig ) batchConfig {
return cfg
})
}
The pages are generated with Golds v0.8.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .