package trace
import (
"context"
"fmt"
"reflect"
"runtime"
rt "runtime/trace"
"slices"
"sync"
"time"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/internal/global"
"go.opentelemetry.io/otel/sdk/instrumentation"
"go.opentelemetry.io/otel/sdk/internal/attrnorm"
"go.opentelemetry.io/otel/sdk/resource"
semconv "go.opentelemetry.io/otel/semconv/v1.43.0"
"go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/otel/trace/embedded"
)
type ReadOnlySpan interface {
Name () string
SpanContext () trace .SpanContext
Parent () trace .SpanContext
SpanKind () trace .SpanKind
StartTime () time .Time
EndTime () time .Time
Attributes () []attribute .KeyValue
Links () []Link
Events () []Event
Status () Status
InstrumentationScope () instrumentation .Scope
InstrumentationLibrary () instrumentation .Library
Resource () *resource .Resource
DroppedAttributes () int
DroppedLinks () int
DroppedEvents () int
ChildSpanCount () int
private()
}
type ReadWriteSpan interface {
trace .Span
ReadOnlySpan
}
type recordingSpan struct {
embedded .Span
mu sync .Mutex
parent trace .SpanContext
spanKind trace .SpanKind
name string
startTime time .Time
endTime time .Time
status Status
childSpanCount int
spanContext trace .SpanContext
attributes []attribute .KeyValue
droppedAttributes int
logDropAttrsOnce sync .Once
attributesDirty bool
attributesShared bool
events evictedQueue [Event ]
links evictedQueue [Link ]
executionTracerTaskEnd func ()
tracer *tracer
origCtx context .Context
}
var (
_ ReadWriteSpan = (*recordingSpan )(nil )
_ runtimeTracer = (*recordingSpan )(nil )
)
func (s *recordingSpan ) setOrigCtx (ctx context .Context ) {
s .origCtx = ctx
}
func (s *recordingSpan ) SpanContext () trace .SpanContext {
if s == nil {
return trace .SpanContext {}
}
return s .spanContext
}
func (s *recordingSpan ) IsRecording () bool {
if s == nil {
return false
}
s .mu .Lock ()
defer s .mu .Unlock ()
return s .isRecording ()
}
func (s *recordingSpan ) isRecording () bool {
if s == nil {
return false
}
return s .endTime .IsZero ()
}
func (s *recordingSpan ) SetStatus (code codes .Code , description string ) {
if s == nil {
return
}
s .mu .Lock ()
defer s .mu .Unlock ()
if !s .isRecording () {
return
}
if s .status .Code > code {
return
}
status := Status {Code : code }
if code == codes .Error {
status .Description = description
}
s .status = status
}
func (s *recordingSpan ) SetAttributes (attributes ...attribute .KeyValue ) {
if s == nil || len (attributes ) == 0 {
return
}
s .mu .Lock ()
defer s .mu .Unlock ()
if !s .isRecording () {
return
}
limit := s .tracer .provider .spanLimits .AttributeCountLimit
if limit == 0 {
s .addDroppedAttr (len (attributes ))
return
}
maxCap := len (s .attributes ) + len (attributes )
if limit > 0 {
maxCap = min (maxCap , limit )
}
s .ensureAttrsWritable (maxCap )
if limit > 0 && len (s .attributes )+len (attributes ) > limit {
s .addOverCapAttrs (limit , attributes )
return
}
s .attributes = slices .Grow (s .attributes , len (attributes ))
for _ , a := range attributes {
if !a .Valid () {
s .addDroppedAttr (1 )
continue
}
a = normAttr (
a ,
s .tracer .provider .spanLimits .AttributeValueDepthLimit ,
s .tracer .provider .spanLimits .AttributeValueLengthLimit ,
)
s .attributes = append (s .attributes , a )
s .attributesDirty = true
}
}
func (s *recordingSpan ) ensureAttrsWritable (capacity int ) {
if !s .attributesShared {
return
}
capacity = max (capacity , len (s .attributes ))
attrs := make ([]attribute .KeyValue , len (s .attributes ), capacity )
copy (attrs , s .attributes )
s .attributes = attrs
s .attributesShared = false
}
var logDropAttrs = func () {
global .Warn ("limit reached: dropping trace Span attributes" )
}
func (s *recordingSpan ) addDroppedAttr (incr int ) {
s .droppedAttributes += incr
s .logDropAttrsOnce .Do (logDropAttrs )
}
func (s *recordingSpan ) addOverCapAttrs (limit int , attrs []attribute .KeyValue ) {
exists := make (map [attribute .Key ]int , len (s .attributes ))
s .dedupeAttrsFromRecord (exists )
maxCap := min (len (attrs )+len (s .attributes ), limit )
if cap (s .attributes ) < maxCap {
s .attributes = slices .Grow (s .attributes , maxCap -cap (s .attributes ))
}
for _ , a := range attrs {
if !a .Valid () {
s .addDroppedAttr (1 )
continue
}
if idx , ok := exists [a .Key ]; ok {
a = normAttr (
a ,
s .tracer .provider .spanLimits .AttributeValueDepthLimit ,
s .tracer .provider .spanLimits .AttributeValueLengthLimit ,
)
s .attributes [idx ] = a
continue
}
if len (s .attributes ) >= limit {
s .addDroppedAttr (1 )
} else {
a = normAttr (
a ,
s .tracer .provider .spanLimits .AttributeValueDepthLimit ,
s .tracer .provider .spanLimits .AttributeValueLengthLimit ,
)
s .attributes = append (s .attributes , a )
exists [a .Key ] = len (s .attributes ) - 1
}
}
}
func normAttr(attr attribute .KeyValue , depthLimit , lengthLimit int ) attribute .KeyValue {
switch attr .Value .Type () {
case attribute .SLICE , attribute .MAP :
if depthLimit < 0 {
attr , _ = attrnorm .KeyValueDedup (attr )
} else {
attr , _, _ = attrnorm .KeyValueDedupLimitDepth (attr , depthLimit )
}
}
return attrnorm .Truncate (lengthLimit , attr )
}
func (s *recordingSpan ) End (options ...trace .SpanEndOption ) {
if s == nil {
return
}
et := monotonicEndTime (s .startTime )
s .mu .Lock ()
if !s .isRecording () {
s .mu .Unlock ()
return
}
config := trace .NewSpanEndConfig (options ...)
if !s .tracer .provider .panicRecordingDisabled {
if recovered := recover (); recovered != nil {
defer panic (recovered )
opts := []trace .EventOption {
trace .WithAttributes (
semconv .ExceptionType (typeStr (recovered )),
semconv .ExceptionMessage (fmt .Sprint (recovered )),
),
}
if config .StackTrace () {
opts = append (opts , trace .WithAttributes (
semconv .ExceptionStacktrace (recordStackTrace ()),
))
}
s .addEvent (semconv .ExceptionEventName , opts ...)
}
}
if s .executionTracerTaskEnd != nil {
s .mu .Unlock ()
s .executionTracerTaskEnd ()
s .mu .Lock ()
}
if config .Timestamp ().IsZero () {
s .endTime = et
} else {
s .endTime = config .Timestamp ()
}
s .mu .Unlock ()
if s .tracer .inst .Enabled () {
ctx := s .origCtx
if ctx == nil {
ctx = trace .ContextWithSpan (context .Background (), s )
}
defer s .tracer .inst .SpanEnded (ctx , s )
}
sps := s .tracer .provider .getSpanProcessors ()
if len (sps ) == 0 {
return
}
snap := s .snapshot ()
for _ , sp := range sps {
sp .sp .OnEnd (snap )
}
}
func monotonicEndTime(start time .Time ) time .Time {
return start .Add (time .Since (start ))
}
func (s *recordingSpan ) RecordError (err error , opts ...trace .EventOption ) {
if s == nil || err == nil {
return
}
if !s .IsRecording () {
return
}
opts = append (opts , trace .WithAttributes (
semconv .ExceptionType (typeStr (err )),
semconv .ExceptionMessage (err .Error()),
))
c := trace .NewEventConfig (opts ...)
if c .StackTrace () {
opts = append (opts , trace .WithAttributes (
semconv .ExceptionStacktrace (recordStackTrace ()),
))
}
s .AddEvent (semconv .ExceptionEventName , opts ...)
}
func typeStr(i any ) string {
t := reflect .TypeOf (i )
if t .PkgPath () == "" && t .Name () == "" {
return t .String ()
}
return fmt .Sprintf ("%s.%s" , t .PkgPath (), t .Name ())
}
func recordStackTrace() string {
stackTrace := make ([]byte , 2048 )
n := runtime .Stack (stackTrace , false )
return string (stackTrace [0 :n ])
}
func (s *recordingSpan ) AddEvent (name string , o ...trace .EventOption ) {
if s == nil {
return
}
s .mu .Lock ()
defer s .mu .Unlock ()
if !s .isRecording () {
return
}
s .addEvent (name , o ...)
}
func (s *recordingSpan ) addEvent (name string , o ...trace .EventOption ) {
c := trace .NewEventConfig (o ...)
attrs , _ , _ := attrnorm .KeyValuesDedupLimitDepth (
c .Attributes (),
s .tracer .provider .spanLimits .AttributeValueDepthLimit ,
)
e := Event {Name : name , Attributes : attrs , Time : c .Timestamp ()}
limit := s .tracer .provider .spanLimits .AttributePerEventCountLimit
if limit == 0 {
e .DroppedAttributeCount = len (e .Attributes )
e .Attributes = nil
} else if limit > 0 && len (e .Attributes ) > limit {
e .DroppedAttributeCount = len (e .Attributes ) - limit
e .Attributes = e .Attributes [:limit ]
}
s .events .add (e )
}
func (s *recordingSpan ) SetName (name string ) {
if s == nil {
return
}
s .mu .Lock ()
defer s .mu .Unlock ()
if !s .isRecording () {
return
}
s .name = name
}
func (s *recordingSpan ) Name () string {
s .mu .Lock ()
defer s .mu .Unlock ()
return s .name
}
func (s *recordingSpan ) Parent () trace .SpanContext {
s .mu .Lock ()
defer s .mu .Unlock ()
return s .parent
}
func (s *recordingSpan ) SpanKind () trace .SpanKind {
s .mu .Lock ()
defer s .mu .Unlock ()
return s .spanKind
}
func (s *recordingSpan ) StartTime () time .Time {
s .mu .Lock ()
defer s .mu .Unlock ()
return s .startTime
}
func (s *recordingSpan ) EndTime () time .Time {
s .mu .Lock ()
defer s .mu .Unlock ()
return s .endTime
}
func (s *recordingSpan ) Attributes () []attribute .KeyValue {
s .mu .Lock ()
defer s .mu .Unlock ()
s .dedupeAttrs ()
s .attributesShared = cap (s .attributes ) > 0
return s .attributes
}
func (s *recordingSpan ) dedupeAttrs () {
if !s .attributesDirty {
return
}
s .ensureAttrsWritable (len (s .attributes ))
exists := make (map [attribute .Key ]int , len (s .attributes ))
s .dedupeAttrsFromRecord (exists )
}
func (s *recordingSpan ) dedupeAttrsFromRecord (record map [attribute .Key ]int ) {
unique := s .attributes [:0 ]
for _ , a := range s .attributes {
if idx , ok := record [a .Key ]; ok {
unique [idx ] = a
} else {
unique = append (unique , a )
record [a .Key ] = len (unique ) - 1
}
}
clear (s .attributes [len (unique ):])
s .attributes = unique
s .attributesDirty = false
}
func (s *recordingSpan ) Links () []Link {
s .mu .Lock ()
defer s .mu .Unlock ()
if len (s .links .queue ) == 0 {
return []Link {}
}
return s .links .copy ()
}
func (s *recordingSpan ) Events () []Event {
s .mu .Lock ()
defer s .mu .Unlock ()
if len (s .events .queue ) == 0 {
return []Event {}
}
return s .events .copy ()
}
func (s *recordingSpan ) Status () Status {
s .mu .Lock ()
defer s .mu .Unlock ()
return s .status
}
func (s *recordingSpan ) InstrumentationScope () instrumentation .Scope {
s .mu .Lock ()
defer s .mu .Unlock ()
return s .tracer .instrumentationScope
}
func (s *recordingSpan ) InstrumentationLibrary () instrumentation .Library {
s .mu .Lock ()
defer s .mu .Unlock ()
return s .tracer .instrumentationScope
}
func (s *recordingSpan ) Resource () *resource .Resource {
s .mu .Lock ()
defer s .mu .Unlock ()
return s .tracer .provider .resource
}
func (s *recordingSpan ) AddLink (link trace .Link ) {
if s == nil {
return
}
if !link .SpanContext .IsValid () && len (link .Attributes ) == 0 &&
link .SpanContext .TraceState ().Len () == 0 {
return
}
s .mu .Lock ()
defer s .mu .Unlock ()
if !s .isRecording () {
return
}
attrs , _ , _ := attrnorm .KeyValuesDedupLimitDepth (
link .Attributes ,
s .tracer .provider .spanLimits .AttributeValueDepthLimit ,
)
l := Link {SpanContext : link .SpanContext , Attributes : attrs }
limit := s .tracer .provider .spanLimits .AttributePerLinkCountLimit
if limit == 0 {
l .DroppedAttributeCount = len (l .Attributes )
l .Attributes = nil
} else if limit > 0 && len (l .Attributes ) > limit {
l .DroppedAttributeCount = len (l .Attributes ) - limit
l .Attributes = l .Attributes [:limit ]
}
s .links .add (l )
}
func (s *recordingSpan ) DroppedAttributes () int {
s .mu .Lock ()
defer s .mu .Unlock ()
return s .droppedAttributes
}
func (s *recordingSpan ) DroppedLinks () int {
s .mu .Lock ()
defer s .mu .Unlock ()
return s .links .droppedCount
}
func (s *recordingSpan ) DroppedEvents () int {
s .mu .Lock ()
defer s .mu .Unlock ()
return s .events .droppedCount
}
func (s *recordingSpan ) ChildSpanCount () int {
s .mu .Lock ()
defer s .mu .Unlock ()
return s .childSpanCount
}
func (s *recordingSpan ) TracerProvider () trace .TracerProvider {
return s .tracer .provider
}
func (s *recordingSpan ) snapshot () ReadOnlySpan {
var sd snapshot
s .mu .Lock ()
defer s .mu .Unlock ()
sd .endTime = s .endTime
sd .instrumentationScope = s .tracer .instrumentationScope
sd .name = s .name
sd .parent = s .parent
sd .resource = s .tracer .provider .resource
sd .spanContext = s .spanContext
sd .spanKind = s .spanKind
sd .startTime = s .startTime
sd .status = s .status
sd .childSpanCount = s .childSpanCount
if len (s .attributes ) > 0 {
s .dedupeAttrs ()
sd .attributes = s .attributes
s .attributesShared = true
}
sd .droppedAttributeCount = s .droppedAttributes
if len (s .events .queue ) > 0 {
sd .events = s .events .copy ()
sd .droppedEventCount = s .events .droppedCount
}
if len (s .links .queue ) > 0 {
sd .links = s .links .copy ()
sd .droppedLinkCount = s .links .droppedCount
}
return &sd
}
func (s *recordingSpan ) addChild () {
if s == nil {
return
}
s .mu .Lock ()
defer s .mu .Unlock ()
if !s .isRecording () {
return
}
s .childSpanCount ++
}
func (*recordingSpan ) private () {}
func (s *recordingSpan ) runtimeTrace (ctx context .Context ) context .Context {
if !rt .IsEnabled () {
return ctx
}
nctx , task := rt .NewTask (ctx , s .name )
s .mu .Lock ()
s .executionTracerTaskEnd = task .End
s .mu .Unlock ()
return nctx
}
type nonRecordingSpan struct {
embedded .Span
tracer *tracer
sc trace .SpanContext
}
var _ trace .Span = nonRecordingSpan {}
func (s nonRecordingSpan ) SpanContext () trace .SpanContext { return s .sc }
func (nonRecordingSpan ) IsRecording () bool { return false }
func (nonRecordingSpan ) SetStatus (codes .Code , string ) {}
func (nonRecordingSpan ) SetError (bool ) {}
func (nonRecordingSpan ) SetAttributes (...attribute .KeyValue ) {}
func (nonRecordingSpan ) End (...trace .SpanEndOption ) {}
func (nonRecordingSpan ) RecordError (error , ...trace .EventOption ) {}
func (nonRecordingSpan ) AddEvent (string , ...trace .EventOption ) {}
func (nonRecordingSpan ) AddLink (trace .Link ) {}
func (nonRecordingSpan ) SetName (string ) {}
func (s nonRecordingSpan ) TracerProvider () trace .TracerProvider { return s .tracer .provider }
func isRecording(s SamplingResult ) bool {
return s .Decision == RecordOnly || s .Decision == RecordAndSample
}
func isSampled(s SamplingResult ) bool {
return s .Decision == RecordAndSample
}
type Status struct {
Code codes .Code
Description string
}
The pages are generated with Golds v0.8.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .