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