tracer.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. // Copyright 2022 The OpenZipkin 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 zipkin
  15. import (
  16. "context"
  17. "sync/atomic"
  18. "time"
  19. "github.com/openzipkin/zipkin-go/idgenerator"
  20. "github.com/openzipkin/zipkin-go/model"
  21. "github.com/openzipkin/zipkin-go/propagation"
  22. "github.com/openzipkin/zipkin-go/reporter"
  23. )
  24. // Tracer is our Zipkin tracer implementation. It should be initialized using
  25. // the NewTracer method.
  26. type Tracer struct {
  27. defaultTags map[string]string
  28. extractFailurePolicy ExtractFailurePolicy
  29. sampler Sampler
  30. generate idgenerator.IDGenerator
  31. reporter reporter.Reporter
  32. localEndpoint *model.Endpoint
  33. noop int32 // used as atomic bool (1 = true, 0 = false)
  34. sharedSpans bool
  35. unsampledNoop bool
  36. }
  37. // NewTracer returns a new Zipkin Tracer.
  38. func NewTracer(rep reporter.Reporter, opts ...TracerOption) (*Tracer, error) {
  39. // set default tracer options
  40. t := &Tracer{
  41. defaultTags: make(map[string]string),
  42. extractFailurePolicy: ExtractFailurePolicyRestart,
  43. sampler: AlwaysSample,
  44. generate: idgenerator.NewRandom64(),
  45. reporter: rep,
  46. localEndpoint: nil,
  47. noop: 0,
  48. sharedSpans: true,
  49. unsampledNoop: false,
  50. }
  51. // if no reporter was provided we default to noop implementation.
  52. if t.reporter == nil {
  53. t.reporter = reporter.NewNoopReporter()
  54. t.noop = 1
  55. }
  56. // process functional options
  57. for _, opt := range opts {
  58. if err := opt(t); err != nil {
  59. return nil, err
  60. }
  61. }
  62. return t, nil
  63. }
  64. // StartSpanFromContext creates and starts a span using the span found in
  65. // context as parent. If no parent span is found a root span is created.
  66. func (t *Tracer) StartSpanFromContext(ctx context.Context, name string, options ...SpanOption) (Span, context.Context) {
  67. if parentSpan := SpanFromContext(ctx); parentSpan != nil {
  68. options = append(options, Parent(parentSpan.Context()))
  69. }
  70. span := t.StartSpan(name, options...)
  71. return span, NewContext(ctx, span)
  72. }
  73. // StartSpan creates and starts a span.
  74. func (t *Tracer) StartSpan(name string, options ...SpanOption) Span {
  75. if atomic.LoadInt32(&t.noop) == 1 {
  76. // even though we're going to return a noopSpan, we need to initialize
  77. // a spanImpl to fetch the parent context that might be provided as a
  78. // SpanOption
  79. s := &spanImpl{
  80. SpanModel: model.SpanModel{
  81. Tags: make(map[string]string),
  82. },
  83. }
  84. for _, option := range options {
  85. option(t, s)
  86. }
  87. // return noopSpan with the extracted SpanContext from spanImpl.
  88. return &noopSpan{SpanContext: s.SpanContext}
  89. }
  90. s := &spanImpl{
  91. SpanModel: model.SpanModel{
  92. Kind: model.Undetermined,
  93. Name: name,
  94. LocalEndpoint: t.localEndpoint,
  95. Annotations: make([]model.Annotation, 0),
  96. Tags: make(map[string]string),
  97. },
  98. flushOnFinish: true,
  99. tracer: t,
  100. }
  101. // add default tracer tags to span
  102. for k, v := range t.defaultTags {
  103. s.Tag(k, v)
  104. }
  105. // handle provided functional options
  106. for _, option := range options {
  107. option(t, s)
  108. }
  109. if s.TraceID.Empty() {
  110. // create root span
  111. s.SpanContext.TraceID = t.generate.TraceID()
  112. s.SpanContext.ID = t.generate.SpanID(s.SpanContext.TraceID)
  113. } else {
  114. // valid parent context found
  115. if t.sharedSpans && s.Kind == model.Server {
  116. // join span
  117. s.Shared = true
  118. } else {
  119. // regular child span
  120. parentID := s.SpanContext.ID
  121. s.SpanContext.ParentID = &parentID
  122. s.SpanContext.ID = t.generate.SpanID(model.TraceID{})
  123. }
  124. }
  125. if !s.SpanContext.Debug && s.Sampled == nil {
  126. // deferred sampled context found, invoke sampler
  127. sampled := t.sampler(s.SpanContext.TraceID.Low)
  128. s.SpanContext.Sampled = &sampled
  129. if sampled {
  130. s.mustCollect = 1
  131. }
  132. } else {
  133. if s.SpanContext.Debug || *s.Sampled {
  134. s.mustCollect = 1
  135. }
  136. }
  137. if t.unsampledNoop && s.mustCollect == 0 {
  138. // trace not being sampled and noop requested
  139. return &noopSpan{
  140. SpanContext: s.SpanContext,
  141. }
  142. }
  143. // add start time
  144. if s.Timestamp.IsZero() {
  145. s.Timestamp = time.Now()
  146. }
  147. return s
  148. }
  149. // Extract extracts a SpanContext using the provided Extractor function.
  150. func (t *Tracer) Extract(extractor propagation.Extractor) (sc model.SpanContext) {
  151. if atomic.LoadInt32(&t.noop) == 1 {
  152. return
  153. }
  154. psc, err := extractor()
  155. if psc != nil {
  156. sc = *psc
  157. }
  158. sc.Err = err
  159. return
  160. }
  161. // SetNoop allows for killswitch behavior. If set to true the tracer will return
  162. // noopSpans and all data is dropped. This allows operators to stop tracing in
  163. // risk scenarios. Set back to false to resume tracing.
  164. func (t *Tracer) SetNoop(noop bool) {
  165. if noop {
  166. atomic.CompareAndSwapInt32(&t.noop, 0, 1)
  167. } else {
  168. atomic.CompareAndSwapInt32(&t.noop, 1, 0)
  169. }
  170. }
  171. // LocalEndpoint returns a copy of the currently set local endpoint of the
  172. // tracer instance.
  173. func (t *Tracer) LocalEndpoint() *model.Endpoint {
  174. if t.localEndpoint == nil {
  175. return nil
  176. }
  177. ep := *t.localEndpoint
  178. return &ep
  179. }