1
0

trace.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. // Copyright 2017, OpenCensus 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
  15. import (
  16. "context"
  17. crand "crypto/rand"
  18. "encoding/binary"
  19. "fmt"
  20. "math/rand"
  21. "sync"
  22. "sync/atomic"
  23. "time"
  24. "go.opencensus.io/internal"
  25. "go.opencensus.io/trace/tracestate"
  26. )
  27. // Span represents a span of a trace. It has an associated SpanContext, and
  28. // stores data accumulated while the span is active.
  29. //
  30. // Ideally users should interact with Spans by calling the functions in this
  31. // package that take a Context parameter.
  32. type Span struct {
  33. // data contains information recorded about the span.
  34. //
  35. // It will be non-nil if we are exporting the span or recording events for it.
  36. // Otherwise, data is nil, and the Span is simply a carrier for the
  37. // SpanContext, so that the trace ID is propagated.
  38. data *SpanData
  39. mu sync.Mutex // protects the contents of *data (but not the pointer value.)
  40. spanContext SpanContext
  41. // spanStore is the spanStore this span belongs to, if any, otherwise it is nil.
  42. *spanStore
  43. endOnce sync.Once
  44. executionTracerTaskEnd func() // ends the execution tracer span
  45. }
  46. // IsRecordingEvents returns true if events are being recorded for this span.
  47. // Use this check to avoid computing expensive annotations when they will never
  48. // be used.
  49. func (s *Span) IsRecordingEvents() bool {
  50. if s == nil {
  51. return false
  52. }
  53. return s.data != nil
  54. }
  55. // TraceOptions contains options associated with a trace span.
  56. type TraceOptions uint32
  57. // IsSampled returns true if the span will be exported.
  58. func (sc SpanContext) IsSampled() bool {
  59. return sc.TraceOptions.IsSampled()
  60. }
  61. // setIsSampled sets the TraceOptions bit that determines whether the span will be exported.
  62. func (sc *SpanContext) setIsSampled(sampled bool) {
  63. if sampled {
  64. sc.TraceOptions |= 1
  65. } else {
  66. sc.TraceOptions &= ^TraceOptions(1)
  67. }
  68. }
  69. // IsSampled returns true if the span will be exported.
  70. func (t TraceOptions) IsSampled() bool {
  71. return t&1 == 1
  72. }
  73. // SpanContext contains the state that must propagate across process boundaries.
  74. //
  75. // SpanContext is not an implementation of context.Context.
  76. // TODO: add reference to external Census docs for SpanContext.
  77. type SpanContext struct {
  78. TraceID TraceID
  79. SpanID SpanID
  80. TraceOptions TraceOptions
  81. Tracestate *tracestate.Tracestate
  82. }
  83. type contextKey struct{}
  84. // FromContext returns the Span stored in a context, or nil if there isn't one.
  85. func FromContext(ctx context.Context) *Span {
  86. s, _ := ctx.Value(contextKey{}).(*Span)
  87. return s
  88. }
  89. // NewContext returns a new context with the given Span attached.
  90. func NewContext(parent context.Context, s *Span) context.Context {
  91. return context.WithValue(parent, contextKey{}, s)
  92. }
  93. // All available span kinds. Span kind must be either one of these values.
  94. const (
  95. SpanKindUnspecified = iota
  96. SpanKindServer
  97. SpanKindClient
  98. )
  99. // StartOptions contains options concerning how a span is started.
  100. type StartOptions struct {
  101. // Sampler to consult for this Span. If provided, it is always consulted.
  102. //
  103. // If not provided, then the behavior differs based on whether
  104. // the parent of this Span is remote, local, or there is no parent.
  105. // In the case of a remote parent or no parent, the
  106. // default sampler (see Config) will be consulted. Otherwise,
  107. // when there is a non-remote parent, no new sampling decision will be made:
  108. // we will preserve the sampling of the parent.
  109. Sampler Sampler
  110. // SpanKind represents the kind of a span. If none is set,
  111. // SpanKindUnspecified is used.
  112. SpanKind int
  113. }
  114. // StartOption apply changes to StartOptions.
  115. type StartOption func(*StartOptions)
  116. // WithSpanKind makes new spans to be created with the given kind.
  117. func WithSpanKind(spanKind int) StartOption {
  118. return func(o *StartOptions) {
  119. o.SpanKind = spanKind
  120. }
  121. }
  122. // WithSampler makes new spans to be be created with a custom sampler.
  123. // Otherwise, the global sampler is used.
  124. func WithSampler(sampler Sampler) StartOption {
  125. return func(o *StartOptions) {
  126. o.Sampler = sampler
  127. }
  128. }
  129. // StartSpan starts a new child span of the current span in the context. If
  130. // there is no span in the context, creates a new trace and span.
  131. //
  132. // Returned context contains the newly created span. You can use it to
  133. // propagate the returned span in process.
  134. func StartSpan(ctx context.Context, name string, o ...StartOption) (context.Context, *Span) {
  135. var opts StartOptions
  136. var parent SpanContext
  137. if p := FromContext(ctx); p != nil {
  138. parent = p.spanContext
  139. }
  140. for _, op := range o {
  141. op(&opts)
  142. }
  143. span := startSpanInternal(name, parent != SpanContext{}, parent, false, opts)
  144. ctx, end := startExecutionTracerTask(ctx, name)
  145. span.executionTracerTaskEnd = end
  146. return NewContext(ctx, span), span
  147. }
  148. // StartSpanWithRemoteParent starts a new child span of the span from the given parent.
  149. //
  150. // If the incoming context contains a parent, it ignores. StartSpanWithRemoteParent is
  151. // preferred for cases where the parent is propagated via an incoming request.
  152. //
  153. // Returned context contains the newly created span. You can use it to
  154. // propagate the returned span in process.
  155. func StartSpanWithRemoteParent(ctx context.Context, name string, parent SpanContext, o ...StartOption) (context.Context, *Span) {
  156. var opts StartOptions
  157. for _, op := range o {
  158. op(&opts)
  159. }
  160. span := startSpanInternal(name, parent != SpanContext{}, parent, true, opts)
  161. ctx, end := startExecutionTracerTask(ctx, name)
  162. span.executionTracerTaskEnd = end
  163. return NewContext(ctx, span), span
  164. }
  165. func startSpanInternal(name string, hasParent bool, parent SpanContext, remoteParent bool, o StartOptions) *Span {
  166. span := &Span{}
  167. span.spanContext = parent
  168. cfg := config.Load().(*Config)
  169. if !hasParent {
  170. span.spanContext.TraceID = cfg.IDGenerator.NewTraceID()
  171. }
  172. span.spanContext.SpanID = cfg.IDGenerator.NewSpanID()
  173. sampler := cfg.DefaultSampler
  174. if !hasParent || remoteParent || o.Sampler != nil {
  175. // If this span is the child of a local span and no Sampler is set in the
  176. // options, keep the parent's TraceOptions.
  177. //
  178. // Otherwise, consult the Sampler in the options if it is non-nil, otherwise
  179. // the default sampler.
  180. if o.Sampler != nil {
  181. sampler = o.Sampler
  182. }
  183. span.spanContext.setIsSampled(sampler(SamplingParameters{
  184. ParentContext: parent,
  185. TraceID: span.spanContext.TraceID,
  186. SpanID: span.spanContext.SpanID,
  187. Name: name,
  188. HasRemoteParent: remoteParent}).Sample)
  189. }
  190. if !internal.LocalSpanStoreEnabled && !span.spanContext.IsSampled() {
  191. return span
  192. }
  193. span.data = &SpanData{
  194. SpanContext: span.spanContext,
  195. StartTime: time.Now(),
  196. SpanKind: o.SpanKind,
  197. Name: name,
  198. HasRemoteParent: remoteParent,
  199. }
  200. if hasParent {
  201. span.data.ParentSpanID = parent.SpanID
  202. }
  203. if internal.LocalSpanStoreEnabled {
  204. var ss *spanStore
  205. ss = spanStoreForNameCreateIfNew(name)
  206. if ss != nil {
  207. span.spanStore = ss
  208. ss.add(span)
  209. }
  210. }
  211. return span
  212. }
  213. // End ends the span.
  214. func (s *Span) End() {
  215. if s == nil {
  216. return
  217. }
  218. if s.executionTracerTaskEnd != nil {
  219. s.executionTracerTaskEnd()
  220. }
  221. if !s.IsRecordingEvents() {
  222. return
  223. }
  224. s.endOnce.Do(func() {
  225. exp, _ := exporters.Load().(exportersMap)
  226. mustExport := s.spanContext.IsSampled() && len(exp) > 0
  227. if s.spanStore != nil || mustExport {
  228. sd := s.makeSpanData()
  229. sd.EndTime = internal.MonotonicEndTime(sd.StartTime)
  230. if s.spanStore != nil {
  231. s.spanStore.finished(s, sd)
  232. }
  233. if mustExport {
  234. for e := range exp {
  235. e.ExportSpan(sd)
  236. }
  237. }
  238. }
  239. })
  240. }
  241. // makeSpanData produces a SpanData representing the current state of the Span.
  242. // It requires that s.data is non-nil.
  243. func (s *Span) makeSpanData() *SpanData {
  244. var sd SpanData
  245. s.mu.Lock()
  246. sd = *s.data
  247. if s.data.Attributes != nil {
  248. sd.Attributes = make(map[string]interface{})
  249. for k, v := range s.data.Attributes {
  250. sd.Attributes[k] = v
  251. }
  252. }
  253. s.mu.Unlock()
  254. return &sd
  255. }
  256. // SpanContext returns the SpanContext of the span.
  257. func (s *Span) SpanContext() SpanContext {
  258. if s == nil {
  259. return SpanContext{}
  260. }
  261. return s.spanContext
  262. }
  263. // SetName sets the name of the span, if it is recording events.
  264. func (s *Span) SetName(name string) {
  265. if !s.IsRecordingEvents() {
  266. return
  267. }
  268. s.mu.Lock()
  269. s.data.Name = name
  270. s.mu.Unlock()
  271. }
  272. // SetStatus sets the status of the span, if it is recording events.
  273. func (s *Span) SetStatus(status Status) {
  274. if !s.IsRecordingEvents() {
  275. return
  276. }
  277. s.mu.Lock()
  278. s.data.Status = status
  279. s.mu.Unlock()
  280. }
  281. // AddAttributes sets attributes in the span.
  282. //
  283. // Existing attributes whose keys appear in the attributes parameter are overwritten.
  284. func (s *Span) AddAttributes(attributes ...Attribute) {
  285. if !s.IsRecordingEvents() {
  286. return
  287. }
  288. s.mu.Lock()
  289. if s.data.Attributes == nil {
  290. s.data.Attributes = make(map[string]interface{})
  291. }
  292. copyAttributes(s.data.Attributes, attributes)
  293. s.mu.Unlock()
  294. }
  295. // copyAttributes copies a slice of Attributes into a map.
  296. func copyAttributes(m map[string]interface{}, attributes []Attribute) {
  297. for _, a := range attributes {
  298. m[a.key] = a.value
  299. }
  300. }
  301. func (s *Span) lazyPrintfInternal(attributes []Attribute, format string, a ...interface{}) {
  302. now := time.Now()
  303. msg := fmt.Sprintf(format, a...)
  304. var m map[string]interface{}
  305. s.mu.Lock()
  306. if len(attributes) != 0 {
  307. m = make(map[string]interface{})
  308. copyAttributes(m, attributes)
  309. }
  310. s.data.Annotations = append(s.data.Annotations, Annotation{
  311. Time: now,
  312. Message: msg,
  313. Attributes: m,
  314. })
  315. s.mu.Unlock()
  316. }
  317. func (s *Span) printStringInternal(attributes []Attribute, str string) {
  318. now := time.Now()
  319. var a map[string]interface{}
  320. s.mu.Lock()
  321. if len(attributes) != 0 {
  322. a = make(map[string]interface{})
  323. copyAttributes(a, attributes)
  324. }
  325. s.data.Annotations = append(s.data.Annotations, Annotation{
  326. Time: now,
  327. Message: str,
  328. Attributes: a,
  329. })
  330. s.mu.Unlock()
  331. }
  332. // Annotate adds an annotation with attributes.
  333. // Attributes can be nil.
  334. func (s *Span) Annotate(attributes []Attribute, str string) {
  335. if !s.IsRecordingEvents() {
  336. return
  337. }
  338. s.printStringInternal(attributes, str)
  339. }
  340. // Annotatef adds an annotation with attributes.
  341. func (s *Span) Annotatef(attributes []Attribute, format string, a ...interface{}) {
  342. if !s.IsRecordingEvents() {
  343. return
  344. }
  345. s.lazyPrintfInternal(attributes, format, a...)
  346. }
  347. // AddMessageSendEvent adds a message send event to the span.
  348. //
  349. // messageID is an identifier for the message, which is recommended to be
  350. // unique in this span and the same between the send event and the receive
  351. // event (this allows to identify a message between the sender and receiver).
  352. // For example, this could be a sequence id.
  353. func (s *Span) AddMessageSendEvent(messageID, uncompressedByteSize, compressedByteSize int64) {
  354. if !s.IsRecordingEvents() {
  355. return
  356. }
  357. now := time.Now()
  358. s.mu.Lock()
  359. s.data.MessageEvents = append(s.data.MessageEvents, MessageEvent{
  360. Time: now,
  361. EventType: MessageEventTypeSent,
  362. MessageID: messageID,
  363. UncompressedByteSize: uncompressedByteSize,
  364. CompressedByteSize: compressedByteSize,
  365. })
  366. s.mu.Unlock()
  367. }
  368. // AddMessageReceiveEvent adds a message receive event to the span.
  369. //
  370. // messageID is an identifier for the message, which is recommended to be
  371. // unique in this span and the same between the send event and the receive
  372. // event (this allows to identify a message between the sender and receiver).
  373. // For example, this could be a sequence id.
  374. func (s *Span) AddMessageReceiveEvent(messageID, uncompressedByteSize, compressedByteSize int64) {
  375. if !s.IsRecordingEvents() {
  376. return
  377. }
  378. now := time.Now()
  379. s.mu.Lock()
  380. s.data.MessageEvents = append(s.data.MessageEvents, MessageEvent{
  381. Time: now,
  382. EventType: MessageEventTypeRecv,
  383. MessageID: messageID,
  384. UncompressedByteSize: uncompressedByteSize,
  385. CompressedByteSize: compressedByteSize,
  386. })
  387. s.mu.Unlock()
  388. }
  389. // AddLink adds a link to the span.
  390. func (s *Span) AddLink(l Link) {
  391. if !s.IsRecordingEvents() {
  392. return
  393. }
  394. s.mu.Lock()
  395. s.data.Links = append(s.data.Links, l)
  396. s.mu.Unlock()
  397. }
  398. func (s *Span) String() string {
  399. if s == nil {
  400. return "<nil>"
  401. }
  402. if s.data == nil {
  403. return fmt.Sprintf("span %s", s.spanContext.SpanID)
  404. }
  405. s.mu.Lock()
  406. str := fmt.Sprintf("span %s %q", s.spanContext.SpanID, s.data.Name)
  407. s.mu.Unlock()
  408. return str
  409. }
  410. var config atomic.Value // access atomically
  411. func init() {
  412. gen := &defaultIDGenerator{}
  413. // initialize traceID and spanID generators.
  414. var rngSeed int64
  415. for _, p := range []interface{}{
  416. &rngSeed, &gen.traceIDAdd, &gen.nextSpanID, &gen.spanIDInc,
  417. } {
  418. binary.Read(crand.Reader, binary.LittleEndian, p)
  419. }
  420. gen.traceIDRand = rand.New(rand.NewSource(rngSeed))
  421. gen.spanIDInc |= 1
  422. config.Store(&Config{
  423. DefaultSampler: ProbabilitySampler(defaultSamplingProbability),
  424. IDGenerator: gen,
  425. })
  426. }
  427. type defaultIDGenerator struct {
  428. sync.Mutex
  429. // Please keep these as the first fields
  430. // so that these 8 byte fields will be aligned on addresses
  431. // divisible by 8, on both 32-bit and 64-bit machines when
  432. // performing atomic increments and accesses.
  433. // See:
  434. // * https://github.com/census-instrumentation/opencensus-go/issues/587
  435. // * https://github.com/census-instrumentation/opencensus-go/issues/865
  436. // * https://golang.org/pkg/sync/atomic/#pkg-note-BUG
  437. nextSpanID uint64
  438. spanIDInc uint64
  439. traceIDAdd [2]uint64
  440. traceIDRand *rand.Rand
  441. }
  442. // NewSpanID returns a non-zero span ID from a randomly-chosen sequence.
  443. func (gen *defaultIDGenerator) NewSpanID() [8]byte {
  444. var id uint64
  445. for id == 0 {
  446. id = atomic.AddUint64(&gen.nextSpanID, gen.spanIDInc)
  447. }
  448. var sid [8]byte
  449. binary.LittleEndian.PutUint64(sid[:], id)
  450. return sid
  451. }
  452. // NewTraceID returns a non-zero trace ID from a randomly-chosen sequence.
  453. // mu should be held while this function is called.
  454. func (gen *defaultIDGenerator) NewTraceID() [16]byte {
  455. var tid [16]byte
  456. // Construct the trace ID from two outputs of traceIDRand, with a constant
  457. // added to each half for additional entropy.
  458. gen.Lock()
  459. binary.LittleEndian.PutUint64(tid[0:8], gen.traceIDRand.Uint64()+gen.traceIDAdd[0])
  460. binary.LittleEndian.PutUint64(tid[8:16], gen.traceIDRand.Uint64()+gen.traceIDAdd[1])
  461. gen.Unlock()
  462. return tid
  463. }