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