batch_span_processor.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. // Copyright The OpenTelemetry Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package trace // import "go.opentelemetry.io/otel/sdk/trace"
  15. import (
  16. "context"
  17. "runtime"
  18. "sync"
  19. "sync/atomic"
  20. "time"
  21. "go.opentelemetry.io/otel"
  22. "go.opentelemetry.io/otel/internal/global"
  23. "go.opentelemetry.io/otel/sdk/internal/env"
  24. "go.opentelemetry.io/otel/trace"
  25. )
  26. // Defaults for BatchSpanProcessorOptions.
  27. const (
  28. DefaultMaxQueueSize = 2048
  29. DefaultScheduleDelay = 5000
  30. DefaultExportTimeout = 30000
  31. DefaultMaxExportBatchSize = 512
  32. )
  33. type BatchSpanProcessorOption func(o *BatchSpanProcessorOptions)
  34. type BatchSpanProcessorOptions struct {
  35. // MaxQueueSize is the maximum queue size to buffer spans for delayed processing. If the
  36. // queue gets full it drops the spans. Use BlockOnQueueFull to change this behavior.
  37. // The default value of MaxQueueSize is 2048.
  38. MaxQueueSize int
  39. // BatchTimeout is the maximum duration for constructing a batch. Processor
  40. // forcefully sends available spans when timeout is reached.
  41. // The default value of BatchTimeout is 5000 msec.
  42. BatchTimeout time.Duration
  43. // ExportTimeout specifies the maximum duration for exporting spans. If the timeout
  44. // is reached, the export will be cancelled.
  45. // The default value of ExportTimeout is 30000 msec.
  46. ExportTimeout time.Duration
  47. // MaxExportBatchSize is the maximum number of spans to process in a single batch.
  48. // If there are more than one batch worth of spans then it processes multiple batches
  49. // of spans one batch after the other without any delay.
  50. // The default value of MaxExportBatchSize is 512.
  51. MaxExportBatchSize int
  52. // BlockOnQueueFull blocks onEnd() and onStart() method if the queue is full
  53. // AND if BlockOnQueueFull is set to true.
  54. // Blocking option should be used carefully as it can severely affect the performance of an
  55. // application.
  56. BlockOnQueueFull bool
  57. }
  58. // batchSpanProcessor is a SpanProcessor that batches asynchronously-received
  59. // spans and sends them to a trace.Exporter when complete.
  60. type batchSpanProcessor struct {
  61. e SpanExporter
  62. o BatchSpanProcessorOptions
  63. queue chan ReadOnlySpan
  64. dropped uint32
  65. batch []ReadOnlySpan
  66. batchMutex sync.Mutex
  67. timer *time.Timer
  68. stopWait sync.WaitGroup
  69. stopOnce sync.Once
  70. stopCh chan struct{}
  71. }
  72. var _ SpanProcessor = (*batchSpanProcessor)(nil)
  73. // NewBatchSpanProcessor creates a new SpanProcessor that will send completed
  74. // span batches to the exporter with the supplied options.
  75. //
  76. // If the exporter is nil, the span processor will preform no action.
  77. func NewBatchSpanProcessor(exporter SpanExporter, options ...BatchSpanProcessorOption) SpanProcessor {
  78. maxQueueSize := env.BatchSpanProcessorMaxQueueSize(DefaultMaxQueueSize)
  79. maxExportBatchSize := env.BatchSpanProcessorMaxExportBatchSize(DefaultMaxExportBatchSize)
  80. if maxExportBatchSize > maxQueueSize {
  81. if DefaultMaxExportBatchSize > maxQueueSize {
  82. maxExportBatchSize = maxQueueSize
  83. } else {
  84. maxExportBatchSize = DefaultMaxExportBatchSize
  85. }
  86. }
  87. o := BatchSpanProcessorOptions{
  88. BatchTimeout: time.Duration(env.BatchSpanProcessorScheduleDelay(DefaultScheduleDelay)) * time.Millisecond,
  89. ExportTimeout: time.Duration(env.BatchSpanProcessorExportTimeout(DefaultExportTimeout)) * time.Millisecond,
  90. MaxQueueSize: maxQueueSize,
  91. MaxExportBatchSize: maxExportBatchSize,
  92. }
  93. for _, opt := range options {
  94. opt(&o)
  95. }
  96. bsp := &batchSpanProcessor{
  97. e: exporter,
  98. o: o,
  99. batch: make([]ReadOnlySpan, 0, o.MaxExportBatchSize),
  100. timer: time.NewTimer(o.BatchTimeout),
  101. queue: make(chan ReadOnlySpan, o.MaxQueueSize),
  102. stopCh: make(chan struct{}),
  103. }
  104. bsp.stopWait.Add(1)
  105. go func() {
  106. defer bsp.stopWait.Done()
  107. bsp.processQueue()
  108. bsp.drainQueue()
  109. }()
  110. return bsp
  111. }
  112. // OnStart method does nothing.
  113. func (bsp *batchSpanProcessor) OnStart(parent context.Context, s ReadWriteSpan) {}
  114. // OnEnd method enqueues a ReadOnlySpan for later processing.
  115. func (bsp *batchSpanProcessor) OnEnd(s ReadOnlySpan) {
  116. // Do not enqueue spans if we are just going to drop them.
  117. if bsp.e == nil {
  118. return
  119. }
  120. bsp.enqueue(s)
  121. }
  122. // Shutdown flushes the queue and waits until all spans are processed.
  123. // It only executes once. Subsequent call does nothing.
  124. func (bsp *batchSpanProcessor) Shutdown(ctx context.Context) error {
  125. var err error
  126. bsp.stopOnce.Do(func() {
  127. wait := make(chan struct{})
  128. go func() {
  129. close(bsp.stopCh)
  130. bsp.stopWait.Wait()
  131. if bsp.e != nil {
  132. if err := bsp.e.Shutdown(ctx); err != nil {
  133. otel.Handle(err)
  134. }
  135. }
  136. close(wait)
  137. }()
  138. // Wait until the wait group is done or the context is cancelled
  139. select {
  140. case <-wait:
  141. case <-ctx.Done():
  142. err = ctx.Err()
  143. }
  144. })
  145. return err
  146. }
  147. type forceFlushSpan struct {
  148. ReadOnlySpan
  149. flushed chan struct{}
  150. }
  151. func (f forceFlushSpan) SpanContext() trace.SpanContext {
  152. return trace.NewSpanContext(trace.SpanContextConfig{TraceFlags: trace.FlagsSampled})
  153. }
  154. // ForceFlush exports all ended spans that have not yet been exported.
  155. func (bsp *batchSpanProcessor) ForceFlush(ctx context.Context) error {
  156. var err error
  157. if bsp.e != nil {
  158. flushCh := make(chan struct{})
  159. if bsp.enqueueBlockOnQueueFull(ctx, forceFlushSpan{flushed: flushCh}, true) {
  160. select {
  161. case <-flushCh:
  162. // Processed any items in queue prior to ForceFlush being called
  163. case <-ctx.Done():
  164. return ctx.Err()
  165. }
  166. }
  167. wait := make(chan error)
  168. go func() {
  169. wait <- bsp.exportSpans(ctx)
  170. close(wait)
  171. }()
  172. // Wait until the export is finished or the context is cancelled/timed out
  173. select {
  174. case err = <-wait:
  175. case <-ctx.Done():
  176. err = ctx.Err()
  177. }
  178. }
  179. return err
  180. }
  181. func WithMaxQueueSize(size int) BatchSpanProcessorOption {
  182. return func(o *BatchSpanProcessorOptions) {
  183. o.MaxQueueSize = size
  184. }
  185. }
  186. func WithMaxExportBatchSize(size int) BatchSpanProcessorOption {
  187. return func(o *BatchSpanProcessorOptions) {
  188. o.MaxExportBatchSize = size
  189. }
  190. }
  191. func WithBatchTimeout(delay time.Duration) BatchSpanProcessorOption {
  192. return func(o *BatchSpanProcessorOptions) {
  193. o.BatchTimeout = delay
  194. }
  195. }
  196. func WithExportTimeout(timeout time.Duration) BatchSpanProcessorOption {
  197. return func(o *BatchSpanProcessorOptions) {
  198. o.ExportTimeout = timeout
  199. }
  200. }
  201. func WithBlocking() BatchSpanProcessorOption {
  202. return func(o *BatchSpanProcessorOptions) {
  203. o.BlockOnQueueFull = true
  204. }
  205. }
  206. // exportSpans is a subroutine of processing and draining the queue.
  207. func (bsp *batchSpanProcessor) exportSpans(ctx context.Context) error {
  208. bsp.timer.Reset(bsp.o.BatchTimeout)
  209. bsp.batchMutex.Lock()
  210. defer bsp.batchMutex.Unlock()
  211. if bsp.o.ExportTimeout > 0 {
  212. var cancel context.CancelFunc
  213. ctx, cancel = context.WithTimeout(ctx, bsp.o.ExportTimeout)
  214. defer cancel()
  215. }
  216. if l := len(bsp.batch); l > 0 {
  217. global.Debug("exporting spans", "count", len(bsp.batch), "total_dropped", atomic.LoadUint32(&bsp.dropped))
  218. err := bsp.e.ExportSpans(ctx, bsp.batch)
  219. // A new batch is always created after exporting, even if the batch failed to be exported.
  220. //
  221. // It is up to the exporter to implement any type of retry logic if a batch is failing
  222. // to be exported, since it is specific to the protocol and backend being sent to.
  223. bsp.batch = bsp.batch[:0]
  224. if err != nil {
  225. return err
  226. }
  227. }
  228. return nil
  229. }
  230. // processQueue removes spans from the `queue` channel until processor
  231. // is shut down. It calls the exporter in batches of up to MaxExportBatchSize
  232. // waiting up to BatchTimeout to form a batch.
  233. func (bsp *batchSpanProcessor) processQueue() {
  234. defer bsp.timer.Stop()
  235. ctx, cancel := context.WithCancel(context.Background())
  236. defer cancel()
  237. for {
  238. select {
  239. case <-bsp.stopCh:
  240. return
  241. case <-bsp.timer.C:
  242. if err := bsp.exportSpans(ctx); err != nil {
  243. otel.Handle(err)
  244. }
  245. case sd := <-bsp.queue:
  246. if ffs, ok := sd.(forceFlushSpan); ok {
  247. close(ffs.flushed)
  248. continue
  249. }
  250. bsp.batchMutex.Lock()
  251. bsp.batch = append(bsp.batch, sd)
  252. shouldExport := len(bsp.batch) >= bsp.o.MaxExportBatchSize
  253. bsp.batchMutex.Unlock()
  254. if shouldExport {
  255. if !bsp.timer.Stop() {
  256. <-bsp.timer.C
  257. }
  258. if err := bsp.exportSpans(ctx); err != nil {
  259. otel.Handle(err)
  260. }
  261. }
  262. }
  263. }
  264. }
  265. // drainQueue awaits the any caller that had added to bsp.stopWait
  266. // to finish the enqueue, then exports the final batch.
  267. func (bsp *batchSpanProcessor) drainQueue() {
  268. ctx, cancel := context.WithCancel(context.Background())
  269. defer cancel()
  270. for {
  271. select {
  272. case sd := <-bsp.queue:
  273. if sd == nil {
  274. if err := bsp.exportSpans(ctx); err != nil {
  275. otel.Handle(err)
  276. }
  277. return
  278. }
  279. bsp.batchMutex.Lock()
  280. bsp.batch = append(bsp.batch, sd)
  281. shouldExport := len(bsp.batch) == bsp.o.MaxExportBatchSize
  282. bsp.batchMutex.Unlock()
  283. if shouldExport {
  284. if err := bsp.exportSpans(ctx); err != nil {
  285. otel.Handle(err)
  286. }
  287. }
  288. default:
  289. close(bsp.queue)
  290. }
  291. }
  292. }
  293. func (bsp *batchSpanProcessor) enqueue(sd ReadOnlySpan) {
  294. bsp.enqueueBlockOnQueueFull(context.TODO(), sd, bsp.o.BlockOnQueueFull)
  295. }
  296. func (bsp *batchSpanProcessor) enqueueBlockOnQueueFull(ctx context.Context, sd ReadOnlySpan, block bool) bool {
  297. if !sd.SpanContext().IsSampled() {
  298. return false
  299. }
  300. // This ensures the bsp.queue<- below does not panic as the
  301. // processor shuts down.
  302. defer func() {
  303. x := recover()
  304. switch err := x.(type) {
  305. case nil:
  306. return
  307. case runtime.Error:
  308. if err.Error() == "send on closed channel" {
  309. return
  310. }
  311. }
  312. panic(x)
  313. }()
  314. select {
  315. case <-bsp.stopCh:
  316. return false
  317. default:
  318. }
  319. if block {
  320. select {
  321. case bsp.queue <- sd:
  322. return true
  323. case <-ctx.Done():
  324. return false
  325. }
  326. }
  327. select {
  328. case bsp.queue <- sd:
  329. return true
  330. default:
  331. atomic.AddUint32(&bsp.dropped, 1)
  332. }
  333. return false
  334. }
  335. // MarshalLog is the marshaling function used by the logging system to represent this exporter.
  336. func (bsp *batchSpanProcessor) MarshalLog() interface{} {
  337. return struct {
  338. Type string
  339. SpanExporter SpanExporter
  340. Config BatchSpanProcessorOptions
  341. }{
  342. Type: "BatchSpanProcessor",
  343. SpanExporter: bsp.e,
  344. Config: bsp.o,
  345. }
  346. }