Debian Codegraph @

sdk/trace/span.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package trace // import "go.opentelemetry.io/otel/sdk/trace"
5
6 import (
7 "context"
8 "fmt"
9 "reflect"
10 "runtime"
11 rt "runtime/trace"
12 "slices"
13 "strings"
14 "sync"
15 "time"
16 "unicode/utf8"
17
18 "go.opentelemetry.io/otel/attribute"
19 "go.opentelemetry.io/otel/codes"
20 "go.opentelemetry.io/otel/internal/global"
21 "go.opentelemetry.io/otel/sdk/instrumentation"
22 "go.opentelemetry.io/otel/sdk/resource"
23 semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
24 "go.opentelemetry.io/otel/trace"
25 "go.opentelemetry.io/otel/trace/embedded"
26 )
27
28 // ReadOnlySpan allows reading information from the data structure underlying a
29 // trace.Span. It is used in places where reading information from a span is
30 // necessary but changing the span isn't necessary or allowed.
31 //
32 // Warning: methods may be added to this interface in minor releases.
33 type ReadOnlySpan interface {
34 // Name returns the name of the span.
35 Name() string
36 // SpanContext returns the unique SpanContext that identifies the span.
37 SpanContext() trace.SpanContext
38 // Parent returns the unique SpanContext that identifies the parent of the
39 // span if one exists. If the span has no parent the returned SpanContext
40 // will be invalid.
41 Parent() trace.SpanContext
42 // SpanKind returns the role the span plays in a Trace.
43 SpanKind() trace.SpanKind
44 // StartTime returns the time the span started recording.
45 StartTime() time.Time
46 // EndTime returns the time the span stopped recording. It will be zero if
47 // the span has not ended.
48 EndTime() time.Time
49 // Attributes returns the defining attributes of the span.
50 // The order of the returned attributes is not guaranteed to be stable across invocations.
51 Attributes() []attribute.KeyValue
52 // Links returns all the links the span has to other spans.
53 Links() []Link
54 // Events returns all the events that occurred within in the spans
55 // lifetime.
56 Events() []Event
57 // Status returns the spans status.
58 Status() Status
59 // InstrumentationScope returns information about the instrumentation
60 // scope that created the span.
61 InstrumentationScope() instrumentation.Scope
62 // InstrumentationLibrary returns information about the instrumentation
63 // library that created the span.
64 //
65 // Deprecated: please use InstrumentationScope instead.
66 InstrumentationLibrary() instrumentation.Library //nolint:staticcheck // This method needs to be define for backwards compatibility
67 // Resource returns information about the entity that produced the span.
68 Resource() *resource.Resource
69 // DroppedAttributes returns the number of attributes dropped by the span
70 // due to limits being reached.
71 DroppedAttributes() int
72 // DroppedLinks returns the number of links dropped by the span due to
73 // limits being reached.
74 DroppedLinks() int
75 // DroppedEvents returns the number of events dropped by the span due to
76 // limits being reached.
77 DroppedEvents() int
78 // ChildSpanCount returns the count of spans that consider the span a
79 // direct parent.
80 ChildSpanCount() int
81
82 // A private method to prevent users implementing the
83 // interface and so future additions to it will not
84 // violate compatibility.
85 private()
86 }
87
88 // ReadWriteSpan exposes the same methods as trace.Span and in addition allows
89 // reading information from the underlying data structure.
90 // This interface exposes the union of the methods of trace.Span (which is a
91 // "write-only" span) and ReadOnlySpan. New methods for writing or reading span
92 // information should be added under trace.Span or ReadOnlySpan, respectively.
93 //
94 // Warning: methods may be added to this interface in minor releases.
95 type ReadWriteSpan interface {
96 trace.Span
97 ReadOnlySpan
98 }
99
100 // recordingSpan is an implementation of the OpenTelemetry Span API
101 // representing the individual component of a trace that is sampled.
102 type recordingSpan struct {
103 embedded.Span
104
105 // mu protects the contents of this span.
106 mu sync.Mutex
107
108 // parent holds the parent span of this span as a trace.SpanContext.
109 parent trace.SpanContext
110
111 // spanKind represents the kind of this span as a trace.SpanKind.
112 spanKind trace.SpanKind
113
114 // name is the name of this span.
115 name string
116
117 // startTime is the time at which this span was started.
118 startTime time.Time
119
120 // endTime is the time at which this span was ended. It contains the zero
121 // value of time.Time until the span is ended.
122 endTime time.Time
123
124 // status is the status of this span.
125 status Status
126
127 // childSpanCount holds the number of child spans created for this span.
128 childSpanCount int
129
130 // spanContext holds the SpanContext of this span.
131 spanContext trace.SpanContext
132
133 // attributes is a collection of user provided key/values. The collection
134 // is constrained by a configurable maximum held by the parent
135 // TracerProvider. When additional attributes are added after this maximum
136 // is reached these attributes the user is attempting to add are dropped.
137 // This dropped number of attributes is tracked and reported in the
138 // ReadOnlySpan exported when the span ends.
139 attributes []attribute.KeyValue
140 droppedAttributes int
141 logDropAttrsOnce sync.Once
142
143 // events are stored in FIFO queue capped by configured limit.
144 events evictedQueue[Event]
145
146 // links are stored in FIFO queue capped by configured limit.
147 links evictedQueue[Link]
148
149 // executionTracerTaskEnd ends the execution tracer span.
150 executionTracerTaskEnd func()
151
152 // tracer is the SDK tracer that created this span.
153 tracer *tracer
154
155 // origCtx is the context used when starting this span that has the
156 // recordingSpan instance set as the active span. If not nil, it is used
157 // when ending the span to ensure any metrics are recorded with a context
158 // containing this span without requiring an additional allocation.
159 origCtx context.Context
160 }
161
162 var (
163 _ ReadWriteSpan = (*recordingSpan)(nil)
164 _ runtimeTracer = (*recordingSpan)(nil)
165 )
166
167 func (s *recordingSpan) setOrigCtx(ctx context.Context) {
168 s.origCtx = ctx
169 }
170
171 // SpanContext returns the SpanContext of this span.
172 func (s *recordingSpan) SpanContext() trace.SpanContext {
173 if s == nil {
174 return trace.SpanContext{}
175 }
176 return s.spanContext
177 }
178
179 // IsRecording reports whether this span is being recorded. If this span has ended
180 // this will return false.
181 func (s *recordingSpan) IsRecording() bool {
182 if s == nil {
183 return false
184 }
185 s.mu.Lock()
186 defer s.mu.Unlock()
187
188 return s.isRecording()
189 }
190
191 // isRecording reports whether this span is being recorded. If this span has ended
192 // this will return false.
193 //
194 // This method assumes s.mu.Lock is held by the caller.
195 func (s *recordingSpan) isRecording() bool {
196 if s == nil {
197 return false
198 }
199 return s.endTime.IsZero()
200 }
201
202 // SetStatus sets the status of the Span in the form of a code and a
203 // description, overriding previous values set. The description is only
204 // included in the set status when the code is for an error. If this span is
205 // not being recorded than this method does nothing.
206 func (s *recordingSpan) SetStatus(code codes.Code, description string) {
207 if s == nil {
208 return
209 }
210
211 s.mu.Lock()
212 defer s.mu.Unlock()
213 if !s.isRecording() {
214 return
215 }
216 if s.status.Code > code {
217 return
218 }
219
220 status := Status{Code: code}
221 if code == codes.Error {
222 status.Description = description
223 }
224
225 s.status = status
226 }
227
228 // SetAttributes sets attributes of this span.
229 //
230 // If a key from attributes already exists the value associated with that key
231 // will be overwritten with the value contained in attributes.
232 //
233 // If this span is not being recorded than this method does nothing.
234 //
235 // If adding attributes to the span would exceed the maximum amount of
236 // attributes the span is configured to have, the last added attributes will
237 // be dropped.
238 func (s *recordingSpan) SetAttributes(attributes ...attribute.KeyValue) {
239 if s == nil || len(attributes) == 0 {
240 return
241 }
242
243 s.mu.Lock()
244 defer s.mu.Unlock()
245 if !s.isRecording() {
246 return
247 }
248
249 limit := s.tracer.provider.spanLimits.AttributeCountLimit
250 if limit == 0 {
251 // No attributes allowed.
252 s.addDroppedAttr(len(attributes))
253 return
254 }
255
256 // If adding these attributes could exceed the capacity of s perform a
257 // de-duplication and truncation while adding to avoid over allocation.
258 if limit > 0 && len(s.attributes)+len(attributes) > limit {
259 s.addOverCapAttrs(limit, attributes)
260 return
261 }
262
263 // Otherwise, add without deduplication. When attributes are read they
264 // will be deduplicated, optimizing the operation.
265 s.attributes = slices.Grow(s.attributes, len(attributes))
266 for _, a := range attributes {
267 if !a.Valid() {
268 // Drop all invalid attributes.
269 s.addDroppedAttr(1)
270 continue
271 }
272 a = truncateAttr(s.tracer.provider.spanLimits.AttributeValueLengthLimit, a)
273 s.attributes = append(s.attributes, a)
274 }
275 }
276
277 // Declared as a var so tests can override.
278 var logDropAttrs = func() {
279 global.Warn("limit reached: dropping trace Span attributes")
280 }
281
282 // addDroppedAttr adds incr to the count of dropped attributes.
283 //
284 // The first, and only the first, time this method is called a warning will be
285 // logged.
286 //
287 // This method assumes s.mu.Lock is held by the caller.
288 func (s *recordingSpan) addDroppedAttr(incr int) {
289 s.droppedAttributes += incr
290 s.logDropAttrsOnce.Do(logDropAttrs)
291 }
292
293 // addOverCapAttrs adds the attributes attrs to the span s while
294 // de-duplicating the attributes of s and attrs and dropping attributes that
295 // exceed the limit.
296 //
297 // This method assumes s.mu.Lock is held by the caller.
298 //
299 // This method should only be called when there is a possibility that adding
300 // attrs to s will exceed the limit. Otherwise, attrs should be added to s
301 // without checking for duplicates and all retrieval methods of the attributes
302 // for s will de-duplicate as needed.
303 //
304 // This method assumes limit is a value > 0. The argument should be validated
305 // by the caller.
306 func (s *recordingSpan) addOverCapAttrs(limit int, attrs []attribute.KeyValue) {
307 // In order to not allocate more capacity to s.attributes than needed,
308 // prune and truncate this addition of attributes while adding.
309
310 // Do not set a capacity when creating this map. Benchmark testing has
311 // showed this to only add unused memory allocations in general use.
312 exists := make(map[attribute.Key]int, len(s.attributes))
313 s.dedupeAttrsFromRecord(exists)
314
315 // Now that s.attributes is deduplicated, adding unique attributes up to
316 // the capacity of s will not over allocate s.attributes.
317
318 // max size = limit
319 maxCap := min(len(attrs)+len(s.attributes), limit)
320 if cap(s.attributes) < maxCap {
321 s.attributes = slices.Grow(s.attributes, maxCap-cap(s.attributes))
322 }
323 for _, a := range attrs {
324 if !a.Valid() {
325 // Drop all invalid attributes.
326 s.addDroppedAttr(1)
327 continue
328 }
329
330 if idx, ok := exists[a.Key]; ok {
331 // Perform all updates before dropping, even when at capacity.
332 a = truncateAttr(s.tracer.provider.spanLimits.AttributeValueLengthLimit, a)
333 s.attributes[idx] = a
334 continue
335 }
336
337 if len(s.attributes) >= limit {
338 // Do not just drop all of the remaining attributes, make sure
339 // updates are checked and performed.
340 s.addDroppedAttr(1)
341 } else {
342 a = truncateAttr(s.tracer.provider.spanLimits.AttributeValueLengthLimit, a)
343 s.attributes = append(s.attributes, a)
344 exists[a.Key] = len(s.attributes) - 1
345 }
346 }
347 }
348
349 // truncateAttr returns a truncated version of attr. Only string and string
350 // slice attribute values are truncated. String values are truncated to at
351 // most a length of limit. Each string slice value is truncated in this fashion
352 // (the slice length itself is unaffected).
353 //
354 // No truncation is performed for a negative limit.
355 func truncateAttr(limit int, attr attribute.KeyValue) attribute.KeyValue {
356 if limit < 0 {
357 return attr
358 }
359 switch attr.Value.Type() {
360 case attribute.STRING:
361 v := attr.Value.AsString()
362 return attr.Key.String(truncate(limit, v))
363 case attribute.STRINGSLICE:
364 v := attr.Value.AsStringSlice()
365 for i := range v {
366 v[i] = truncate(limit, v[i])
367 }
368 return attr.Key.StringSlice(v)
369 }
370 return attr
371 }
372
373 // truncate returns a truncated version of s such that it contains less than
374 // the limit number of characters. Truncation is applied by returning the limit
375 // number of valid characters contained in s.
376 //
377 // If limit is negative, it returns the original string.
378 //
379 // UTF-8 is supported. When truncating, all invalid characters are dropped
380 // before applying truncation.
381 //
382 // If s already contains less than the limit number of bytes, it is returned
383 // unchanged. No invalid characters are removed.
384 func truncate(limit int, s string) string {
385 // This prioritize performance in the following order based on the most
386 // common expected use-cases.
387 //
388 // - Short values less than the default limit (128).
389 // - Strings with valid encodings that exceed the limit.
390 // - No limit.
391 // - Strings with invalid encodings that exceed the limit.
392 if limit < 0 || len(s) <= limit {
393 return s
394 }
395
396 // Optimistically, assume all valid UTF-8.
397 var b strings.Builder
398 count := 0
399 for i, c := range s {
400 if c != utf8.RuneError {
401 count++
402 if count > limit {
403 return s[:i]
404 }
405 continue
406 }
407
408 _, size := utf8.DecodeRuneInString(s[i:])
409 if size == 1 {
410 // Invalid encoding.
411 b.Grow(len(s) - 1)
412 _, _ = b.WriteString(s[:i])
413 s = s[i:]
414 break
415 }
416 }
417
418 // Fast-path, no invalid input.
419 if b.Cap() == 0 {
420 return s
421 }
422
423 // Truncate while validating UTF-8.
424 for i := 0; i < len(s) && count < limit; {
425 c := s[i]
426 if c < utf8.RuneSelf {
427 // Optimization for single byte runes (common case).
428 _ = b.WriteByte(c)
429 i++
430 count++
431 continue
432 }
433
434 _, size := utf8.DecodeRuneInString(s[i:])
435 if size == 1 {
436 // We checked for all 1-byte runes above, this is a RuneError.
437 i++
438 continue
439 }
440
441 _, _ = b.WriteString(s[i : i+size])
442 i += size
443 count++
444 }
445
446 return b.String()
447 }
448
449 // End ends the span. This method does nothing if the span is already ended or
450 // is not being recorded.
451 //
452 // The only SpanEndOption currently supported are [trace.WithTimestamp], and
453 // [trace.WithStackTrace].
454 //
455 // If this method is called while panicking an error event is added to the
456 // Span before ending it and the panic is continued.
457 func (s *recordingSpan) End(options ...trace.SpanEndOption) {
458 // Do not start by checking if the span is being recorded which requires
459 // acquiring a lock. Make a minimal check that the span is not nil.
460 if s == nil {
461 return
462 }
463
464 // Store the end time as soon as possible to avoid artificially increasing
465 // the span's duration in case some operation below takes a while.
466 et := monotonicEndTime(s.startTime)
467
468 // Lock the span now that we have an end time and see if we need to do any more processing.
469 s.mu.Lock()
470 if !s.isRecording() {
471 s.mu.Unlock()
472 return
473 }
474
475 config := trace.NewSpanEndConfig(options...)
476 if recovered := recover(); recovered != nil {
477 // Record but don't stop the panic.
478 defer panic(recovered)
479 opts := []trace.EventOption{
480 trace.WithAttributes(
481 semconv.ExceptionType(typeStr(recovered)),
482 semconv.ExceptionMessage(fmt.Sprint(recovered)),
483 ),
484 }
485
486 if config.StackTrace() {
487 opts = append(opts, trace.WithAttributes(
488 semconv.ExceptionStacktrace(recordStackTrace()),
489 ))
490 }
491
492 s.addEvent(semconv.ExceptionEventName, opts...)
493 }
494
495 if s.executionTracerTaskEnd != nil {
496 s.mu.Unlock()
497 s.executionTracerTaskEnd()
498 s.mu.Lock()
499 }
500
501 // Setting endTime to non-zero marks the span as ended and not recording.
502 if config.Timestamp().IsZero() {
503 s.endTime = et
504 } else {
505 s.endTime = config.Timestamp()
506 }
507 s.mu.Unlock()
508
509 if s.tracer.inst.Enabled() {
510 ctx := s.origCtx
511 if ctx == nil {
512 // This should not happen as the origCtx should be set, but
513 // ensure trace information is propagated in the case of an
514 // error.
515 ctx = trace.ContextWithSpan(context.Background(), s)
516 }
517 defer s.tracer.inst.SpanEnded(ctx, s)
518 }
519
520 sps := s.tracer.provider.getSpanProcessors()
521 if len(sps) == 0 {
522 return
523 }
524 snap := s.snapshot()
525 for _, sp := range sps {
526 sp.sp.OnEnd(snap)
527 }
528 }
529
530 // monotonicEndTime returns the end time at present but offset from start,
531 // monotonically.
532 //
533 // The monotonic clock is used in subtractions hence the duration since start
534 // added back to start gives end as a monotonic time. See
535 // https://golang.org/pkg/time/#hdr-Monotonic_Clocks
536 func monotonicEndTime(start time.Time) time.Time {
537 return start.Add(time.Since(start))
538 }
539
540 // RecordError will record err as a span event for this span. An additional call to
541 // SetStatus is required if the Status of the Span should be set to Error, this method
542 // does not change the Span status. If this span is not being recorded or err is nil
543 // than this method does nothing.
544 func (s *recordingSpan) RecordError(err error, opts ...trace.EventOption) {
545 if s == nil || err == nil {
546 return
547 }
548
549 s.mu.Lock()
550 defer s.mu.Unlock()
551 if !s.isRecording() {
552 return
553 }
554
555 opts = append(opts, trace.WithAttributes(
556 semconv.ExceptionType(typeStr(err)),
557 semconv.ExceptionMessage(err.Error()),
558 ))
559
560 c := trace.NewEventConfig(opts...)
561 if c.StackTrace() {
562 opts = append(opts, trace.WithAttributes(
563 semconv.ExceptionStacktrace(recordStackTrace()),
564 ))
565 }
566
567 s.addEvent(semconv.ExceptionEventName, opts...)
568 }
569
570 func typeStr(i any) string {
571 t := reflect.TypeOf(i)
572 if t.PkgPath() == "" && t.Name() == "" {
573 // Likely a builtin type.
574 return t.String()
575 }
576 return fmt.Sprintf("%s.%s", t.PkgPath(), t.Name())
577 }
578
579 func recordStackTrace() string {
580 stackTrace := make([]byte, 2048)
581 n := runtime.Stack(stackTrace, false)
582
583 return string(stackTrace[0:n])
584 }
585
586 // AddEvent adds an event with the provided name and options. If this span is
587 // not being recorded then this method does nothing.
588 func (s *recordingSpan) AddEvent(name string, o ...trace.EventOption) {
589 if s == nil {
590 return
591 }
592
593 s.mu.Lock()
594 defer s.mu.Unlock()
595 if !s.isRecording() {
596 return
597 }
598 s.addEvent(name, o...)
599 }
600
601 // addEvent adds an event with the provided name and options.
602 //
603 // This method assumes s.mu.Lock is held by the caller.
604 func (s *recordingSpan) addEvent(name string, o ...trace.EventOption) {
605 c := trace.NewEventConfig(o...)
606 e := Event{Name: name, Attributes: c.Attributes(), Time: c.Timestamp()}
607
608 // Discard attributes over limit.
609 limit := s.tracer.provider.spanLimits.AttributePerEventCountLimit
610 if limit == 0 {
611 // Drop all attributes.
612 e.DroppedAttributeCount = len(e.Attributes)
613 e.Attributes = nil
614 } else if limit > 0 && len(e.Attributes) > limit {
615 // Drop over capacity.
616 e.DroppedAttributeCount = len(e.Attributes) - limit
617 e.Attributes = e.Attributes[:limit]
618 }
619
620 s.events.add(e)
621 }
622
623 // SetName sets the name of this span. If this span is not being recorded than
624 // this method does nothing.
625 func (s *recordingSpan) SetName(name string) {
626 if s == nil {
627 return
628 }
629
630 s.mu.Lock()
631 defer s.mu.Unlock()
632 if !s.isRecording() {
633 return
634 }
635 s.name = name
636 }
637
638 // Name returns the name of this span.
639 func (s *recordingSpan) Name() string {
640 s.mu.Lock()
641 defer s.mu.Unlock()
642 return s.name
643 }
644
645 // Name returns the SpanContext of this span's parent span.
646 func (s *recordingSpan) Parent() trace.SpanContext {
647 s.mu.Lock()
648 defer s.mu.Unlock()
649 return s.parent
650 }
651
652 // SpanKind returns the SpanKind of this span.
653 func (s *recordingSpan) SpanKind() trace.SpanKind {
654 s.mu.Lock()
655 defer s.mu.Unlock()
656 return s.spanKind
657 }
658
659 // StartTime returns the time this span started.
660 func (s *recordingSpan) StartTime() time.Time {
661 s.mu.Lock()
662 defer s.mu.Unlock()
663 return s.startTime
664 }
665
666 // EndTime returns the time this span ended. For spans that have not yet
667 // ended, the returned value will be the zero value of time.Time.
668 func (s *recordingSpan) EndTime() time.Time {
669 s.mu.Lock()
670 defer s.mu.Unlock()
671 return s.endTime
672 }
673
674 // Attributes returns the attributes of this span.
675 //
676 // The order of the returned attributes is not guaranteed to be stable.
677 func (s *recordingSpan) Attributes() []attribute.KeyValue {
678 s.mu.Lock()
679 defer s.mu.Unlock()
680 s.dedupeAttrs()
681 return s.attributes
682 }
683
684 // dedupeAttrs deduplicates the attributes of s to fit capacity.
685 //
686 // This method assumes s.mu.Lock is held by the caller.
687 func (s *recordingSpan) dedupeAttrs() {
688 // Do not set a capacity when creating this map. Benchmark testing has
689 // showed this to only add unused memory allocations in general use.
690 exists := make(map[attribute.Key]int, len(s.attributes))
691 s.dedupeAttrsFromRecord(exists)
692 }
693
694 // dedupeAttrsFromRecord deduplicates the attributes of s to fit capacity
695 // using record as the record of unique attribute keys to their index.
696 //
697 // This method assumes s.mu.Lock is held by the caller.
698 func (s *recordingSpan) dedupeAttrsFromRecord(record map[attribute.Key]int) {
699 // Use the fact that slices share the same backing array.
700 unique := s.attributes[:0]
701 for _, a := range s.attributes {
702 if idx, ok := record[a.Key]; ok {
703 unique[idx] = a
704 } else {
705 unique = append(unique, a)
706 record[a.Key] = len(unique) - 1
707 }
708 }
709 clear(s.attributes[len(unique):]) // Erase unneeded elements to let GC collect objects.
710 s.attributes = unique
711 }
712
713 // Links returns the links of this span.
714 func (s *recordingSpan) Links() []Link {
715 s.mu.Lock()
716 defer s.mu.Unlock()
717 if len(s.links.queue) == 0 {
718 return []Link{}
719 }
720 return s.links.copy()
721 }
722
723 // Events returns the events of this span.
724 func (s *recordingSpan) Events() []Event {
725 s.mu.Lock()
726 defer s.mu.Unlock()
727 if len(s.events.queue) == 0 {
728 return []Event{}
729 }
730 return s.events.copy()
731 }
732
733 // Status returns the status of this span.
734 func (s *recordingSpan) Status() Status {
735 s.mu.Lock()
736 defer s.mu.Unlock()
737 return s.status
738 }
739
740 // InstrumentationScope returns the instrumentation.Scope associated with
741 // the Tracer that created this span.
742 func (s *recordingSpan) InstrumentationScope() instrumentation.Scope {
743 s.mu.Lock()
744 defer s.mu.Unlock()
745 return s.tracer.instrumentationScope
746 }
747
748 // InstrumentationLibrary returns the instrumentation.Library associated with
749 // the Tracer that created this span.
750 func (s *recordingSpan) InstrumentationLibrary() instrumentation.Library { //nolint:staticcheck // This method needs to be define for backwards compatibility
751 s.mu.Lock()
752 defer s.mu.Unlock()
753 return s.tracer.instrumentationScope
754 }
755
756 // Resource returns the Resource associated with the Tracer that created this
757 // span.
758 func (s *recordingSpan) Resource() *resource.Resource {
759 s.mu.Lock()
760 defer s.mu.Unlock()
761 return s.tracer.provider.resource
762 }
763
764 func (s *recordingSpan) AddLink(link trace.Link) {
765 if s == nil {
766 return
767 }
768 if !link.SpanContext.IsValid() && len(link.Attributes) == 0 &&
769 link.SpanContext.TraceState().Len() == 0 {
770 return
771 }
772
773 s.mu.Lock()
774 defer s.mu.Unlock()
775 if !s.isRecording() {
776 return
777 }
778
779 l := Link{SpanContext: link.SpanContext, Attributes: link.Attributes}
780
781 // Discard attributes over limit.
782 limit := s.tracer.provider.spanLimits.AttributePerLinkCountLimit
783 if limit == 0 {
784 // Drop all attributes.
785 l.DroppedAttributeCount = len(l.Attributes)
786 l.Attributes = nil
787 } else if limit > 0 && len(l.Attributes) > limit {
788 l.DroppedAttributeCount = len(l.Attributes) - limit
789 l.Attributes = l.Attributes[:limit]
790 }
791
792 s.links.add(l)
793 }
794
795 // DroppedAttributes returns the number of attributes dropped by the span
796 // due to limits being reached.
797 func (s *recordingSpan) DroppedAttributes() int {
798 s.mu.Lock()
799 defer s.mu.Unlock()
800 return s.droppedAttributes
801 }
802
803 // DroppedLinks returns the number of links dropped by the span due to limits
804 // being reached.
805 func (s *recordingSpan) DroppedLinks() int {
806 s.mu.Lock()
807 defer s.mu.Unlock()
808 return s.links.droppedCount
809 }
810
811 // DroppedEvents returns the number of events dropped by the span due to
812 // limits being reached.
813 func (s *recordingSpan) DroppedEvents() int {
814 s.mu.Lock()
815 defer s.mu.Unlock()
816 return s.events.droppedCount
817 }
818
819 // ChildSpanCount returns the count of spans that consider the span a
820 // direct parent.
821 func (s *recordingSpan) ChildSpanCount() int {
822 s.mu.Lock()
823 defer s.mu.Unlock()
824 return s.childSpanCount
825 }
826
827 // TracerProvider returns a trace.TracerProvider that can be used to generate
828 // additional Spans on the same telemetry pipeline as the current Span.
829 func (s *recordingSpan) TracerProvider() trace.TracerProvider {
830 return s.tracer.provider
831 }
832
833 // snapshot creates a read-only copy of the current state of the span.
834 func (s *recordingSpan) snapshot() ReadOnlySpan {
835 var sd snapshot
836 s.mu.Lock()
837 defer s.mu.Unlock()
838
839 sd.endTime = s.endTime
840 sd.instrumentationScope = s.tracer.instrumentationScope
841 sd.name = s.name
842 sd.parent = s.parent
843 sd.resource = s.tracer.provider.resource
844 sd.spanContext = s.spanContext
845 sd.spanKind = s.spanKind
846 sd.startTime = s.startTime
847 sd.status = s.status
848 sd.childSpanCount = s.childSpanCount
849
850 if len(s.attributes) > 0 {
851 s.dedupeAttrs()
852 sd.attributes = s.attributes
853 }
854 sd.droppedAttributeCount = s.droppedAttributes
855 if len(s.events.queue) > 0 {
856 sd.events = s.events.copy()
857 sd.droppedEventCount = s.events.droppedCount
858 }
859 if len(s.links.queue) > 0 {
860 sd.links = s.links.copy()
861 sd.droppedLinkCount = s.links.droppedCount
862 }
863 return &sd
864 }
865
866 func (s *recordingSpan) addChild() {
867 if s == nil {
868 return
869 }
870
871 s.mu.Lock()
872 defer s.mu.Unlock()
873 if !s.isRecording() {
874 return
875 }
876 s.childSpanCount++
877 }
878
879 func (*recordingSpan) private() {}
880
881 // runtimeTrace starts a "runtime/trace".Task for the span and returns a
882 // context containing the task.
883 func (s *recordingSpan) runtimeTrace(ctx context.Context) context.Context {
884 if !rt.IsEnabled() {
885 // Avoid additional overhead if runtime/trace is not enabled.
886 return ctx
887 }
888 nctx, task := rt.NewTask(ctx, s.name)
889
890 s.mu.Lock()
891 s.executionTracerTaskEnd = task.End
892 s.mu.Unlock()
893
894 return nctx
895 }
896
897 // nonRecordingSpan is a minimal implementation of the OpenTelemetry Span API
898 // that wraps a SpanContext. It performs no operations other than to return
899 // the wrapped SpanContext or TracerProvider that created it.
900 type nonRecordingSpan struct {
901 embedded.Span
902
903 // tracer is the SDK tracer that created this span.
904 tracer *tracer
905 sc trace.SpanContext
906 }
907
908 var _ trace.Span = nonRecordingSpan{}
909
910 // SpanContext returns the wrapped SpanContext.
911 func (s nonRecordingSpan) SpanContext() trace.SpanContext { return s.sc }
912
913 // IsRecording always returns false.
914 func (nonRecordingSpan) IsRecording() bool { return false }
915
916 // SetStatus does nothing.
917 func (nonRecordingSpan) SetStatus(codes.Code, string) {}
918
919 // SetError does nothing.
920 func (nonRecordingSpan) SetError(bool) {}
921
922 // SetAttributes does nothing.
923 func (nonRecordingSpan) SetAttributes(...attribute.KeyValue) {}
924
925 // End does nothing.
926 func (nonRecordingSpan) End(...trace.SpanEndOption) {}
927
928 // RecordError does nothing.
929 func (nonRecordingSpan) RecordError(error, ...trace.EventOption) {}
930
931 // AddEvent does nothing.
932 func (nonRecordingSpan) AddEvent(string, ...trace.EventOption) {}
933
934 // AddLink does nothing.
935 func (nonRecordingSpan) AddLink(trace.Link) {}
936
937 // SetName does nothing.
938 func (nonRecordingSpan) SetName(string) {}
939
940 // TracerProvider returns the trace.TracerProvider that provided the Tracer
941 // that created this span.
942 func (s nonRecordingSpan) TracerProvider() trace.TracerProvider { return s.tracer.provider }
943
944 func isRecording(s SamplingResult) bool {
945 return s.Decision == RecordOnly || s.Decision == RecordAndSample
946 }
947
948 func isSampled(s SamplingResult) bool {
949 return s.Decision == RecordAndSample
950 }
951
952 // Status is the classified state of a Span.
953 type Status struct {
954 // Code is an identifier of a Spans state classification.
955 Code codes.Code
956 // Description is a user hint about why that status was set. It is only
957 // applicable when Code is Error.
958 Description string
959 }