| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package trace |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
"errors" |
| 9 |
"fmt" |
| 10 |
"math" |
| 11 |
"strconv" |
| 12 |
"strings" |
| 13 |
"sync" |
| 14 |
"sync/atomic" |
| 15 |
"testing" |
| 16 |
"time" |
| 17 |
|
| 18 |
"github.com/google/go-cmp/cmp" |
| 19 |
"github.com/stretchr/testify/assert" |
| 20 |
"github.com/stretchr/testify/require" |
| 21 |
|
| 22 |
"go.opentelemetry.io/otel" |
| 23 |
"go.opentelemetry.io/otel/attribute" |
| 24 |
"go.opentelemetry.io/otel/codes" |
| 25 |
"go.opentelemetry.io/otel/sdk" |
| 26 |
"go.opentelemetry.io/otel/sdk/instrumentation" |
| 27 |
"go.opentelemetry.io/otel/sdk/metric" |
| 28 |
"go.opentelemetry.io/otel/sdk/metric/metricdata" |
| 29 |
"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest" |
| 30 |
"go.opentelemetry.io/otel/sdk/resource" |
| 31 |
"go.opentelemetry.io/otel/sdk/trace/internal/observ" |
| 32 |
semconv "go.opentelemetry.io/otel/semconv/v1.40.0" |
| 33 |
"go.opentelemetry.io/otel/semconv/v1.40.0/otelconv" |
| 34 |
"go.opentelemetry.io/otel/trace" |
| 35 |
) |
| 36 |
|
| 37 |
const envVarResourceAttributes = "OTEL_RESOURCE_ATTRIBUTES" |
| 38 |
|
| 39 |
type storingHandler struct { |
| 40 |
errs []error |
| 41 |
} |
| 42 |
|
| 43 |
func (s *storingHandler) Handle(err error) { |
| 44 |
s.errs = append(s.errs, err) |
| 45 |
} |
| 46 |
|
| 47 |
func (s *storingHandler) Reset() { |
| 48 |
s.errs = nil |
| 49 |
} |
| 50 |
|
| 51 |
var ( |
| 52 |
tid trace.TraceID |
| 53 |
sid trace.SpanID |
| 54 |
sc trace.SpanContext |
| 55 |
ts trace.TraceState |
| 56 |
|
| 57 |
handler = &storingHandler{} |
| 58 |
) |
| 59 |
|
| 60 |
func init() { |
| 61 |
tid, _ = trace.TraceIDFromHex("01020304050607080102040810203040") |
| 62 |
sid, _ = trace.SpanIDFromHex("0102040810203040") |
| 63 |
sc = trace.NewSpanContext(trace.SpanContextConfig{ |
| 64 |
TraceID: tid, |
| 65 |
SpanID: sid, |
| 66 |
TraceFlags: 0x1, |
| 67 |
}) |
| 68 |
ts, _ = trace.ParseTraceState("k=v") |
| 69 |
|
| 70 |
otel.SetErrorHandler(handler) |
| 71 |
} |
| 72 |
|
| 73 |
func TestTracerFollowsExpectedAPIBehaviour(t *testing.T) { |
| 74 |
harness := newHarness(t) |
| 75 |
|
| 76 |
harness.testTracerProvider(func() trace.TracerProvider { |
| 77 |
return NewTracerProvider(WithSampler(TraceIDRatioBased(0))) |
| 78 |
}) |
| 79 |
|
| 80 |
tp := NewTracerProvider(WithSampler(TraceIDRatioBased(0))) |
| 81 |
harness.testTracer(func() trace.Tracer { |
| 82 |
return tp.Tracer("") |
| 83 |
}) |
| 84 |
} |
| 85 |
|
| 86 |
type testExporter struct { |
| 87 |
mu sync.RWMutex |
| 88 |
idx map[string]int |
| 89 |
spans []*snapshot |
| 90 |
} |
| 91 |
|
| 92 |
func NewTestExporter() *testExporter { |
| 93 |
return &testExporter{idx: make(map[string]int)} |
| 94 |
} |
| 95 |
|
| 96 |
func (te *testExporter) ExportSpans(_ context.Context, spans []ReadOnlySpan) error { |
| 97 |
te.mu.Lock() |
| 98 |
defer te.mu.Unlock() |
| 99 |
|
| 100 |
i := len(te.spans) |
| 101 |
for _, s := range spans { |
| 102 |
te.idx[s.Name()] = i |
| 103 |
te.spans = append(te.spans, s.(*snapshot)) |
| 104 |
i++ |
| 105 |
} |
| 106 |
return nil |
| 107 |
} |
| 108 |
|
| 109 |
func (te *testExporter) Spans() []*snapshot { |
| 110 |
te.mu.RLock() |
| 111 |
defer te.mu.RUnlock() |
| 112 |
|
| 113 |
cp := make([]*snapshot, len(te.spans)) |
| 114 |
copy(cp, te.spans) |
| 115 |
return cp |
| 116 |
} |
| 117 |
|
| 118 |
func (te *testExporter) GetSpan(name string) (*snapshot, bool) { |
| 119 |
te.mu.RLock() |
| 120 |
defer te.mu.RUnlock() |
| 121 |
i, ok := te.idx[name] |
| 122 |
if !ok { |
| 123 |
return nil, false |
| 124 |
} |
| 125 |
return te.spans[i], true |
| 126 |
} |
| 127 |
|
| 128 |
func (te *testExporter) Len() int { |
| 129 |
te.mu.RLock() |
| 130 |
defer te.mu.RUnlock() |
| 131 |
return len(te.spans) |
| 132 |
} |
| 133 |
|
| 134 |
func (te *testExporter) Shutdown(context.Context) error { |
| 135 |
te.Reset() |
| 136 |
return nil |
| 137 |
} |
| 138 |
|
| 139 |
func (te *testExporter) Reset() { |
| 140 |
te.mu.Lock() |
| 141 |
defer te.mu.Unlock() |
| 142 |
te.idx = make(map[string]int) |
| 143 |
te.spans = te.spans[:0] |
| 144 |
} |
| 145 |
|
| 146 |
type testSampler struct { |
| 147 |
callCount int |
| 148 |
prefix string |
| 149 |
t *testing.T |
| 150 |
} |
| 151 |
|
| 152 |
func (ts *testSampler) ShouldSample(p SamplingParameters) SamplingResult { |
| 153 |
ts.callCount++ |
| 154 |
ts.t.Logf("called sampler for name %q", p.Name) |
| 155 |
decision := Drop |
| 156 |
if strings.HasPrefix(p.Name, ts.prefix) { |
| 157 |
decision = RecordAndSample |
| 158 |
} |
| 159 |
return SamplingResult{ |
| 160 |
Decision: decision, |
| 161 |
Attributes: []attribute.KeyValue{attribute.Int("callCount", ts.callCount)}, |
| 162 |
} |
| 163 |
} |
| 164 |
|
| 165 |
func (testSampler) Description() string { |
| 166 |
return "testSampler" |
| 167 |
} |
| 168 |
|
| 169 |
func TestSetName(t *testing.T) { |
| 170 |
tp := NewTracerProvider() |
| 171 |
|
| 172 |
type testCase struct { |
| 173 |
name string |
| 174 |
newName string |
| 175 |
} |
| 176 |
for idx, tt := range []testCase{ |
| 177 |
{ // 0 |
| 178 |
name: "foobar", |
| 179 |
newName: "foobaz", |
| 180 |
}, |
| 181 |
{ // 1 |
| 182 |
name: "foobar", |
| 183 |
newName: "barbaz", |
| 184 |
}, |
| 185 |
{ // 2 |
| 186 |
name: "barbar", |
| 187 |
newName: "barbaz", |
| 188 |
}, |
| 189 |
{ // 3 |
| 190 |
name: "barbar", |
| 191 |
newName: "foobar", |
| 192 |
}, |
| 193 |
} { |
| 194 |
sp := startNamedSpan(tp, "SetName", tt.name) |
| 195 |
if sdkspan, ok := sp.(*recordingSpan); ok { |
| 196 |
if sdkspan.Name() != tt.name { |
| 197 |
t.Errorf("%d: invalid name at span creation, expected %v, got %v", idx, tt.name, sdkspan.Name()) |
| 198 |
} |
| 199 |
} else { |
| 200 |
t.Errorf("%d: unable to coerce span to SDK span, is type %T", idx, sp) |
| 201 |
} |
| 202 |
sp.SetName(tt.newName) |
| 203 |
if sdkspan, ok := sp.(*recordingSpan); ok { |
| 204 |
if sdkspan.Name() != tt.newName { |
| 205 |
t.Errorf("%d: span name not changed, expected %v, got %v", idx, tt.newName, sdkspan.Name()) |
| 206 |
} |
| 207 |
} else { |
| 208 |
t.Errorf("%d: unable to coerce span to SDK span, is type %T", idx, sp) |
| 209 |
} |
| 210 |
sp.End() |
| 211 |
} |
| 212 |
} |
| 213 |
|
| 214 |
func TestSpanIsRecording(t *testing.T) { |
| 215 |
t.Run("while Span active", func(t *testing.T) { |
| 216 |
for name, tc := range map[string]struct { |
| 217 |
sampler Sampler |
| 218 |
want bool |
| 219 |
}{ |
| 220 |
"Always sample, recording on": {sampler: AlwaysSample(), want: true}, |
| 221 |
"Never sample recording off": {sampler: NeverSample(), want: false}, |
| 222 |
} { |
| 223 |
tp := NewTracerProvider(WithSampler(tc.sampler)) |
| 224 |
_, span := tp.Tracer(name).Start(t.Context(), "StartSpan") |
| 225 |
got := span.IsRecording() |
| 226 |
span.End() |
| 227 |
assert.Equal(t, tc.want, got, name) |
| 228 |
} |
| 229 |
}) |
| 230 |
|
| 231 |
t.Run("after Span end", func(t *testing.T) { |
| 232 |
for name, tc := range map[string]Sampler{ |
| 233 |
"Always Sample": AlwaysSample(), |
| 234 |
"Never Sample": NeverSample(), |
| 235 |
} { |
| 236 |
tp := NewTracerProvider(WithSampler(tc)) |
| 237 |
_, span := tp.Tracer(name).Start(t.Context(), "StartSpan") |
| 238 |
span.End() |
| 239 |
got := span.IsRecording() |
| 240 |
assert.False(t, got, name) |
| 241 |
} |
| 242 |
}) |
| 243 |
} |
| 244 |
|
| 245 |
func TestSampling(t *testing.T) { |
| 246 |
idg := defaultIDGenerator() |
| 247 |
const total = 10000 |
| 248 |
for name, tc := range map[string]struct { |
| 249 |
sampler Sampler |
| 250 |
expect float64 |
| 251 |
parent bool |
| 252 |
sampledParent bool |
| 253 |
}{ |
| 254 |
// Span w/o a parent |
| 255 |
"NeverSample": {sampler: NeverSample(), expect: 0}, |
| 256 |
"AlwaysSample": {sampler: AlwaysSample(), expect: 1.0}, |
| 257 |
"TraceIdRatioBased_-1": {sampler: TraceIDRatioBased(-1.0), expect: 0}, |
| 258 |
"TraceIdRatioBased_.25": {sampler: TraceIDRatioBased(0.25), expect: .25}, |
| 259 |
"TraceIdRatioBased_.50": {sampler: TraceIDRatioBased(0.50), expect: .5}, |
| 260 |
"TraceIdRatioBased_.75": {sampler: TraceIDRatioBased(0.75), expect: .75}, |
| 261 |
"TraceIdRatioBased_2.0": {sampler: TraceIDRatioBased(2.0), expect: 1}, |
| 262 |
|
| 263 |
// Spans w/o a parent and using ParentBased(DelegateSampler()) Sampler, receive DelegateSampler's sampling decision |
| 264 |
"ParentNeverSample": {sampler: ParentBased(NeverSample()), expect: 0}, |
| 265 |
"ParentAlwaysSample": {sampler: ParentBased(AlwaysSample()), expect: 1}, |
| 266 |
"ParentTraceIdRatioBased_.50": {sampler: ParentBased(TraceIDRatioBased(0.50)), expect: .5}, |
| 267 |
|
| 268 |
// An unadorned TraceIDRatioBased sampler ignores parent spans |
| 269 |
"UnsampledParentSpanWithTraceIdRatioBased_.25": {sampler: TraceIDRatioBased(0.25), expect: .25, parent: true}, |
| 270 |
"SampledParentSpanWithTraceIdRatioBased_.25": {sampler: TraceIDRatioBased(0.25), expect: .25, parent: true, sampledParent: true}, |
| 271 |
"UnsampledParentSpanWithTraceIdRatioBased_.50": {sampler: TraceIDRatioBased(0.50), expect: .5, parent: true}, |
| 272 |
"SampledParentSpanWithTraceIdRatioBased_.50": {sampler: TraceIDRatioBased(0.50), expect: .5, parent: true, sampledParent: true}, |
| 273 |
"UnsampledParentSpanWithTraceIdRatioBased_.75": {sampler: TraceIDRatioBased(0.75), expect: .75, parent: true}, |
| 274 |
"SampledParentSpanWithTraceIdRatioBased_.75": {sampler: TraceIDRatioBased(0.75), expect: .75, parent: true, sampledParent: true}, |
| 275 |
|
| 276 |
// Spans with a sampled parent but using NeverSample Sampler, are not sampled |
| 277 |
"SampledParentSpanWithNeverSample": {sampler: NeverSample(), expect: 0, parent: true, sampledParent: true}, |
| 278 |
|
| 279 |
// Spans with a sampled parent and using ParentBased(DelegateSampler()) Sampler, inherit the parent span's sampling status |
| 280 |
"SampledParentSpanWithParentNeverSample": {sampler: ParentBased(NeverSample()), expect: 1, parent: true, sampledParent: true}, |
| 281 |
"UnsampledParentSpanWithParentNeverSampler": {sampler: ParentBased(NeverSample()), expect: 0, parent: true, sampledParent: false}, |
| 282 |
"SampledParentSpanWithParentAlwaysSampler": {sampler: ParentBased(AlwaysSample()), expect: 1, parent: true, sampledParent: true}, |
| 283 |
"UnsampledParentSpanWithParentAlwaysSampler": {sampler: ParentBased(AlwaysSample()), expect: 0, parent: true, sampledParent: false}, |
| 284 |
"SampledParentSpanWithParentTraceIdRatioBased_.50": {sampler: ParentBased(TraceIDRatioBased(0.50)), expect: 1, parent: true, sampledParent: true}, |
| 285 |
"UnsampledParentSpanWithParentTraceIdRatioBased_.50": {sampler: ParentBased(TraceIDRatioBased(0.50)), expect: 0, parent: true, sampledParent: false}, |
| 286 |
} { |
| 287 |
t.Run(name, func(t *testing.T) { |
| 288 |
t.Parallel() |
| 289 |
p := NewTracerProvider(WithSampler(tc.sampler)) |
| 290 |
tr := p.Tracer("test") |
| 291 |
var sampled int |
| 292 |
for range total { |
| 293 |
ctx := t.Context() |
| 294 |
if tc.parent { |
| 295 |
tid, sid := idg.NewIDs(ctx) |
| 296 |
psc := trace.NewSpanContext(trace.SpanContextConfig{ |
| 297 |
TraceID: tid, |
| 298 |
SpanID: sid, |
| 299 |
}) |
| 300 |
if tc.sampledParent { |
| 301 |
psc = psc.WithTraceFlags(trace.FlagsSampled) |
| 302 |
} |
| 303 |
ctx = trace.ContextWithRemoteSpanContext(ctx, psc) |
| 304 |
} |
| 305 |
_, span := tr.Start(ctx, "test") |
| 306 |
if span.SpanContext().IsSampled() { |
| 307 |
sampled++ |
| 308 |
} |
| 309 |
} |
| 310 |
tolerance := 0.0 |
| 311 |
got := float64(sampled) / float64(total) |
| 312 |
|
| 313 |
if tc.expect > 0 && tc.expect < 1 { |
| 314 |
// See https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval |
| 315 |
const z = 4.75342 // This should succeed 99.9999% of the time |
| 316 |
tolerance = z * math.Sqrt(got*(1-got)/total) |
| 317 |
} |
| 318 |
|
| 319 |
diff := math.Abs(got - tc.expect) |
| 320 |
if diff > tolerance { |
| 321 |
t.Errorf("got %f (diff: %f), expected %f (w/tolerance: %f)", got, diff, tc.expect, tolerance) |
| 322 |
} |
| 323 |
}) |
| 324 |
} |
| 325 |
} |
| 326 |
|
| 327 |
func TestStartSpanWithParent(t *testing.T) { |
| 328 |
tp := NewTracerProvider() |
| 329 |
tr := tp.Tracer("SpanWithParent") |
| 330 |
ctx := t.Context() |
| 331 |
|
| 332 |
_, s1 := tr.Start(trace.ContextWithRemoteSpanContext(ctx, sc), "span1-unsampled-parent1") |
| 333 |
if err := checkChild(t, sc, s1); err != nil { |
| 334 |
t.Error(err) |
| 335 |
} |
| 336 |
|
| 337 |
_, s2 := tr.Start(trace.ContextWithRemoteSpanContext(ctx, sc), "span2-unsampled-parent1") |
| 338 |
if err := checkChild(t, sc, s2); err != nil { |
| 339 |
t.Error(err) |
| 340 |
} |
| 341 |
|
| 342 |
sc2 := sc.WithTraceState(ts) |
| 343 |
_, s3 := tr.Start(trace.ContextWithRemoteSpanContext(ctx, sc2), "span3-sampled-parent2") |
| 344 |
if err := checkChild(t, sc2, s3); err != nil { |
| 345 |
t.Error(err) |
| 346 |
} |
| 347 |
|
| 348 |
ctx2, s4 := tr.Start(trace.ContextWithRemoteSpanContext(ctx, sc2), "span4-sampled-parent2") |
| 349 |
if err := checkChild(t, sc2, s4); err != nil { |
| 350 |
t.Error(err) |
| 351 |
} |
| 352 |
|
| 353 |
s4Sc := s4.SpanContext() |
| 354 |
_, s5 := tr.Start(ctx2, "span5-implicit-childof-span4") |
| 355 |
if err := checkChild(t, s4Sc, s5); err != nil { |
| 356 |
t.Error(err) |
| 357 |
} |
| 358 |
} |
| 359 |
|
| 360 |
// Test we get a successful span as a new root if a nil context is sent in, as opposed to a panic. |
| 361 |
// See https://github.com/open-telemetry/opentelemetry-go/issues/3109 |
| 362 |
func TestStartSpanWithNilContext(t *testing.T) { |
| 363 |
tp := NewTracerProvider() |
| 364 |
tr := tp.Tracer("NoPanic") |
| 365 |
|
| 366 |
// nolint:staticcheck // no nil context, but that's the point of the test. |
| 367 |
assert.NotPanics(t, func() { tr.Start(nil, "should-not-panic") }) |
| 368 |
} |
| 369 |
|
| 370 |
func TestStartSpanNewRootNotSampled(t *testing.T) { |
| 371 |
alwaysSampleTp := NewTracerProvider() |
| 372 |
sampledTr := alwaysSampleTp.Tracer("AlwaysSampled") |
| 373 |
neverSampleTp := NewTracerProvider(WithSampler(ParentBased(NeverSample()))) |
| 374 |
neverSampledTr := neverSampleTp.Tracer("ParentBasedNeverSample") |
| 375 |
ctx := t.Context() |
| 376 |
|
| 377 |
ctx, s1 := sampledTr.Start(trace.ContextWithRemoteSpanContext(ctx, sc), "span1-sampled") |
| 378 |
if err := checkChild(t, sc, s1); err != nil { |
| 379 |
t.Error(err) |
| 380 |
} |
| 381 |
|
| 382 |
_, s2 := neverSampledTr.Start(ctx, "span2-no-newroot") |
| 383 |
if !s2.SpanContext().IsSampled() { |
| 384 |
t.Error( |
| 385 |
fmt.Errorf( |
| 386 |
"got child span is not sampled, want child span with sampler: ParentBased(NeverSample()) to be sampled", |
| 387 |
), |
| 388 |
) |
| 389 |
} |
| 390 |
|
| 391 |
// Adding WithNewRoot causes child spans to not sample based on parent context |
| 392 |
_, s3 := neverSampledTr.Start(ctx, "span3-newroot", trace.WithNewRoot()) |
| 393 |
if s3.SpanContext().IsSampled() { |
| 394 |
t.Error( |
| 395 |
fmt.Errorf( |
| 396 |
"got child span is sampled, want child span WithNewRoot() and with sampler: ParentBased(NeverSample()) to not be sampled", |
| 397 |
), |
| 398 |
) |
| 399 |
} |
| 400 |
} |
| 401 |
|
| 402 |
func TestSetSpanAttributesOnStart(t *testing.T) { |
| 403 |
te := NewTestExporter() |
| 404 |
tp := NewTracerProvider(WithSyncer(te), WithResource(resource.Empty())) |
| 405 |
span := startSpan(tp, |
| 406 |
"StartSpanAttribute", |
| 407 |
trace.WithAttributes(attribute.String("key1", "value1")), |
| 408 |
trace.WithAttributes(attribute.String("key2", "value2")), |
| 409 |
) |
| 410 |
got, err := endSpan(te, span) |
| 411 |
if err != nil { |
| 412 |
t.Fatal(err) |
| 413 |
} |
| 414 |
|
| 415 |
want := &snapshot{ |
| 416 |
spanContext: trace.NewSpanContext(trace.SpanContextConfig{ |
| 417 |
TraceID: tid, |
| 418 |
TraceFlags: 0x1, |
| 419 |
}), |
| 420 |
parent: sc.WithRemote(true), |
| 421 |
name: "span0", |
| 422 |
attributes: []attribute.KeyValue{ |
| 423 |
attribute.String("key1", "value1"), |
| 424 |
attribute.String("key2", "value2"), |
| 425 |
}, |
| 426 |
spanKind: trace.SpanKindInternal, |
| 427 |
instrumentationScope: instrumentation.Scope{Name: "StartSpanAttribute"}, |
| 428 |
} |
| 429 |
if diff := cmpDiff(got, want); diff != "" { |
| 430 |
t.Errorf("SetSpanAttributesOnStart: -got +want %s", diff) |
| 431 |
} |
| 432 |
} |
| 433 |
|
| 434 |
func TestSamplerAttributesLocalChildSpan(t *testing.T) { |
| 435 |
sampler := &testSampler{prefix: "span", t: t} |
| 436 |
te := NewTestExporter() |
| 437 |
tp := NewTracerProvider(WithSampler(sampler), WithSyncer(te), WithResource(resource.Empty())) |
| 438 |
|
| 439 |
ctx := t.Context() |
| 440 |
ctx, span := startLocalSpan(ctx, tp, "SpanOne", "span0") |
| 441 |
_, spanTwo := startLocalSpan(ctx, tp, "SpanTwo", "span1") |
| 442 |
|
| 443 |
spanTwo.End() |
| 444 |
span.End() |
| 445 |
|
| 446 |
got := te.Spans() |
| 447 |
require.Len(t, got, 2) |
| 448 |
// FILO order above means spanTwo <-> gotSpan0 and span <-> gotSpan1. |
| 449 |
gotSpan0, gotSpan1 := got[0], got[1] |
| 450 |
// Ensure sampler is called for local child spans by verifying the |
| 451 |
// attributes set by the sampler are set on the child span. |
| 452 |
assert.Equal(t, []attribute.KeyValue{attribute.Int("callCount", 2)}, gotSpan0.Attributes()) |
| 453 |
assert.Equal(t, []attribute.KeyValue{attribute.Int("callCount", 1)}, gotSpan1.Attributes()) |
| 454 |
} |
| 455 |
|
| 456 |
func TestSpanSetAttributes(t *testing.T) { |
| 457 |
attrs := [...]attribute.KeyValue{ |
| 458 |
attribute.String("key1", "value1"), |
| 459 |
attribute.String("key2", "value2"), |
| 460 |
attribute.String("key3", "value3"), |
| 461 |
attribute.String("key4", "value4"), |
| 462 |
attribute.String("key1", "value5"), |
| 463 |
attribute.String("key2", "value6"), |
| 464 |
attribute.String("key3", "value7"), |
| 465 |
} |
| 466 |
invalid := attribute.KeyValue{} |
| 467 |
|
| 468 |
tests := []struct { |
| 469 |
name string |
| 470 |
input [][]attribute.KeyValue |
| 471 |
wantAttrs []attribute.KeyValue |
| 472 |
wantDropped int |
| 473 |
}{ |
| 474 |
{ |
| 475 |
name: "array", |
| 476 |
input: [][]attribute.KeyValue{attrs[:3]}, |
| 477 |
wantAttrs: attrs[:3], |
| 478 |
}, |
| 479 |
{ |
| 480 |
name: "single_value:array", |
| 481 |
input: [][]attribute.KeyValue{attrs[:1], attrs[1:3]}, |
| 482 |
wantAttrs: attrs[:3], |
| 483 |
}, |
| 484 |
{ |
| 485 |
name: "array:single_value", |
| 486 |
input: [][]attribute.KeyValue{attrs[:2], attrs[2:3]}, |
| 487 |
wantAttrs: attrs[:3], |
| 488 |
}, |
| 489 |
{ |
| 490 |
name: "single_values", |
| 491 |
input: [][]attribute.KeyValue{attrs[:1], attrs[1:2], attrs[2:3]}, |
| 492 |
wantAttrs: attrs[:3], |
| 493 |
}, |
| 494 |
|
| 495 |
// The tracing specification states: |
| 496 |
// |
| 497 |
// For each unique attribute key, addition of which would result in |
| 498 |
// exceeding the limit, SDK MUST discard that key/value pair |
| 499 |
// |
| 500 |
// Therefore, adding attributes after the capacity is reached should |
| 501 |
// result in those attributes being dropped. |
| 502 |
|
| 503 |
{ |
| 504 |
name: "drop_last_added", |
| 505 |
input: [][]attribute.KeyValue{attrs[:3], attrs[3:4], attrs[3:4]}, |
| 506 |
wantAttrs: attrs[:3], |
| 507 |
wantDropped: 2, |
| 508 |
}, |
| 509 |
|
| 510 |
// The tracing specification states: |
| 511 |
// |
| 512 |
// Setting an attribute with the same key as an existing attribute |
| 513 |
// SHOULD overwrite the existing attribute's value. |
| 514 |
// |
| 515 |
// Therefore, attributes are updated regardless of capacity state. |
| 516 |
|
| 517 |
{ |
| 518 |
name: "single_value_update", |
| 519 |
input: [][]attribute.KeyValue{attrs[:1], attrs[:3]}, |
| 520 |
wantAttrs: attrs[:3], |
| 521 |
}, |
| 522 |
{ |
| 523 |
name: "all_update", |
| 524 |
input: [][]attribute.KeyValue{attrs[:3], attrs[4:7]}, |
| 525 |
wantAttrs: attrs[4:7], |
| 526 |
}, |
| 527 |
{ |
| 528 |
name: "all_update/multi", |
| 529 |
input: [][]attribute.KeyValue{attrs[:3], attrs[4:7], attrs[:3]}, |
| 530 |
wantAttrs: attrs[:3], |
| 531 |
}, |
| 532 |
{ |
| 533 |
name: "deduplicate/under_capacity", |
| 534 |
input: [][]attribute.KeyValue{attrs[:1], attrs[:1], attrs[:1]}, |
| 535 |
wantAttrs: attrs[:1], |
| 536 |
}, |
| 537 |
{ |
| 538 |
name: "deduplicate/over_capacity", |
| 539 |
input: [][]attribute.KeyValue{attrs[:1], attrs[:1], attrs[:1], attrs[:3]}, |
| 540 |
wantAttrs: attrs[:3], |
| 541 |
}, |
| 542 |
{ |
| 543 |
name: "deduplicate/added", |
| 544 |
input: [][]attribute.KeyValue{ |
| 545 |
attrs[:2], |
| 546 |
{attrs[2], attrs[2], attrs[2]}, |
| 547 |
}, |
| 548 |
wantAttrs: attrs[:3], |
| 549 |
}, |
| 550 |
{ |
| 551 |
name: "deduplicate/added_at_cappacity", |
| 552 |
input: [][]attribute.KeyValue{ |
| 553 |
attrs[:3], |
| 554 |
{attrs[2], attrs[2], attrs[2]}, |
| 555 |
}, |
| 556 |
wantAttrs: attrs[:3], |
| 557 |
}, |
| 558 |
{ |
| 559 |
name: "invalid", |
| 560 |
input: [][]attribute.KeyValue{ |
| 561 |
{invalid}, |
| 562 |
}, |
| 563 |
wantDropped: 1, |
| 564 |
}, |
| 565 |
{ |
| 566 |
name: "invalid_with_valid", |
| 567 |
input: [][]attribute.KeyValue{ |
| 568 |
{invalid, attrs[0]}, |
| 569 |
}, |
| 570 |
wantAttrs: attrs[:1], |
| 571 |
wantDropped: 1, |
| 572 |
}, |
| 573 |
{ |
| 574 |
name: "invalid_over_capacity", |
| 575 |
input: [][]attribute.KeyValue{ |
| 576 |
{invalid, invalid, invalid, invalid, attrs[0]}, |
| 577 |
}, |
| 578 |
wantAttrs: attrs[:1], |
| 579 |
wantDropped: 4, |
| 580 |
}, |
| 581 |
{ |
| 582 |
name: "valid:invalid/under_capacity", |
| 583 |
input: [][]attribute.KeyValue{ |
| 584 |
attrs[:1], |
| 585 |
{invalid}, |
| 586 |
}, |
| 587 |
wantAttrs: attrs[:1], |
| 588 |
wantDropped: 1, |
| 589 |
}, |
| 590 |
{ |
| 591 |
name: "valid:invalid/over_capacity", |
| 592 |
input: [][]attribute.KeyValue{ |
| 593 |
attrs[:1], |
| 594 |
{invalid, invalid, invalid, invalid}, |
| 595 |
}, |
| 596 |
wantAttrs: attrs[:1], |
| 597 |
wantDropped: 4, |
| 598 |
}, |
| 599 |
{ |
| 600 |
name: "valid_at_capacity:invalid", |
| 601 |
input: [][]attribute.KeyValue{ |
| 602 |
attrs[:3], |
| 603 |
{invalid, invalid, invalid, invalid}, |
| 604 |
}, |
| 605 |
wantAttrs: attrs[:3], |
| 606 |
wantDropped: 4, |
| 607 |
}, |
| 608 |
} |
| 609 |
|
| 610 |
const ( |
| 611 |
capacity = 3 |
| 612 |
instName = "TestSpanAttributeCapacity" |
| 613 |
spanName = "test span" |
| 614 |
) |
| 615 |
|
| 616 |
for _, test := range tests { |
| 617 |
t.Run(test.name, func(t *testing.T) { |
| 618 |
te := NewTestExporter() |
| 619 |
sl := NewSpanLimits() |
| 620 |
sl.AttributeCountLimit = capacity |
| 621 |
tp := NewTracerProvider(WithSyncer(te), WithSpanLimits(sl)) |
| 622 |
_, span := tp.Tracer(instName).Start(t.Context(), spanName) |
| 623 |
for _, a := range test.input { |
| 624 |
span.SetAttributes(a...) |
| 625 |
} |
| 626 |
span.End() |
| 627 |
|
| 628 |
require.Implements(t, (*ReadOnlySpan)(nil), span) |
| 629 |
roSpan := span.(ReadOnlySpan) |
| 630 |
|
| 631 |
// Ensure the span itself is valid. |
| 632 |
assert.ElementsMatch(t, test.wantAttrs, roSpan.Attributes(), "expected attributes") |
| 633 |
assert.Equal(t, test.wantDropped, roSpan.DroppedAttributes(), "dropped attributes") |
| 634 |
|
| 635 |
snap, ok := te.GetSpan(spanName) |
| 636 |
require.Truef(t, ok, "span %s not exported", spanName) |
| 637 |
|
| 638 |
// Ensure the exported span snapshot is valid. |
| 639 |
assert.ElementsMatch(t, test.wantAttrs, snap.Attributes(), "expected attributes") |
| 640 |
assert.Equal(t, test.wantDropped, snap.DroppedAttributes(), "dropped attributes") |
| 641 |
}) |
| 642 |
} |
| 643 |
} |
| 644 |
|
| 645 |
func TestEvents(t *testing.T) { |
| 646 |
te := NewTestExporter() |
| 647 |
tp := NewTracerProvider(WithSyncer(te), WithResource(resource.Empty())) |
| 648 |
|
| 649 |
span := startSpan(tp, "Events") |
| 650 |
k1v1 := attribute.String("key1", "value1") |
| 651 |
k2v2 := attribute.Bool("key2", true) |
| 652 |
k3v3 := attribute.Int64("key3", 3) |
| 653 |
|
| 654 |
span.AddEvent("foo", trace.WithAttributes(attribute.String("key1", "value1"))) |
| 655 |
span.AddEvent("bar", trace.WithAttributes( |
| 656 |
attribute.Bool("key2", true), |
| 657 |
attribute.Int64("key3", 3), |
| 658 |
)) |
| 659 |
got, err := endSpan(te, span) |
| 660 |
if err != nil { |
| 661 |
t.Fatal(err) |
| 662 |
} |
| 663 |
|
| 664 |
for i := range got.Events() { |
| 665 |
if !checkTime(&got.Events()[i].Time) { |
| 666 |
t.Error("exporting span: expected nonzero Event Time") |
| 667 |
} |
| 668 |
} |
| 669 |
|
| 670 |
want := &snapshot{ |
| 671 |
spanContext: trace.NewSpanContext(trace.SpanContextConfig{ |
| 672 |
TraceID: tid, |
| 673 |
TraceFlags: 0x1, |
| 674 |
}), |
| 675 |
parent: sc.WithRemote(true), |
| 676 |
name: "span0", |
| 677 |
events: []Event{ |
| 678 |
{Name: "foo", Attributes: []attribute.KeyValue{k1v1}}, |
| 679 |
{Name: "bar", Attributes: []attribute.KeyValue{k2v2, k3v3}}, |
| 680 |
}, |
| 681 |
spanKind: trace.SpanKindInternal, |
| 682 |
instrumentationScope: instrumentation.Scope{Name: "Events"}, |
| 683 |
} |
| 684 |
if diff := cmpDiff(got, want); diff != "" { |
| 685 |
t.Errorf("Message Events: -got +want %s", diff) |
| 686 |
} |
| 687 |
} |
| 688 |
|
| 689 |
func TestEventsOverLimit(t *testing.T) { |
| 690 |
te := NewTestExporter() |
| 691 |
sl := NewSpanLimits() |
| 692 |
sl.EventCountLimit = 2 |
| 693 |
tp := NewTracerProvider(WithSpanLimits(sl), WithSyncer(te), WithResource(resource.Empty())) |
| 694 |
|
| 695 |
span := startSpan(tp, "EventsOverLimit") |
| 696 |
k1v1 := attribute.String("key1", "value1") |
| 697 |
k2v2 := attribute.Bool("key2", false) |
| 698 |
k3v3 := attribute.String("key3", "value3") |
| 699 |
|
| 700 |
span.AddEvent("fooDrop", trace.WithAttributes(attribute.String("key1", "value1"))) |
| 701 |
span.AddEvent("barDrop", trace.WithAttributes( |
| 702 |
attribute.Bool("key2", true), |
| 703 |
attribute.String("key3", "value3"), |
| 704 |
)) |
| 705 |
span.AddEvent("foo", trace.WithAttributes(attribute.String("key1", "value1"))) |
| 706 |
span.AddEvent("bar", trace.WithAttributes( |
| 707 |
attribute.Bool("key2", false), |
| 708 |
attribute.String("key3", "value3"), |
| 709 |
)) |
| 710 |
got, err := endSpan(te, span) |
| 711 |
if err != nil { |
| 712 |
t.Fatal(err) |
| 713 |
} |
| 714 |
|
| 715 |
for i := range got.Events() { |
| 716 |
if !checkTime(&got.Events()[i].Time) { |
| 717 |
t.Error("exporting span: expected nonzero Event Time") |
| 718 |
} |
| 719 |
} |
| 720 |
|
| 721 |
want := &snapshot{ |
| 722 |
spanContext: trace.NewSpanContext(trace.SpanContextConfig{ |
| 723 |
TraceID: tid, |
| 724 |
TraceFlags: 0x1, |
| 725 |
}), |
| 726 |
parent: sc.WithRemote(true), |
| 727 |
name: "span0", |
| 728 |
events: []Event{ |
| 729 |
{Name: "foo", Attributes: []attribute.KeyValue{k1v1}}, |
| 730 |
{Name: "bar", Attributes: []attribute.KeyValue{k2v2, k3v3}}, |
| 731 |
}, |
| 732 |
droppedEventCount: 2, |
| 733 |
spanKind: trace.SpanKindInternal, |
| 734 |
instrumentationScope: instrumentation.Scope{Name: "EventsOverLimit"}, |
| 735 |
} |
| 736 |
if diff := cmpDiff(got, want); diff != "" { |
| 737 |
t.Errorf("Message Event over limit: -got +want %s", diff) |
| 738 |
} |
| 739 |
} |
| 740 |
|
| 741 |
func TestLinks(t *testing.T) { |
| 742 |
te := NewTestExporter() |
| 743 |
tp := NewTracerProvider(WithSyncer(te), WithResource(resource.Empty())) |
| 744 |
|
| 745 |
k1v1 := attribute.String("key1", "value1") |
| 746 |
k2v2 := attribute.String("key2", "value2") |
| 747 |
k3v3 := attribute.String("key3", "value3") |
| 748 |
|
| 749 |
sc1 := trace.NewSpanContext( |
| 750 |
trace.SpanContextConfig{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}}, |
| 751 |
) |
| 752 |
sc2 := trace.NewSpanContext( |
| 753 |
trace.SpanContextConfig{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}}, |
| 754 |
) |
| 755 |
|
| 756 |
l1 := trace.Link{SpanContext: sc1, Attributes: []attribute.KeyValue{k1v1}} |
| 757 |
l2 := trace.Link{SpanContext: sc2, Attributes: []attribute.KeyValue{k2v2, k3v3}} |
| 758 |
|
| 759 |
links := []trace.Link{l1, l2} |
| 760 |
span := startSpan(tp, "Links", trace.WithLinks(links...)) |
| 761 |
|
| 762 |
got, err := endSpan(te, span) |
| 763 |
if err != nil { |
| 764 |
t.Fatal(err) |
| 765 |
} |
| 766 |
|
| 767 |
want := &snapshot{ |
| 768 |
spanContext: trace.NewSpanContext(trace.SpanContextConfig{ |
| 769 |
TraceID: tid, |
| 770 |
TraceFlags: 0x1, |
| 771 |
}), |
| 772 |
parent: sc.WithRemote(true), |
| 773 |
name: "span0", |
| 774 |
links: []Link{{l1.SpanContext, l1.Attributes, 0}, {l2.SpanContext, l2.Attributes, 0}}, |
| 775 |
spanKind: trace.SpanKindInternal, |
| 776 |
instrumentationScope: instrumentation.Scope{Name: "Links"}, |
| 777 |
} |
| 778 |
if diff := cmpDiff(got, want); diff != "" { |
| 779 |
t.Errorf("Link: -got +want %s", diff) |
| 780 |
} |
| 781 |
sc1 = trace.NewSpanContext(trace.SpanContextConfig{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}}) |
| 782 |
|
| 783 |
span1 := startSpan(tp, "name", trace.WithLinks([]trace.Link{ |
| 784 |
{SpanContext: trace.SpanContext{}}, |
| 785 |
{SpanContext: sc1}, |
| 786 |
}...)) |
| 787 |
|
| 788 |
sdkspan, _ := span1.(*recordingSpan) |
| 789 |
require.Len(t, sdkspan.Links(), 1) |
| 790 |
} |
| 791 |
|
| 792 |
func TestLinksOverLimit(t *testing.T) { |
| 793 |
te := NewTestExporter() |
| 794 |
|
| 795 |
sc1 := trace.NewSpanContext( |
| 796 |
trace.SpanContextConfig{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}}, |
| 797 |
) |
| 798 |
sc2 := trace.NewSpanContext( |
| 799 |
trace.SpanContextConfig{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}}, |
| 800 |
) |
| 801 |
sc3 := trace.NewSpanContext( |
| 802 |
trace.SpanContextConfig{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}}, |
| 803 |
) |
| 804 |
|
| 805 |
sl := NewSpanLimits() |
| 806 |
sl.LinkCountLimit = 2 |
| 807 |
tp := NewTracerProvider(WithSpanLimits(sl), WithSyncer(te), WithResource(resource.Empty())) |
| 808 |
|
| 809 |
span := startSpan(tp, "LinksOverLimit", |
| 810 |
trace.WithLinks( |
| 811 |
trace.Link{SpanContext: sc1, Attributes: []attribute.KeyValue{attribute.String("key1", "value1")}}, |
| 812 |
trace.Link{SpanContext: sc2, Attributes: []attribute.KeyValue{attribute.String("key2", "value2")}}, |
| 813 |
trace.Link{SpanContext: sc3, Attributes: []attribute.KeyValue{attribute.String("key3", "value3")}}, |
| 814 |
), |
| 815 |
) |
| 816 |
|
| 817 |
k2v2 := attribute.String("key2", "value2") |
| 818 |
k3v3 := attribute.String("key3", "value3") |
| 819 |
|
| 820 |
got, err := endSpan(te, span) |
| 821 |
if err != nil { |
| 822 |
t.Fatal(err) |
| 823 |
} |
| 824 |
|
| 825 |
want := &snapshot{ |
| 826 |
spanContext: trace.NewSpanContext(trace.SpanContextConfig{ |
| 827 |
TraceID: tid, |
| 828 |
TraceFlags: 0x1, |
| 829 |
}), |
| 830 |
parent: sc.WithRemote(true), |
| 831 |
name: "span0", |
| 832 |
links: []Link{ |
| 833 |
{SpanContext: sc2, Attributes: []attribute.KeyValue{k2v2}, DroppedAttributeCount: 0}, |
| 834 |
{SpanContext: sc3, Attributes: []attribute.KeyValue{k3v3}, DroppedAttributeCount: 0}, |
| 835 |
}, |
| 836 |
droppedLinkCount: 1, |
| 837 |
spanKind: trace.SpanKindInternal, |
| 838 |
instrumentationScope: instrumentation.Scope{Name: "LinksOverLimit"}, |
| 839 |
} |
| 840 |
if diff := cmpDiff(got, want); diff != "" { |
| 841 |
t.Errorf("Link over limit: -got +want %s", diff) |
| 842 |
} |
| 843 |
} |
| 844 |
|
| 845 |
func TestSetSpanName(t *testing.T) { |
| 846 |
te := NewTestExporter() |
| 847 |
tp := NewTracerProvider(WithSyncer(te), WithResource(resource.Empty())) |
| 848 |
ctx := t.Context() |
| 849 |
|
| 850 |
want := "SpanName-1" |
| 851 |
ctx = trace.ContextWithRemoteSpanContext(ctx, sc) |
| 852 |
_, span := tp.Tracer("SetSpanName").Start(ctx, "SpanName-1") |
| 853 |
got, err := endSpan(te, span) |
| 854 |
if err != nil { |
| 855 |
t.Fatal(err) |
| 856 |
} |
| 857 |
|
| 858 |
if got.Name() != want { |
| 859 |
t.Errorf("span.Name: got %q; want %q", got.Name(), want) |
| 860 |
} |
| 861 |
} |
| 862 |
|
| 863 |
func TestSetSpanStatus(t *testing.T) { |
| 864 |
te := NewTestExporter() |
| 865 |
tp := NewTracerProvider(WithSyncer(te), WithResource(resource.Empty())) |
| 866 |
|
| 867 |
span := startSpan(tp, "SpanStatus") |
| 868 |
span.SetStatus(codes.Error, "Error") |
| 869 |
got, err := endSpan(te, span) |
| 870 |
if err != nil { |
| 871 |
t.Fatal(err) |
| 872 |
} |
| 873 |
|
| 874 |
want := &snapshot{ |
| 875 |
spanContext: trace.NewSpanContext(trace.SpanContextConfig{ |
| 876 |
TraceID: tid, |
| 877 |
TraceFlags: 0x1, |
| 878 |
}), |
| 879 |
parent: sc.WithRemote(true), |
| 880 |
name: "span0", |
| 881 |
spanKind: trace.SpanKindInternal, |
| 882 |
status: Status{ |
| 883 |
Code: codes.Error, |
| 884 |
Description: "Error", |
| 885 |
}, |
| 886 |
instrumentationScope: instrumentation.Scope{Name: "SpanStatus"}, |
| 887 |
} |
| 888 |
if diff := cmpDiff(got, want); diff != "" { |
| 889 |
t.Errorf("SetSpanStatus: -got +want %s", diff) |
| 890 |
} |
| 891 |
} |
| 892 |
|
| 893 |
func TestSetSpanStatusWithoutMessageWhenStatusIsNotError(t *testing.T) { |
| 894 |
te := NewTestExporter() |
| 895 |
tp := NewTracerProvider(WithSyncer(te), WithResource(resource.Empty())) |
| 896 |
|
| 897 |
span := startSpan(tp, "SpanStatus") |
| 898 |
span.SetStatus(codes.Ok, "This message will be ignored") |
| 899 |
got, err := endSpan(te, span) |
| 900 |
if err != nil { |
| 901 |
t.Fatal(err) |
| 902 |
} |
| 903 |
|
| 904 |
want := &snapshot{ |
| 905 |
spanContext: trace.NewSpanContext(trace.SpanContextConfig{ |
| 906 |
TraceID: tid, |
| 907 |
TraceFlags: 0x1, |
| 908 |
}), |
| 909 |
parent: sc.WithRemote(true), |
| 910 |
name: "span0", |
| 911 |
spanKind: trace.SpanKindInternal, |
| 912 |
status: Status{ |
| 913 |
Code: codes.Ok, |
| 914 |
Description: "", |
| 915 |
}, |
| 916 |
instrumentationScope: instrumentation.Scope{Name: "SpanStatus"}, |
| 917 |
} |
| 918 |
if diff := cmpDiff(got, want); diff != "" { |
| 919 |
t.Errorf("SetSpanStatus: -got +want %s", diff) |
| 920 |
} |
| 921 |
} |
| 922 |
|
| 923 |
func cmpDiff(x, y any) string { |
| 924 |
return cmp.Diff(x, y, |
| 925 |
cmp.AllowUnexported(snapshot{}), |
| 926 |
cmp.AllowUnexported(attribute.Value{}), |
| 927 |
cmp.AllowUnexported(Event{}), |
| 928 |
cmp.AllowUnexported(trace.TraceState{}), |
| 929 |
cmp.Comparer(func(x, y attribute.Set) bool { |
| 930 |
return x.Equals(&y) |
| 931 |
}), |
| 932 |
) |
| 933 |
} |
| 934 |
|
| 935 |
// checkChild is test utility function that tests that c has fields set appropriately, |
| 936 |
// given that it is a child span of p. |
| 937 |
func checkChild(t *testing.T, p trace.SpanContext, apiSpan trace.Span) error { |
| 938 |
s := apiSpan.(*recordingSpan) |
| 939 |
if s == nil { |
| 940 |
return fmt.Errorf("got nil child span, want non-nil") |
| 941 |
} |
| 942 |
if got, want := s.spanContext.TraceID().String(), p.TraceID().String(); got != want { |
| 943 |
return fmt.Errorf("got child trace ID %s, want %s", got, want) |
| 944 |
} |
| 945 |
if childID, parentID := s.spanContext.SpanID().String(), p.SpanID().String(); childID == parentID { |
| 946 |
return fmt.Errorf("got child span ID %s, parent span ID %s; want unequal IDs", childID, parentID) |
| 947 |
} |
| 948 |
if got, want := s.spanContext.TraceFlags(), p.TraceFlags(); got != want { |
| 949 |
return fmt.Errorf("got child trace options %d, want %d", got, want) |
| 950 |
} |
| 951 |
got, want := s.spanContext.TraceState(), p.TraceState() |
| 952 |
assert.Equal(t, want, got) |
| 953 |
return nil |
| 954 |
} |
| 955 |
|
| 956 |
// startSpan starts a span with a name "span0". See startNamedSpan for |
| 957 |
// details. |
| 958 |
func startSpan(tp *TracerProvider, trName string, args ...trace.SpanStartOption) trace.Span { |
| 959 |
return startNamedSpan(tp, trName, "span0", args...) |
| 960 |
} |
| 961 |
|
| 962 |
// startNamed Span is a test utility func that starts a span with a |
| 963 |
// passed name and with remote span context as parent. The remote span |
| 964 |
// context contains TraceFlags with sampled bit set. This allows the |
| 965 |
// span to be automatically sampled. |
| 966 |
func startNamedSpan(tp *TracerProvider, trName, name string, args ...trace.SpanStartOption) trace.Span { |
| 967 |
_, span := tp.Tracer(trName).Start( |
| 968 |
trace.ContextWithRemoteSpanContext(context.Background(), sc), |
| 969 |
name, |
| 970 |
args..., |
| 971 |
) |
| 972 |
return span |
| 973 |
} |
| 974 |
|
| 975 |
// startLocalSpan is a test utility func that starts a span with a |
| 976 |
// passed name and with the passed context. The context is returned |
| 977 |
// along with the span so this parent can be used to create child |
| 978 |
// spans. |
| 979 |
func startLocalSpan( |
| 980 |
ctx context.Context, |
| 981 |
tp *TracerProvider, |
| 982 |
trName, name string, |
| 983 |
args ...trace.SpanStartOption, |
| 984 |
) (context.Context, trace.Span) { |
| 985 |
ctx, span := tp.Tracer(trName).Start( |
| 986 |
ctx, |
| 987 |
name, |
| 988 |
args..., |
| 989 |
) |
| 990 |
return ctx, span |
| 991 |
} |
| 992 |
|
| 993 |
// endSpan is a test utility function that ends the span in the context and |
| 994 |
// returns the exported span. |
| 995 |
// It requires that span be sampled using one of these methods |
| 996 |
// 1. Passing parent span context in context |
| 997 |
// 2. Use WithSampler(AlwaysSample()) |
| 998 |
// 3. Configuring AlwaysSample() as default sampler |
| 999 |
// |
| 1000 |
// It also does some basic tests on the span. |
| 1001 |
// It also clears spanID in the to make the comparison easier. |
| 1002 |
func endSpan(te *testExporter, span trace.Span) (*snapshot, error) { |
| 1003 |
if !span.IsRecording() { |
| 1004 |
return nil, fmt.Errorf("method IsRecording: got false, want true") |
| 1005 |
} |
| 1006 |
if !span.SpanContext().IsSampled() { |
| 1007 |
return nil, fmt.Errorf("method IsSampled: got false, want true") |
| 1008 |
} |
| 1009 |
span.End() |
| 1010 |
if te.Len() != 1 { |
| 1011 |
return nil, fmt.Errorf("got %d exported spans, want one span", te.Len()) |
| 1012 |
} |
| 1013 |
got := te.Spans()[0] |
| 1014 |
if !got.SpanContext().SpanID().IsValid() { |
| 1015 |
return nil, fmt.Errorf("exporting span: expected nonzero SpanID") |
| 1016 |
} |
| 1017 |
got.spanContext = got.SpanContext().WithSpanID(trace.SpanID{}) |
| 1018 |
if !checkTime(&got.startTime) { |
| 1019 |
return nil, fmt.Errorf("exporting span: expected nonzero StartTime") |
| 1020 |
} |
| 1021 |
if !checkTime(&got.endTime) { |
| 1022 |
return nil, fmt.Errorf("exporting span: expected nonzero EndTime") |
| 1023 |
} |
| 1024 |
return got, nil |
| 1025 |
} |
| 1026 |
|
| 1027 |
// checkTime checks that a nonzero time was set in x, then clears it. |
| 1028 |
func checkTime(x *time.Time) bool { |
| 1029 |
if x.IsZero() { |
| 1030 |
return false |
| 1031 |
} |
| 1032 |
*x = time.Time{} |
| 1033 |
return true |
| 1034 |
} |
| 1035 |
|
| 1036 |
func TestEndSpanTwice(t *testing.T) { |
| 1037 |
te := NewTestExporter() |
| 1038 |
tp := NewTracerProvider(WithSyncer(te)) |
| 1039 |
|
| 1040 |
st := time.Now() |
| 1041 |
et1 := st.Add(100 * time.Millisecond) |
| 1042 |
et2 := st.Add(200 * time.Millisecond) |
| 1043 |
|
| 1044 |
span := startSpan(tp, "EndSpanTwice", trace.WithTimestamp(st)) |
| 1045 |
span.End(trace.WithTimestamp(et1)) |
| 1046 |
span.End(trace.WithTimestamp(et2)) |
| 1047 |
|
| 1048 |
if te.Len() != 1 { |
| 1049 |
t.Fatalf("expected only a single span, got %#v", te.Spans()) |
| 1050 |
} |
| 1051 |
|
| 1052 |
ro := span.(ReadOnlySpan) |
| 1053 |
if ro.EndTime() != et1 { |
| 1054 |
t.Fatalf("2nd call to End() should not modify end time") |
| 1055 |
} |
| 1056 |
} |
| 1057 |
|
| 1058 |
func TestStartSpanAfterEnd(t *testing.T) { |
| 1059 |
te := NewTestExporter() |
| 1060 |
tp := NewTracerProvider(WithSampler(AlwaysSample()), WithSyncer(te)) |
| 1061 |
ctx := t.Context() |
| 1062 |
|
| 1063 |
tr := tp.Tracer("SpanAfterEnd") |
| 1064 |
ctx, span0 := tr.Start(trace.ContextWithRemoteSpanContext(ctx, sc), "parent") |
| 1065 |
ctx1, span1 := tr.Start(ctx, "span-1") |
| 1066 |
span1.End() |
| 1067 |
// Start a new span with the context containing span-1 |
| 1068 |
// even though span-1 is ended, we still add this as a new child of span-1 |
| 1069 |
_, span2 := tr.Start(ctx1, "span-2") |
| 1070 |
span2.End() |
| 1071 |
span0.End() |
| 1072 |
if got, want := te.Len(), 3; got != want { |
| 1073 |
t.Fatalf("len(%#v) = %d; want %d", te.Spans(), got, want) |
| 1074 |
} |
| 1075 |
|
| 1076 |
gotParent, ok := te.GetSpan("parent") |
| 1077 |
if !ok { |
| 1078 |
t.Fatal("parent not recorded") |
| 1079 |
} |
| 1080 |
gotSpan1, ok := te.GetSpan("span-1") |
| 1081 |
if !ok { |
| 1082 |
t.Fatal("span-1 not recorded") |
| 1083 |
} |
| 1084 |
gotSpan2, ok := te.GetSpan("span-2") |
| 1085 |
if !ok { |
| 1086 |
t.Fatal("span-2 not recorded") |
| 1087 |
} |
| 1088 |
|
| 1089 |
if got, want := gotSpan1.SpanContext().TraceID(), gotParent.SpanContext().TraceID(); got != want { |
| 1090 |
t.Errorf("span-1.TraceID=%q; want %q", got, want) |
| 1091 |
} |
| 1092 |
if got, want := gotSpan2.SpanContext().TraceID(), gotParent.SpanContext().TraceID(); got != want { |
| 1093 |
t.Errorf("span-2.TraceID=%q; want %q", got, want) |
| 1094 |
} |
| 1095 |
if got, want := gotSpan1.Parent().SpanID(), gotParent.SpanContext().SpanID(); got != want { |
| 1096 |
t.Errorf("span-1.ParentSpanID=%q; want %q (parent.SpanID)", got, want) |
| 1097 |
} |
| 1098 |
if got, want := gotSpan2.Parent().SpanID(), gotSpan1.SpanContext().SpanID(); got != want { |
| 1099 |
t.Errorf("span-2.ParentSpanID=%q; want %q (span1.SpanID)", got, want) |
| 1100 |
} |
| 1101 |
} |
| 1102 |
|
| 1103 |
func TestChildSpanCount(t *testing.T) { |
| 1104 |
te := NewTestExporter() |
| 1105 |
tp := NewTracerProvider(WithSampler(AlwaysSample()), WithSyncer(te)) |
| 1106 |
|
| 1107 |
tr := tp.Tracer("ChidSpanCount") |
| 1108 |
ctx, span0 := tr.Start(t.Context(), "parent") |
| 1109 |
ctx1, span1 := tr.Start(ctx, "span-1") |
| 1110 |
_, span2 := tr.Start(ctx1, "span-2") |
| 1111 |
span2.End() |
| 1112 |
span1.End() |
| 1113 |
|
| 1114 |
_, span3 := tr.Start(ctx, "span-3") |
| 1115 |
span3.End() |
| 1116 |
span0.End() |
| 1117 |
if got, want := te.Len(), 4; got != want { |
| 1118 |
t.Fatalf("len(%#v) = %d; want %d", te.Spans(), got, want) |
| 1119 |
} |
| 1120 |
|
| 1121 |
gotParent, ok := te.GetSpan("parent") |
| 1122 |
if !ok { |
| 1123 |
t.Fatal("parent not recorded") |
| 1124 |
} |
| 1125 |
gotSpan1, ok := te.GetSpan("span-1") |
| 1126 |
if !ok { |
| 1127 |
t.Fatal("span-1 not recorded") |
| 1128 |
} |
| 1129 |
gotSpan2, ok := te.GetSpan("span-2") |
| 1130 |
if !ok { |
| 1131 |
t.Fatal("span-2 not recorded") |
| 1132 |
} |
| 1133 |
gotSpan3, ok := te.GetSpan("span-3") |
| 1134 |
if !ok { |
| 1135 |
t.Fatal("span-3 not recorded") |
| 1136 |
} |
| 1137 |
|
| 1138 |
if got, want := gotSpan3.ChildSpanCount(), 0; got != want { |
| 1139 |
t.Errorf("span-3.ChildSpanCount=%d; want %d", got, want) |
| 1140 |
} |
| 1141 |
if got, want := gotSpan2.ChildSpanCount(), 0; got != want { |
| 1142 |
t.Errorf("span-2.ChildSpanCount=%d; want %d", got, want) |
| 1143 |
} |
| 1144 |
if got, want := gotSpan1.ChildSpanCount(), 1; got != want { |
| 1145 |
t.Errorf("span-1.ChildSpanCount=%d; want %d", got, want) |
| 1146 |
} |
| 1147 |
if got, want := gotParent.ChildSpanCount(), 2; got != want { |
| 1148 |
t.Errorf("parent.ChildSpanCount=%d; want %d", got, want) |
| 1149 |
} |
| 1150 |
} |
| 1151 |
|
| 1152 |
func TestNilSpanEnd(*testing.T) { |
| 1153 |
var span *recordingSpan |
| 1154 |
span.End() |
| 1155 |
} |
| 1156 |
|
| 1157 |
func TestSpanWithCanceledContext(t *testing.T) { |
| 1158 |
te := NewTestExporter() |
| 1159 |
tp := NewTracerProvider(WithSyncer(te)) |
| 1160 |
|
| 1161 |
ctx, cancel := context.WithCancel(t.Context()) |
| 1162 |
cancel() |
| 1163 |
_, span := tp.Tracer(t.Name()).Start(ctx, "span") |
| 1164 |
span.End() |
| 1165 |
|
| 1166 |
assert.Equal(t, 1, te.Len(), "span recording must ignore context cancellation") |
| 1167 |
} |
| 1168 |
|
| 1169 |
func TestNonRecordingSpanDoesNotTrackRuntimeTracerTask(t *testing.T) { |
| 1170 |
tp := NewTracerProvider(WithSampler(NeverSample())) |
| 1171 |
tr := tp.Tracer("TestNonRecordingSpanDoesNotTrackRuntimeTracerTask") |
| 1172 |
|
| 1173 |
_, apiSpan := tr.Start(t.Context(), "foo") |
| 1174 |
if _, ok := apiSpan.(runtimeTracer); ok { |
| 1175 |
t.Fatalf("non recording span implements runtime trace task tracking") |
| 1176 |
} |
| 1177 |
} |
| 1178 |
|
| 1179 |
func TestRecordingSpanRuntimeTracerTaskEnd(t *testing.T) { |
| 1180 |
tp := NewTracerProvider(WithSampler(AlwaysSample())) |
| 1181 |
tr := tp.Tracer("TestRecordingSpanRuntimeTracerTaskEnd") |
| 1182 |
|
| 1183 |
var n atomic.Uint64 |
| 1184 |
executionTracerTaskEnd := func() { |
| 1185 |
n.Add(1) |
| 1186 |
} |
| 1187 |
_, apiSpan := tr.Start(t.Context(), "foo") |
| 1188 |
s, ok := apiSpan.(*recordingSpan) |
| 1189 |
if !ok { |
| 1190 |
t.Fatal("recording span not returned from always sampled Tracer") |
| 1191 |
} |
| 1192 |
|
| 1193 |
s.executionTracerTaskEnd = executionTracerTaskEnd |
| 1194 |
s.End() |
| 1195 |
|
| 1196 |
if n.Load() != 1 { |
| 1197 |
t.Error("recording span did not end runtime trace task") |
| 1198 |
} |
| 1199 |
} |
| 1200 |
|
| 1201 |
func TestCustomStartEndTime(t *testing.T) { |
| 1202 |
te := NewTestExporter() |
| 1203 |
tp := NewTracerProvider(WithSyncer(te), WithSampler(AlwaysSample())) |
| 1204 |
|
| 1205 |
startTime := time.Date(2019, time.August, 27, 14, 42, 0, 0, time.UTC) |
| 1206 |
endTime := startTime.Add(time.Second * 20) |
| 1207 |
_, span := tp.Tracer("Custom Start and End time").Start( |
| 1208 |
t.Context(), |
| 1209 |
"testspan", |
| 1210 |
trace.WithTimestamp(startTime), |
| 1211 |
) |
| 1212 |
span.End(trace.WithTimestamp(endTime)) |
| 1213 |
|
| 1214 |
if te.Len() != 1 { |
| 1215 |
t.Fatalf("got %d exported spans, want one span", te.Len()) |
| 1216 |
} |
| 1217 |
got := te.Spans()[0] |
| 1218 |
if !got.StartTime().Equal(startTime) { |
| 1219 |
t.Errorf("expected start time to be %s, got %s", startTime, got.StartTime()) |
| 1220 |
} |
| 1221 |
if !got.EndTime().Equal(endTime) { |
| 1222 |
t.Errorf("expected end time to be %s, got %s", endTime, got.EndTime()) |
| 1223 |
} |
| 1224 |
} |
| 1225 |
|
| 1226 |
func TestRecordError(t *testing.T) { |
| 1227 |
scenarios := []struct { |
| 1228 |
err error |
| 1229 |
typ string |
| 1230 |
msg string |
| 1231 |
}{ |
| 1232 |
{ |
| 1233 |
err: newTestError("test error"), |
| 1234 |
typ: "go.opentelemetry.io/otel/sdk/trace.testError", |
| 1235 |
msg: "test error", |
| 1236 |
}, |
| 1237 |
{ |
| 1238 |
err: errors.New("test error 2"), |
| 1239 |
typ: "*errors.errorString", |
| 1240 |
msg: "test error 2", |
| 1241 |
}, |
| 1242 |
} |
| 1243 |
|
| 1244 |
for _, s := range scenarios { |
| 1245 |
te := NewTestExporter() |
| 1246 |
tp := NewTracerProvider(WithSyncer(te), WithResource(resource.Empty())) |
| 1247 |
span := startSpan(tp, "RecordError") |
| 1248 |
|
| 1249 |
errTime := time.Now() |
| 1250 |
span.RecordError(s.err, trace.WithTimestamp(errTime)) |
| 1251 |
|
| 1252 |
got, err := endSpan(te, span) |
| 1253 |
if err != nil { |
| 1254 |
t.Fatal(err) |
| 1255 |
} |
| 1256 |
|
| 1257 |
want := &snapshot{ |
| 1258 |
spanContext: trace.NewSpanContext(trace.SpanContextConfig{ |
| 1259 |
TraceID: tid, |
| 1260 |
TraceFlags: 0x1, |
| 1261 |
}), |
| 1262 |
parent: sc.WithRemote(true), |
| 1263 |
name: "span0", |
| 1264 |
status: Status{Code: codes.Unset}, |
| 1265 |
spanKind: trace.SpanKindInternal, |
| 1266 |
events: []Event{ |
| 1267 |
{ |
| 1268 |
Name: semconv.ExceptionEventName, |
| 1269 |
Time: errTime, |
| 1270 |
Attributes: []attribute.KeyValue{ |
| 1271 |
semconv.ExceptionType(s.typ), |
| 1272 |
semconv.ExceptionMessage(s.msg), |
| 1273 |
}, |
| 1274 |
}, |
| 1275 |
}, |
| 1276 |
instrumentationScope: instrumentation.Scope{Name: "RecordError"}, |
| 1277 |
} |
| 1278 |
if diff := cmpDiff(got, want); diff != "" { |
| 1279 |
t.Errorf("SpanErrorOptions: -got +want %s", diff) |
| 1280 |
} |
| 1281 |
} |
| 1282 |
} |
| 1283 |
|
| 1284 |
func TestRecordErrorWithStackTrace(t *testing.T) { |
| 1285 |
err := newTestError("test error") |
| 1286 |
typ := "go.opentelemetry.io/otel/sdk/trace.testError" |
| 1287 |
msg := "test error" |
| 1288 |
|
| 1289 |
te := NewTestExporter() |
| 1290 |
tp := NewTracerProvider(WithSyncer(te), WithResource(resource.Empty())) |
| 1291 |
span := startSpan(tp, "RecordError") |
| 1292 |
|
| 1293 |
errTime := time.Now() |
| 1294 |
span.RecordError(err, trace.WithTimestamp(errTime), trace.WithStackTrace(true)) |
| 1295 |
|
| 1296 |
got, err := endSpan(te, span) |
| 1297 |
if err != nil { |
| 1298 |
t.Fatal(err) |
| 1299 |
} |
| 1300 |
|
| 1301 |
want := &snapshot{ |
| 1302 |
spanContext: trace.NewSpanContext(trace.SpanContextConfig{ |
| 1303 |
TraceID: tid, |
| 1304 |
TraceFlags: 0x1, |
| 1305 |
}), |
| 1306 |
parent: sc.WithRemote(true), |
| 1307 |
name: "span0", |
| 1308 |
status: Status{Code: codes.Unset}, |
| 1309 |
spanKind: trace.SpanKindInternal, |
| 1310 |
events: []Event{ |
| 1311 |
{ |
| 1312 |
Name: semconv.ExceptionEventName, |
| 1313 |
Time: errTime, |
| 1314 |
Attributes: []attribute.KeyValue{ |
| 1315 |
semconv.ExceptionType(typ), |
| 1316 |
semconv.ExceptionMessage(msg), |
| 1317 |
}, |
| 1318 |
}, |
| 1319 |
}, |
| 1320 |
instrumentationScope: instrumentation.Scope{Name: "RecordError"}, |
| 1321 |
} |
| 1322 |
|
| 1323 |
assert.Equal(t, want.spanContext, got.spanContext) |
| 1324 |
assert.Equal(t, want.parent, got.parent) |
| 1325 |
assert.Equal(t, want.name, got.name) |
| 1326 |
assert.Equal(t, want.status, got.status) |
| 1327 |
assert.Equal(t, want.spanKind, got.spanKind) |
| 1328 |
assert.Equal(t, got.events[0].Attributes[0].Value.AsString(), want.events[0].Attributes[0].Value.AsString()) |
| 1329 |
assert.Equal(t, got.events[0].Attributes[1].Value.AsString(), want.events[0].Attributes[1].Value.AsString()) |
| 1330 |
gotStackTraceFunctionName := strings.Split(got.events[0].Attributes[2].Value.AsString(), "\n") |
| 1331 |
|
| 1332 |
assert.Truef( |
| 1333 |
t, |
| 1334 |
strings.HasPrefix(gotStackTraceFunctionName[1], "go.opentelemetry.io/otel/sdk/trace.recordStackTrace"), |
| 1335 |
"%q not prefixed with go.opentelemetry.io/otel/sdk/trace.recordStackTrace", |
| 1336 |
gotStackTraceFunctionName[1], |
| 1337 |
) |
| 1338 |
assert.Truef( |
| 1339 |
t, |
| 1340 |
strings.HasPrefix( |
| 1341 |
gotStackTraceFunctionName[3], |
| 1342 |
"go.opentelemetry.io/otel/sdk/trace.(*recordingSpan).RecordError", |
| 1343 |
), |
| 1344 |
"%q not prefixed with go.opentelemetry.io/otel/sdk/trace.(*recordingSpan).RecordError", |
| 1345 |
gotStackTraceFunctionName[3], |
| 1346 |
) |
| 1347 |
} |
| 1348 |
|
| 1349 |
func TestRecordErrorNil(t *testing.T) { |
| 1350 |
te := NewTestExporter() |
| 1351 |
tp := NewTracerProvider(WithSyncer(te), WithResource(resource.Empty())) |
| 1352 |
span := startSpan(tp, "RecordErrorNil") |
| 1353 |
|
| 1354 |
span.RecordError(nil) |
| 1355 |
|
| 1356 |
got, err := endSpan(te, span) |
| 1357 |
if err != nil { |
| 1358 |
t.Fatal(err) |
| 1359 |
} |
| 1360 |
|
| 1361 |
want := &snapshot{ |
| 1362 |
spanContext: trace.NewSpanContext(trace.SpanContextConfig{ |
| 1363 |
TraceID: tid, |
| 1364 |
TraceFlags: 0x1, |
| 1365 |
}), |
| 1366 |
parent: sc.WithRemote(true), |
| 1367 |
name: "span0", |
| 1368 |
spanKind: trace.SpanKindInternal, |
| 1369 |
status: Status{ |
| 1370 |
Code: codes.Unset, |
| 1371 |
Description: "", |
| 1372 |
}, |
| 1373 |
instrumentationScope: instrumentation.Scope{Name: "RecordErrorNil"}, |
| 1374 |
} |
| 1375 |
if diff := cmpDiff(got, want); diff != "" { |
| 1376 |
t.Errorf("SpanErrorOptions: -got +want %s", diff) |
| 1377 |
} |
| 1378 |
} |
| 1379 |
|
| 1380 |
func TestWithSpanKind(t *testing.T) { |
| 1381 |
te := NewTestExporter() |
| 1382 |
tp := NewTracerProvider(WithSyncer(te), WithSampler(AlwaysSample()), WithResource(resource.Empty())) |
| 1383 |
tr := tp.Tracer("withSpanKind") |
| 1384 |
|
| 1385 |
_, span := tr.Start(t.Context(), "WithoutSpanKind") |
| 1386 |
spanData, err := endSpan(te, span) |
| 1387 |
if err != nil { |
| 1388 |
t.Error(err.Error()) |
| 1389 |
} |
| 1390 |
|
| 1391 |
if spanData.SpanKind() != trace.SpanKindInternal { |
| 1392 |
t.Errorf( |
| 1393 |
"Default value of Spankind should be Internal: got %+v, want %+v\n", |
| 1394 |
spanData.SpanKind(), |
| 1395 |
trace.SpanKindInternal, |
| 1396 |
) |
| 1397 |
} |
| 1398 |
|
| 1399 |
sks := []trace.SpanKind{ |
| 1400 |
trace.SpanKindInternal, |
| 1401 |
trace.SpanKindServer, |
| 1402 |
trace.SpanKindClient, |
| 1403 |
trace.SpanKindProducer, |
| 1404 |
trace.SpanKindConsumer, |
| 1405 |
} |
| 1406 |
|
| 1407 |
for _, sk := range sks { |
| 1408 |
te.Reset() |
| 1409 |
|
| 1410 |
_, span := tr.Start(t.Context(), fmt.Sprintf("SpanKind-%v", sk), trace.WithSpanKind(sk)) |
| 1411 |
spanData, err := endSpan(te, span) |
| 1412 |
if err != nil { |
| 1413 |
t.Error(err.Error()) |
| 1414 |
} |
| 1415 |
|
| 1416 |
if spanData.SpanKind() != sk { |
| 1417 |
t.Errorf("WithSpanKind check: got %+v, want %+v\n", spanData.SpanKind(), sks) |
| 1418 |
} |
| 1419 |
} |
| 1420 |
} |
| 1421 |
|
| 1422 |
func mergeResource(t *testing.T, r1, r2 *resource.Resource) *resource.Resource { |
| 1423 |
r, err := resource.Merge(r1, r2) |
| 1424 |
assert.NoError(t, err) |
| 1425 |
return r |
| 1426 |
} |
| 1427 |
|
| 1428 |
func TestWithResource(t *testing.T) { |
| 1429 |
t.Setenv(envVarResourceAttributes, "key=value,rk5=7") |
| 1430 |
cases := []struct { |
| 1431 |
name string |
| 1432 |
options []TracerProviderOption |
| 1433 |
want *resource.Resource |
| 1434 |
msg string |
| 1435 |
}{ |
| 1436 |
{ |
| 1437 |
name: "explicitly empty resource", |
| 1438 |
options: []TracerProviderOption{WithResource(resource.Empty())}, |
| 1439 |
want: resource.Environment(), |
| 1440 |
}, |
| 1441 |
{ |
| 1442 |
name: "uses default if no resource option", |
| 1443 |
options: []TracerProviderOption{}, |
| 1444 |
want: resource.Default(), |
| 1445 |
}, |
| 1446 |
{ |
| 1447 |
name: "explicit resource", |
| 1448 |
options: []TracerProviderOption{ |
| 1449 |
WithResource(resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk2", 5))), |
| 1450 |
}, |
| 1451 |
want: mergeResource( |
| 1452 |
t, |
| 1453 |
resource.Environment(), |
| 1454 |
resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk2", 5)), |
| 1455 |
), |
| 1456 |
}, |
| 1457 |
{ |
| 1458 |
name: "last resource wins", |
| 1459 |
options: []TracerProviderOption{ |
| 1460 |
WithResource(resource.NewSchemaless(attribute.String("rk1", "vk1"), attribute.Int64("rk2", 5))), |
| 1461 |
WithResource(resource.NewSchemaless(attribute.String("rk3", "rv3"), attribute.Int64("rk4", 10))), |
| 1462 |
}, |
| 1463 |
want: mergeResource( |
| 1464 |
t, |
| 1465 |
resource.Environment(), |
| 1466 |
resource.NewSchemaless(attribute.String("rk3", "rv3"), attribute.Int64("rk4", 10)), |
| 1467 |
), |
| 1468 |
}, |
| 1469 |
{ |
| 1470 |
name: "overlapping attributes with environment resource", |
| 1471 |
options: []TracerProviderOption{ |
| 1472 |
WithResource(resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk5", 10))), |
| 1473 |
}, |
| 1474 |
want: mergeResource( |
| 1475 |
t, |
| 1476 |
resource.Environment(), |
| 1477 |
resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk5", 10)), |
| 1478 |
), |
| 1479 |
}, |
| 1480 |
} |
| 1481 |
for _, tc := range cases { |
| 1482 |
t.Run(tc.name, func(t *testing.T) { |
| 1483 |
te := NewTestExporter() |
| 1484 |
defaultOptions := []TracerProviderOption{WithSyncer(te), WithSampler(AlwaysSample())} |
| 1485 |
tp := NewTracerProvider(append(defaultOptions, tc.options...)...) |
| 1486 |
span := startSpan(tp, "WithResource") |
| 1487 |
span.SetAttributes(attribute.String("key1", "value1")) |
| 1488 |
got, err := endSpan(te, span) |
| 1489 |
if err != nil { |
| 1490 |
t.Error(err.Error()) |
| 1491 |
} |
| 1492 |
want := &snapshot{ |
| 1493 |
spanContext: trace.NewSpanContext(trace.SpanContextConfig{ |
| 1494 |
TraceID: tid, |
| 1495 |
TraceFlags: 0x1, |
| 1496 |
}), |
| 1497 |
parent: sc.WithRemote(true), |
| 1498 |
name: "span0", |
| 1499 |
attributes: []attribute.KeyValue{ |
| 1500 |
attribute.String("key1", "value1"), |
| 1501 |
}, |
| 1502 |
spanKind: trace.SpanKindInternal, |
| 1503 |
resource: tc.want, |
| 1504 |
instrumentationScope: instrumentation.Scope{Name: "WithResource"}, |
| 1505 |
} |
| 1506 |
if diff := cmpDiff(got, want); diff != "" { |
| 1507 |
t.Errorf("WithResource:\n -got +want %s", diff) |
| 1508 |
} |
| 1509 |
}) |
| 1510 |
} |
| 1511 |
} |
| 1512 |
|
| 1513 |
func TestWithInstrumentationVersionAndSchema(t *testing.T) { |
| 1514 |
te := NewTestExporter() |
| 1515 |
tp := NewTracerProvider(WithSyncer(te), WithResource(resource.Empty())) |
| 1516 |
|
| 1517 |
ctx := t.Context() |
| 1518 |
ctx = trace.ContextWithRemoteSpanContext(ctx, sc) |
| 1519 |
_, span := tp.Tracer( |
| 1520 |
"WithInstrumentationVersion", |
| 1521 |
trace.WithInstrumentationVersion("v0.1.0"), |
| 1522 |
trace.WithSchemaURL("https://opentelemetry.io/schemas/1.21.0"), |
| 1523 |
).Start(ctx, "span0") |
| 1524 |
got, err := endSpan(te, span) |
| 1525 |
if err != nil { |
| 1526 |
t.Error(err.Error()) |
| 1527 |
} |
| 1528 |
|
| 1529 |
want := &snapshot{ |
| 1530 |
spanContext: trace.NewSpanContext(trace.SpanContextConfig{ |
| 1531 |
TraceID: tid, |
| 1532 |
TraceFlags: 0x1, |
| 1533 |
}), |
| 1534 |
parent: sc.WithRemote(true), |
| 1535 |
name: "span0", |
| 1536 |
spanKind: trace.SpanKindInternal, |
| 1537 |
instrumentationScope: instrumentation.Scope{ |
| 1538 |
Name: "WithInstrumentationVersion", |
| 1539 |
Version: "v0.1.0", |
| 1540 |
SchemaURL: "https://opentelemetry.io/schemas/1.21.0", |
| 1541 |
}, |
| 1542 |
} |
| 1543 |
if diff := cmpDiff(got, want); diff != "" { |
| 1544 |
t.Errorf("WithResource:\n -got +want %s", diff) |
| 1545 |
} |
| 1546 |
} |
| 1547 |
|
| 1548 |
func TestSpanCapturesPanic(t *testing.T) { |
| 1549 |
te := NewTestExporter() |
| 1550 |
tp := NewTracerProvider(WithSyncer(te), WithResource(resource.Empty())) |
| 1551 |
_, span := tp.Tracer("CatchPanic").Start( |
| 1552 |
t.Context(), |
| 1553 |
"span", |
| 1554 |
) |
| 1555 |
|
| 1556 |
f := func() { |
| 1557 |
defer span.End() |
| 1558 |
panic(errors.New("error message")) |
| 1559 |
} |
| 1560 |
require.PanicsWithError(t, "error message", f) |
| 1561 |
spans := te.Spans() |
| 1562 |
require.Len(t, spans, 1) |
| 1563 |
require.Len(t, spans[0].Events(), 1) |
| 1564 |
assert.Equal(t, semconv.ExceptionEventName, spans[0].Events()[0].Name) |
| 1565 |
assert.Equal(t, []attribute.KeyValue{ |
| 1566 |
semconv.ExceptionType("*errors.errorString"), |
| 1567 |
semconv.ExceptionMessage("error message"), |
| 1568 |
}, spans[0].Events()[0].Attributes) |
| 1569 |
} |
| 1570 |
|
| 1571 |
func TestSpanCapturesPanicWithStackTrace(t *testing.T) { |
| 1572 |
te := NewTestExporter() |
| 1573 |
tp := NewTracerProvider(WithSyncer(te), WithResource(resource.Empty())) |
| 1574 |
_, span := tp.Tracer("CatchPanic").Start( |
| 1575 |
t.Context(), |
| 1576 |
"span", |
| 1577 |
) |
| 1578 |
|
| 1579 |
f := func() { |
| 1580 |
defer span.End(trace.WithStackTrace(true)) |
| 1581 |
panic(errors.New("error message")) |
| 1582 |
} |
| 1583 |
require.PanicsWithError(t, "error message", f) |
| 1584 |
spans := te.Spans() |
| 1585 |
require.Len(t, spans, 1) |
| 1586 |
require.Len(t, spans[0].Events(), 1) |
| 1587 |
assert.Equal(t, semconv.ExceptionEventName, spans[0].Events()[0].Name) |
| 1588 |
assert.Equal(t, "*errors.errorString", spans[0].Events()[0].Attributes[0].Value.AsString()) |
| 1589 |
assert.Equal(t, "error message", spans[0].Events()[0].Attributes[1].Value.AsString()) |
| 1590 |
|
| 1591 |
gotStackTraceFunctionName := strings.Split(spans[0].Events()[0].Attributes[2].Value.AsString(), "\n") |
| 1592 |
assert.Truef( |
| 1593 |
t, |
| 1594 |
strings.HasPrefix(gotStackTraceFunctionName[1], "go.opentelemetry.io/otel/sdk/trace.recordStackTrace"), |
| 1595 |
"%q not prefixed with go.opentelemetry.io/otel/sdk/trace.recordStackTrace", |
| 1596 |
gotStackTraceFunctionName[1], |
| 1597 |
) |
| 1598 |
assert.Truef( |
| 1599 |
t, |
| 1600 |
strings.HasPrefix(gotStackTraceFunctionName[3], "go.opentelemetry.io/otel/sdk/trace.(*recordingSpan).End"), |
| 1601 |
"%q not prefixed with go.opentelemetry.io/otel/sdk/trace.(*recordingSpan).End", |
| 1602 |
gotStackTraceFunctionName[3], |
| 1603 |
) |
| 1604 |
} |
| 1605 |
|
| 1606 |
func TestReadOnlySpan(t *testing.T) { |
| 1607 |
kv := attribute.String("foo", "bar") |
| 1608 |
|
| 1609 |
tp := NewTracerProvider(WithResource(resource.NewSchemaless(kv))) |
| 1610 |
tr := tp.Tracer("ReadOnlySpan", trace.WithInstrumentationVersion("3")) |
| 1611 |
|
| 1612 |
// Initialize parent context. |
| 1613 |
tID, sID := tp.idGenerator.NewIDs(t.Context()) |
| 1614 |
parent := trace.NewSpanContext(trace.SpanContextConfig{ |
| 1615 |
TraceID: tID, |
| 1616 |
SpanID: sID, |
| 1617 |
TraceFlags: 0x1, |
| 1618 |
Remote: true, |
| 1619 |
}) |
| 1620 |
ctx := trace.ContextWithRemoteSpanContext(t.Context(), parent) |
| 1621 |
|
| 1622 |
// Initialize linked context. |
| 1623 |
tID, sID = tp.idGenerator.NewIDs(t.Context()) |
| 1624 |
linked := trace.NewSpanContext(trace.SpanContextConfig{ |
| 1625 |
TraceID: tID, |
| 1626 |
SpanID: sID, |
| 1627 |
TraceFlags: 0x1, |
| 1628 |
}) |
| 1629 |
|
| 1630 |
st := time.Now() |
| 1631 |
ctx, s := tr.Start(ctx, "foo", trace.WithTimestamp(st), |
| 1632 |
trace.WithLinks(trace.Link{SpanContext: linked})) |
| 1633 |
s.SetAttributes(kv) |
| 1634 |
s.AddEvent("foo", trace.WithAttributes(kv)) |
| 1635 |
s.SetStatus(codes.Ok, "foo") |
| 1636 |
|
| 1637 |
// Verify span implements ReadOnlySpan. |
| 1638 |
ro, ok := s.(ReadOnlySpan) |
| 1639 |
require.True(t, ok) |
| 1640 |
|
| 1641 |
assert.Equal(t, "foo", ro.Name()) |
| 1642 |
assert.Equal(t, trace.SpanContextFromContext(ctx), ro.SpanContext()) |
| 1643 |
assert.Equal(t, parent, ro.Parent()) |
| 1644 |
assert.Equal(t, trace.SpanKindInternal, ro.SpanKind()) |
| 1645 |
assert.Equal(t, st, ro.StartTime()) |
| 1646 |
assert.True(t, ro.EndTime().IsZero()) |
| 1647 |
assert.Equal(t, kv.Key, ro.Attributes()[0].Key) |
| 1648 |
assert.Equal(t, kv.Value, ro.Attributes()[0].Value) |
| 1649 |
assert.Equal(t, linked, ro.Links()[0].SpanContext) |
| 1650 |
assert.Equal(t, kv.Key, ro.Events()[0].Attributes[0].Key) |
| 1651 |
assert.Equal(t, kv.Value, ro.Events()[0].Attributes[0].Value) |
| 1652 |
assert.Equal(t, codes.Ok, ro.Status().Code) |
| 1653 |
assert.Empty(t, ro.Status().Description) |
| 1654 |
assert.Equal(t, "ReadOnlySpan", ro.InstrumentationLibrary().Name) |
| 1655 |
assert.Equal(t, "3", ro.InstrumentationLibrary().Version) |
| 1656 |
assert.Equal(t, "ReadOnlySpan", ro.InstrumentationScope().Name) |
| 1657 |
assert.Equal(t, "3", ro.InstrumentationScope().Version) |
| 1658 |
assert.Equal(t, kv.Key, ro.Resource().Attributes()[0].Key) |
| 1659 |
assert.Equal(t, kv.Value, ro.Resource().Attributes()[0].Value) |
| 1660 |
|
| 1661 |
// Verify changes to the original span are reflected in the ReadOnlySpan. |
| 1662 |
s.SetName("bar") |
| 1663 |
assert.Equal(t, "bar", ro.Name()) |
| 1664 |
|
| 1665 |
// Verify snapshot() returns snapshots that are independent from the |
| 1666 |
// original span and from one another. |
| 1667 |
d1 := s.(*recordingSpan).snapshot() |
| 1668 |
s.AddEvent("baz") |
| 1669 |
d2 := s.(*recordingSpan).snapshot() |
| 1670 |
for _, e := range d1.Events() { |
| 1671 |
if e.Name == "baz" { |
| 1672 |
t.Errorf("Didn't expect to find 'baz' event") |
| 1673 |
} |
| 1674 |
} |
| 1675 |
var exists bool |
| 1676 |
for _, e := range d2.Events() { |
| 1677 |
if e.Name == "baz" { |
| 1678 |
exists = true |
| 1679 |
} |
| 1680 |
} |
| 1681 |
if !exists { |
| 1682 |
t.Errorf("Expected to find 'baz' event") |
| 1683 |
} |
| 1684 |
|
| 1685 |
et := st.Add(time.Millisecond) |
| 1686 |
s.End(trace.WithTimestamp(et)) |
| 1687 |
assert.Equal(t, et, ro.EndTime()) |
| 1688 |
} |
| 1689 |
|
| 1690 |
func TestReadWriteSpan(t *testing.T) { |
| 1691 |
tp := NewTracerProvider(WithResource(resource.Empty())) |
| 1692 |
tr := tp.Tracer("ReadWriteSpan") |
| 1693 |
|
| 1694 |
// Initialize parent context. |
| 1695 |
tID, sID := tp.idGenerator.NewIDs(t.Context()) |
| 1696 |
parent := trace.NewSpanContext(trace.SpanContextConfig{ |
| 1697 |
TraceID: tID, |
| 1698 |
SpanID: sID, |
| 1699 |
TraceFlags: 0x1, |
| 1700 |
}) |
| 1701 |
ctx := trace.ContextWithRemoteSpanContext(t.Context(), parent) |
| 1702 |
|
| 1703 |
_, span := tr.Start(ctx, "foo") |
| 1704 |
defer span.End() |
| 1705 |
|
| 1706 |
// Verify span implements ReadOnlySpan. |
| 1707 |
rw, ok := span.(ReadWriteSpan) |
| 1708 |
require.True(t, ok) |
| 1709 |
|
| 1710 |
// Verify the span can be read from. |
| 1711 |
assert.False(t, rw.StartTime().IsZero()) |
| 1712 |
|
| 1713 |
// Verify the span can be written to. |
| 1714 |
rw.SetName("bar") |
| 1715 |
assert.Equal(t, "bar", rw.Name()) |
| 1716 |
// NOTE: This function tests ReadWriteSpan which is an interface which |
| 1717 |
// embeds trace.Span and ReadOnlySpan. Since both of these interfaces have |
| 1718 |
// their own tests, there is no point in testing all the possible methods |
| 1719 |
// available via ReadWriteSpan as doing so would mean creating a lot of |
| 1720 |
// duplication. |
| 1721 |
} |
| 1722 |
|
| 1723 |
func TestAddEventsWithMoreAttributesThanLimit(t *testing.T) { |
| 1724 |
te := NewTestExporter() |
| 1725 |
sl := NewSpanLimits() |
| 1726 |
sl.AttributePerEventCountLimit = 2 |
| 1727 |
tp := NewTracerProvider( |
| 1728 |
WithSpanLimits(sl), |
| 1729 |
WithSyncer(te), |
| 1730 |
WithResource(resource.Empty()), |
| 1731 |
) |
| 1732 |
|
| 1733 |
span := startSpan(tp, "AddSpanEventWithOverLimitedAttributes") |
| 1734 |
span.AddEvent("test1", trace.WithAttributes( |
| 1735 |
attribute.Bool("key1", true), |
| 1736 |
attribute.String("key2", "value2"), |
| 1737 |
)) |
| 1738 |
// Parts of the attribute should be discard |
| 1739 |
span.AddEvent("test2", trace.WithAttributes( |
| 1740 |
attribute.Bool("key1", true), |
| 1741 |
attribute.String("key2", "value2"), |
| 1742 |
attribute.String("key3", "value3"), |
| 1743 |
attribute.String("key4", "value4"), |
| 1744 |
)) |
| 1745 |
got, err := endSpan(te, span) |
| 1746 |
if err != nil { |
| 1747 |
t.Fatal(err) |
| 1748 |
} |
| 1749 |
|
| 1750 |
for i := range got.Events() { |
| 1751 |
if !checkTime(&got.Events()[i].Time) { |
| 1752 |
t.Error("exporting span: expected nonzero Event Time") |
| 1753 |
} |
| 1754 |
} |
| 1755 |
|
| 1756 |
want := &snapshot{ |
| 1757 |
spanContext: trace.NewSpanContext(trace.SpanContextConfig{ |
| 1758 |
TraceID: tid, |
| 1759 |
TraceFlags: 0x1, |
| 1760 |
}), |
| 1761 |
parent: sc.WithRemote(true), |
| 1762 |
name: "span0", |
| 1763 |
attributes: nil, |
| 1764 |
events: []Event{ |
| 1765 |
{ |
| 1766 |
Name: "test1", |
| 1767 |
Attributes: []attribute.KeyValue{ |
| 1768 |
attribute.Bool("key1", true), |
| 1769 |
attribute.String("key2", "value2"), |
| 1770 |
}, |
| 1771 |
}, |
| 1772 |
{ |
| 1773 |
Name: "test2", |
| 1774 |
Attributes: []attribute.KeyValue{ |
| 1775 |
attribute.Bool("key1", true), |
| 1776 |
attribute.String("key2", "value2"), |
| 1777 |
}, |
| 1778 |
DroppedAttributeCount: 2, |
| 1779 |
}, |
| 1780 |
}, |
| 1781 |
spanKind: trace.SpanKindInternal, |
| 1782 |
instrumentationScope: instrumentation.Scope{Name: "AddSpanEventWithOverLimitedAttributes"}, |
| 1783 |
} |
| 1784 |
if diff := cmpDiff(got, want); diff != "" { |
| 1785 |
t.Errorf("SetSpanAttributesOverLimit: -got +want %s", diff) |
| 1786 |
} |
| 1787 |
} |
| 1788 |
|
| 1789 |
type stateSampler struct { |
| 1790 |
prefix string |
| 1791 |
f func(trace.TraceState) trace.TraceState |
| 1792 |
} |
| 1793 |
|
| 1794 |
func (s *stateSampler) ShouldSample(p SamplingParameters) SamplingResult { |
| 1795 |
decision := Drop |
| 1796 |
if strings.HasPrefix(p.Name, s.prefix) { |
| 1797 |
decision = RecordAndSample |
| 1798 |
} |
| 1799 |
ts := s.f(trace.SpanContextFromContext(p.ParentContext).TraceState()) |
| 1800 |
return SamplingResult{Decision: decision, Tracestate: ts} |
| 1801 |
} |
| 1802 |
|
| 1803 |
func (stateSampler) Description() string { |
| 1804 |
return "stateSampler" |
| 1805 |
} |
| 1806 |
|
| 1807 |
// Check that a new span propagates the SamplerResult.TraceState. |
| 1808 |
func TestSamplerTraceState(t *testing.T) { |
| 1809 |
mustTS := func(ts trace.TraceState, err error) trace.TraceState { |
| 1810 |
require.NoError(t, err) |
| 1811 |
return ts |
| 1812 |
} |
| 1813 |
makeInserter := func(k, v, prefix string) Sampler { |
| 1814 |
return &stateSampler{ |
| 1815 |
prefix: prefix, |
| 1816 |
f: func(t trace.TraceState) trace.TraceState { return mustTS(t.Insert(k, v)) }, |
| 1817 |
} |
| 1818 |
} |
| 1819 |
makeDeleter := func(k, prefix string) Sampler { |
| 1820 |
return &stateSampler{ |
| 1821 |
prefix: prefix, |
| 1822 |
f: func(t trace.TraceState) trace.TraceState { return t.Delete(k) }, |
| 1823 |
} |
| 1824 |
} |
| 1825 |
clearer := func(prefix string) Sampler { |
| 1826 |
return &stateSampler{ |
| 1827 |
prefix: prefix, |
| 1828 |
f: func(trace.TraceState) trace.TraceState { return trace.TraceState{} }, |
| 1829 |
} |
| 1830 |
} |
| 1831 |
|
| 1832 |
tests := []struct { |
| 1833 |
name string |
| 1834 |
sampler Sampler |
| 1835 |
spanName string |
| 1836 |
input trace.TraceState |
| 1837 |
want trace.TraceState |
| 1838 |
exportSpan bool |
| 1839 |
}{ |
| 1840 |
{ |
| 1841 |
name: "alwaysOn", |
| 1842 |
sampler: AlwaysSample(), |
| 1843 |
input: mustTS(trace.ParseTraceState("k1=v1")), |
| 1844 |
want: mustTS(trace.ParseTraceState("k1=v1")), |
| 1845 |
exportSpan: true, |
| 1846 |
}, |
| 1847 |
{ |
| 1848 |
name: "alwaysOff", |
| 1849 |
sampler: NeverSample(), |
| 1850 |
input: mustTS(trace.ParseTraceState("k1=v1")), |
| 1851 |
want: mustTS(trace.ParseTraceState("k1=v1")), |
| 1852 |
exportSpan: false, |
| 1853 |
}, |
| 1854 |
{ |
| 1855 |
name: "insertKeySampled", |
| 1856 |
sampler: makeInserter("k2", "v2", "span"), |
| 1857 |
spanName: "span0", |
| 1858 |
input: mustTS(trace.ParseTraceState("k1=v1")), |
| 1859 |
want: mustTS(trace.ParseTraceState("k2=v2,k1=v1")), |
| 1860 |
exportSpan: true, |
| 1861 |
}, |
| 1862 |
{ |
| 1863 |
name: "insertKeyDropped", |
| 1864 |
sampler: makeInserter("k2", "v2", "span"), |
| 1865 |
spanName: "nospan0", |
| 1866 |
input: mustTS(trace.ParseTraceState("k1=v1")), |
| 1867 |
want: mustTS(trace.ParseTraceState("k2=v2,k1=v1")), |
| 1868 |
exportSpan: false, |
| 1869 |
}, |
| 1870 |
{ |
| 1871 |
name: "deleteKeySampled", |
| 1872 |
sampler: makeDeleter("k1", "span"), |
| 1873 |
spanName: "span0", |
| 1874 |
input: mustTS(trace.ParseTraceState("k1=v1,k2=v2")), |
| 1875 |
want: mustTS(trace.ParseTraceState("k2=v2")), |
| 1876 |
exportSpan: true, |
| 1877 |
}, |
| 1878 |
{ |
| 1879 |
name: "deleteKeyDropped", |
| 1880 |
sampler: makeDeleter("k1", "span"), |
| 1881 |
spanName: "nospan0", |
| 1882 |
input: mustTS(trace.ParseTraceState("k1=v1,k2=v2,k3=v3")), |
| 1883 |
want: mustTS(trace.ParseTraceState("k2=v2,k3=v3")), |
| 1884 |
exportSpan: false, |
| 1885 |
}, |
| 1886 |
{ |
| 1887 |
name: "clearer", |
| 1888 |
sampler: clearer("span"), |
| 1889 |
spanName: "span0", |
| 1890 |
input: mustTS(trace.ParseTraceState("k1=v1,k3=v3")), |
| 1891 |
want: mustTS(trace.ParseTraceState("")), |
| 1892 |
exportSpan: true, |
| 1893 |
}, |
| 1894 |
} |
| 1895 |
|
| 1896 |
for _, ts := range tests { |
| 1897 |
t.Run(ts.name, func(t *testing.T) { |
| 1898 |
te := NewTestExporter() |
| 1899 |
tp := NewTracerProvider(WithSampler(ts.sampler), WithSyncer(te), WithResource(resource.Empty())) |
| 1900 |
tr := tp.Tracer("TraceState") |
| 1901 |
|
| 1902 |
sc1 := trace.NewSpanContext(trace.SpanContextConfig{ |
| 1903 |
TraceID: tid, |
| 1904 |
SpanID: sid, |
| 1905 |
TraceFlags: trace.FlagsSampled, |
| 1906 |
TraceState: ts.input, |
| 1907 |
}) |
| 1908 |
ctx := trace.ContextWithRemoteSpanContext(t.Context(), sc1) |
| 1909 |
_, span := tr.Start(ctx, ts.spanName) |
| 1910 |
|
| 1911 |
// span's TraceState should be set regardless of Sampled/NonSampled state. |
| 1912 |
require.Equal(t, ts.want, span.SpanContext().TraceState()) |
| 1913 |
|
| 1914 |
span.End() |
| 1915 |
|
| 1916 |
got := te.Spans() |
| 1917 |
if len(got) > 0 != ts.exportSpan { |
| 1918 |
t.Errorf("unexpected number of exported spans %d", len(got)) |
| 1919 |
} |
| 1920 |
if len(got) == 0 { |
| 1921 |
return |
| 1922 |
} |
| 1923 |
|
| 1924 |
receivedState := got[0].SpanContext().TraceState() |
| 1925 |
|
| 1926 |
if diff := cmpDiff(receivedState, ts.want); diff != "" { |
| 1927 |
t.Errorf("TraceState not propagated: -got +want %s", diff) |
| 1928 |
} |
| 1929 |
}) |
| 1930 |
} |
| 1931 |
} |
| 1932 |
|
| 1933 |
type testIDGenerator struct { |
| 1934 |
traceIDHigh uint64 |
| 1935 |
traceIDLow uint64 |
| 1936 |
spanID uint64 |
| 1937 |
} |
| 1938 |
|
| 1939 |
func (gen *testIDGenerator) NewIDs(ctx context.Context) (trace.TraceID, trace.SpanID) { |
| 1940 |
traceIDHex := fmt.Sprintf("%016x%016x", gen.traceIDHigh, gen.traceIDLow) |
| 1941 |
traceID, _ := trace.TraceIDFromHex(traceIDHex) |
| 1942 |
gen.traceIDLow++ |
| 1943 |
|
| 1944 |
spanID := gen.NewSpanID(ctx, traceID) |
| 1945 |
return traceID, spanID |
| 1946 |
} |
| 1947 |
|
| 1948 |
func (gen *testIDGenerator) NewSpanID(context.Context, trace.TraceID) trace.SpanID { |
| 1949 |
spanIDHex := fmt.Sprintf("%016x", gen.spanID) |
| 1950 |
spanID, _ := trace.SpanIDFromHex(spanIDHex) |
| 1951 |
gen.spanID++ |
| 1952 |
return spanID |
| 1953 |
} |
| 1954 |
|
| 1955 |
var _ IDGenerator = (*testIDGenerator)(nil) |
| 1956 |
|
| 1957 |
func TestWithIDGenerator(t *testing.T) { |
| 1958 |
const ( |
| 1959 |
startTraceIDHigh uint64 = 0x1001_1001_1001_1001 |
| 1960 |
startTraceIDLow uint64 = 0x2002_2002_2002_2002 |
| 1961 |
startSpanID uint64 = 0x3003_3003_3003_3003 |
| 1962 |
numSpan = 5 |
| 1963 |
) |
| 1964 |
|
| 1965 |
gen := &testIDGenerator{traceIDHigh: startTraceIDHigh, traceIDLow: startTraceIDLow, spanID: startSpanID} |
| 1966 |
te := NewTestExporter() |
| 1967 |
tp := NewTracerProvider( |
| 1968 |
WithSyncer(te), |
| 1969 |
WithIDGenerator(gen), |
| 1970 |
) |
| 1971 |
for i := range numSpan { |
| 1972 |
func() { |
| 1973 |
_, span := tp.Tracer(t.Name()).Start(t.Context(), strconv.Itoa(i)) |
| 1974 |
defer span.End() |
| 1975 |
|
| 1976 |
gotSpanID, err := strconv.ParseUint(span.SpanContext().SpanID().String(), 16, 64) |
| 1977 |
require.NoError(t, err) |
| 1978 |
assert.Equal(t, startSpanID+uint64(i), gotSpanID) |
| 1979 |
|
| 1980 |
traceIdStr := span.SpanContext().TraceID().String() |
| 1981 |
highBitsStr := traceIdStr[:16] |
| 1982 |
lowBitsStr := traceIdStr[16:] |
| 1983 |
|
| 1984 |
traceIdValidator := func(t *testing.T, id string, expected uint64) { |
| 1985 |
gotTraceID, err := strconv.ParseUint(id, 16, 64) |
| 1986 |
require.NoError(t, err) |
| 1987 |
assert.Equal(t, expected, gotTraceID) |
| 1988 |
} |
| 1989 |
traceIdValidator(t, highBitsStr, startTraceIDHigh) |
| 1990 |
traceIdValidator(t, lowBitsStr, startTraceIDLow+uint64(i)) |
| 1991 |
}() |
| 1992 |
} |
| 1993 |
} |
| 1994 |
|
| 1995 |
func TestIDsRoundTrip(t *testing.T) { |
| 1996 |
gen := defaultIDGenerator() |
| 1997 |
|
| 1998 |
for range 1000 { |
| 1999 |
traceID, spanID := gen.NewIDs(t.Context()) |
| 2000 |
gotTraceID, err := trace.TraceIDFromHex(traceID.String()) |
| 2001 |
assert.NoError(t, err) |
| 2002 |
assert.Equal(t, traceID, gotTraceID) |
| 2003 |
gotSpanID, err := trace.SpanIDFromHex(spanID.String()) |
| 2004 |
assert.NoError(t, err) |
| 2005 |
assert.Equal(t, spanID, gotSpanID) |
| 2006 |
} |
| 2007 |
} |
| 2008 |
|
| 2009 |
func TestIDConversionErrors(t *testing.T) { |
| 2010 |
for _, tt := range []struct { |
| 2011 |
name string |
| 2012 |
spanIDStr string |
| 2013 |
traceIDStr string |
| 2014 |
spanIDError string |
| 2015 |
traceIDError string |
| 2016 |
}{ |
| 2017 |
{ |
| 2018 |
name: "slightly too long", |
| 2019 |
spanIDStr: sid.String() + "0", |
| 2020 |
spanIDError: "hex encoded span-id must have length equals to 16", |
| 2021 |
traceIDStr: tid.String() + "0", |
| 2022 |
traceIDError: "hex encoded trace-id must have length equals to 32", |
| 2023 |
}, |
| 2024 |
{ |
| 2025 |
name: "blank input", |
| 2026 |
spanIDStr: "", |
| 2027 |
spanIDError: "hex encoded span-id must have length equals to 16", |
| 2028 |
traceIDStr: "", |
| 2029 |
traceIDError: "hex encoded trace-id must have length equals to 32", |
| 2030 |
}, |
| 2031 |
{ |
| 2032 |
name: "not hex", |
| 2033 |
spanIDStr: "unacceptablechar", |
| 2034 |
spanIDError: "trace-id and span-id can only contain [0-9a-f] characters, all lowercase", |
| 2035 |
traceIDStr: "completely unacceptablecharacter", |
| 2036 |
traceIDError: "trace-id and span-id can only contain [0-9a-f] characters, all lowercase", |
| 2037 |
}, |
| 2038 |
{ |
| 2039 |
name: "upper-case hex", |
| 2040 |
spanIDStr: "DEADBEEFBAD0CAFE", |
| 2041 |
spanIDError: "trace-id and span-id can only contain [0-9a-f] characters, all lowercase", |
| 2042 |
traceIDStr: "DEADBEEFBAD0CAFEDEADBEEFBAD0CAFE", |
| 2043 |
traceIDError: "trace-id and span-id can only contain [0-9a-f] characters, all lowercase", |
| 2044 |
}, |
| 2045 |
{ |
| 2046 |
name: "all zero", |
| 2047 |
spanIDStr: "0000000000000000", |
| 2048 |
spanIDError: "span-id can't be all zero", |
| 2049 |
traceIDStr: "00000000000000000000000000000000", |
| 2050 |
traceIDError: "trace-id can't be all zero", |
| 2051 |
}, |
| 2052 |
} { |
| 2053 |
t.Run(tt.name, func(t *testing.T) { |
| 2054 |
_, err := trace.SpanIDFromHex(tt.spanIDStr) |
| 2055 |
assert.ErrorContains(t, err, tt.spanIDError) |
| 2056 |
_, err = trace.TraceIDFromHex(tt.traceIDStr) |
| 2057 |
assert.ErrorContains(t, err, tt.traceIDError) |
| 2058 |
}) |
| 2059 |
} |
| 2060 |
} |
| 2061 |
|
| 2062 |
func TestEmptyRecordingSpanAttributes(t *testing.T) { |
| 2063 |
assert.Nil(t, (&recordingSpan{}).Attributes()) |
| 2064 |
} |
| 2065 |
|
| 2066 |
func TestEmptyRecordingSpanDroppedAttributes(t *testing.T) { |
| 2067 |
assert.Equal(t, 0, (&recordingSpan{}).DroppedAttributes()) |
| 2068 |
} |
| 2069 |
|
| 2070 |
func TestSpanAddLink(t *testing.T) { |
| 2071 |
tests := []struct { |
| 2072 |
name string |
| 2073 |
attrLinkCountLimit int |
| 2074 |
link trace.Link |
| 2075 |
want *snapshot |
| 2076 |
}{ |
| 2077 |
{ |
| 2078 |
name: "AddLinkWithInvalidSpanContext", |
| 2079 |
attrLinkCountLimit: 128, |
| 2080 |
link: trace.Link{ |
| 2081 |
SpanContext: trace.NewSpanContext( |
| 2082 |
trace.SpanContextConfig{TraceID: trace.TraceID([16]byte{}), SpanID: [8]byte{}}, |
| 2083 |
), |
| 2084 |
}, |
| 2085 |
want: &snapshot{ |
| 2086 |
name: "span0", |
| 2087 |
spanContext: trace.NewSpanContext(trace.SpanContextConfig{ |
| 2088 |
TraceID: tid, |
| 2089 |
TraceFlags: 0x1, |
| 2090 |
}), |
| 2091 |
parent: sc.WithRemote(true), |
| 2092 |
links: nil, |
| 2093 |
spanKind: trace.SpanKindInternal, |
| 2094 |
instrumentationScope: instrumentation.Scope{Name: "AddLinkWithInvalidSpanContext"}, |
| 2095 |
}, |
| 2096 |
}, |
| 2097 |
{ |
| 2098 |
name: "AddLink", |
| 2099 |
attrLinkCountLimit: 128, |
| 2100 |
link: trace.Link{ |
| 2101 |
SpanContext: sc, |
| 2102 |
Attributes: []attribute.KeyValue{{Key: "k1", Value: attribute.StringValue("v1")}}, |
| 2103 |
}, |
| 2104 |
want: &snapshot{ |
| 2105 |
name: "span0", |
| 2106 |
spanContext: trace.NewSpanContext(trace.SpanContextConfig{ |
| 2107 |
TraceID: tid, |
| 2108 |
TraceFlags: 0x1, |
| 2109 |
}), |
| 2110 |
parent: sc.WithRemote(true), |
| 2111 |
links: []Link{ |
| 2112 |
{ |
| 2113 |
SpanContext: sc, |
| 2114 |
Attributes: []attribute.KeyValue{{Key: "k1", Value: attribute.StringValue("v1")}}, |
| 2115 |
}, |
| 2116 |
}, |
| 2117 |
spanKind: trace.SpanKindInternal, |
| 2118 |
instrumentationScope: instrumentation.Scope{Name: "AddLink"}, |
| 2119 |
}, |
| 2120 |
}, |
| 2121 |
{ |
| 2122 |
name: "AddLinkWithMoreAttributesThanLimit", |
| 2123 |
attrLinkCountLimit: 1, |
| 2124 |
link: trace.Link{ |
| 2125 |
SpanContext: sc, |
| 2126 |
Attributes: []attribute.KeyValue{ |
| 2127 |
{Key: "k1", Value: attribute.StringValue("v1")}, |
| 2128 |
{Key: "k2", Value: attribute.StringValue("v2")}, |
| 2129 |
{Key: "k3", Value: attribute.StringValue("v3")}, |
| 2130 |
{Key: "k4", Value: attribute.StringValue("v4")}, |
| 2131 |
}, |
| 2132 |
}, |
| 2133 |
want: &snapshot{ |
| 2134 |
name: "span0", |
| 2135 |
spanContext: trace.NewSpanContext(trace.SpanContextConfig{ |
| 2136 |
TraceID: tid, |
| 2137 |
TraceFlags: 0x1, |
| 2138 |
}), |
| 2139 |
parent: sc.WithRemote(true), |
| 2140 |
links: []Link{ |
| 2141 |
{ |
| 2142 |
SpanContext: sc, |
| 2143 |
Attributes: []attribute.KeyValue{{Key: "k1", Value: attribute.StringValue("v1")}}, |
| 2144 |
DroppedAttributeCount: 3, |
| 2145 |
}, |
| 2146 |
}, |
| 2147 |
spanKind: trace.SpanKindInternal, |
| 2148 |
instrumentationScope: instrumentation.Scope{Name: "AddLinkWithMoreAttributesThanLimit"}, |
| 2149 |
}, |
| 2150 |
}, |
| 2151 |
{ |
| 2152 |
name: "AddLinkWithAttributesEmptySpanContext", |
| 2153 |
attrLinkCountLimit: 128, |
| 2154 |
link: trace.Link{ |
| 2155 |
Attributes: []attribute.KeyValue{{Key: "k1", Value: attribute.StringValue("v1")}}, |
| 2156 |
}, |
| 2157 |
want: &snapshot{ |
| 2158 |
name: "span0", |
| 2159 |
spanContext: trace.NewSpanContext(trace.SpanContextConfig{ |
| 2160 |
TraceID: tid, |
| 2161 |
TraceFlags: 0x1, |
| 2162 |
}), |
| 2163 |
parent: sc.WithRemote(true), |
| 2164 |
links: []Link{ |
| 2165 |
{ |
| 2166 |
Attributes: []attribute.KeyValue{{Key: "k1", Value: attribute.StringValue("v1")}}, |
| 2167 |
}, |
| 2168 |
}, |
| 2169 |
spanKind: trace.SpanKindInternal, |
| 2170 |
instrumentationScope: instrumentation.Scope{Name: "AddLinkWithAttributesEmptySpanContext"}, |
| 2171 |
}, |
| 2172 |
}, |
| 2173 |
{ |
| 2174 |
name: "AddLinkWithTraceStateEmptySpanContext", |
| 2175 |
attrLinkCountLimit: 128, |
| 2176 |
link: trace.Link{ |
| 2177 |
SpanContext: trace.SpanContext{}.WithTraceState(ts), |
| 2178 |
}, |
| 2179 |
want: &snapshot{ |
| 2180 |
name: "span0", |
| 2181 |
spanContext: trace.NewSpanContext(trace.SpanContextConfig{ |
| 2182 |
TraceID: tid, |
| 2183 |
TraceFlags: 0x1, |
| 2184 |
}), |
| 2185 |
parent: sc.WithRemote(true), |
| 2186 |
links: []Link{ |
| 2187 |
{ |
| 2188 |
SpanContext: trace.SpanContext{}.WithTraceState(ts), |
| 2189 |
}, |
| 2190 |
}, |
| 2191 |
spanKind: trace.SpanKindInternal, |
| 2192 |
instrumentationScope: instrumentation.Scope{Name: "AddLinkWithTraceStateEmptySpanContext"}, |
| 2193 |
}, |
| 2194 |
}, |
| 2195 |
} |
| 2196 |
|
| 2197 |
for _, tc := range tests { |
| 2198 |
t.Run(tc.name, func(t *testing.T) { |
| 2199 |
te := NewTestExporter() |
| 2200 |
sl := NewSpanLimits() |
| 2201 |
sl.AttributePerLinkCountLimit = tc.attrLinkCountLimit |
| 2202 |
|
| 2203 |
tp := NewTracerProvider(WithSpanLimits(sl), WithSyncer(te), WithResource(resource.Empty())) |
| 2204 |
|
| 2205 |
span := startSpan(tp, tc.name) |
| 2206 |
span.AddLink(tc.link) |
| 2207 |
|
| 2208 |
got, err := endSpan(te, span) |
| 2209 |
if err != nil { |
| 2210 |
t.Fatal(err) |
| 2211 |
} |
| 2212 |
|
| 2213 |
if diff := cmpDiff(got, tc.want); diff != "" { |
| 2214 |
t.Errorf("-got +want %s", diff) |
| 2215 |
} |
| 2216 |
}) |
| 2217 |
} |
| 2218 |
} |
| 2219 |
|
| 2220 |
func TestAddLinkToNonRecordingSpan(t *testing.T) { |
| 2221 |
te := NewTestExporter() |
| 2222 |
sl := NewSpanLimits() |
| 2223 |
tp := NewTracerProvider( |
| 2224 |
WithSpanLimits(sl), |
| 2225 |
WithSyncer(te), |
| 2226 |
WithResource(resource.Empty()), |
| 2227 |
) |
| 2228 |
|
| 2229 |
attrs := []attribute.KeyValue{{Key: "k", Value: attribute.StringValue("v")}} |
| 2230 |
|
| 2231 |
span := startSpan(tp, "AddLinkToNonRecordingSpan") |
| 2232 |
_, err := endSpan(te, span) |
| 2233 |
require.NoError(t, err) |
| 2234 |
|
| 2235 |
// Add link to ended, non-recording, span. The link should be dropped. |
| 2236 |
span.AddLink(trace.Link{ |
| 2237 |
SpanContext: sc, |
| 2238 |
Attributes: attrs, |
| 2239 |
}) |
| 2240 |
|
| 2241 |
require.Equal(t, 1, te.Len()) |
| 2242 |
got := te.Spans()[0] |
| 2243 |
want := &snapshot{ |
| 2244 |
name: "span0", |
| 2245 |
spanContext: trace.NewSpanContext(trace.SpanContextConfig{ |
| 2246 |
TraceID: tid, |
| 2247 |
TraceFlags: 0x1, |
| 2248 |
}), |
| 2249 |
parent: sc.WithRemote(true), |
| 2250 |
links: nil, |
| 2251 |
spanKind: trace.SpanKindInternal, |
| 2252 |
instrumentationScope: instrumentation.Scope{Name: "AddLinkToNonRecordingSpan"}, |
| 2253 |
} |
| 2254 |
|
| 2255 |
if diff := cmpDiff(got, want); diff != "" { |
| 2256 |
t.Errorf("AddLinkToNonRecordingSpan: -got +want %s", diff) |
| 2257 |
} |
| 2258 |
} |
| 2259 |
|
| 2260 |
func TestObservability(t *testing.T) { |
| 2261 |
testCases := []struct { |
| 2262 |
name string |
| 2263 |
test func(t *testing.T, scopeMetrics func() metricdata.ScopeMetrics) |
| 2264 |
}{ |
| 2265 |
{ |
| 2266 |
name: "SampledSpan", |
| 2267 |
test: func(t *testing.T, scopeMetrics func() metricdata.ScopeMetrics) { |
| 2268 |
tp := NewTracerProvider() |
| 2269 |
_, span := tp.Tracer("").Start(t.Context(), "StartSpan") |
| 2270 |
|
| 2271 |
want := metricdata.ScopeMetrics{ |
| 2272 |
Scope: instrumentation.Scope{ |
| 2273 |
Name: observ.ScopeName, |
| 2274 |
Version: sdk.Version(), |
| 2275 |
SchemaURL: observ.SchemaURL, |
| 2276 |
}, |
| 2277 |
Metrics: []metricdata.Metrics{ |
| 2278 |
{ |
| 2279 |
Name: otelconv.SDKSpanLive{}.Name(), |
| 2280 |
Description: otelconv.SDKSpanLive{}.Description(), |
| 2281 |
Unit: otelconv.SDKSpanLive{}.Unit(), |
| 2282 |
Data: metricdata.Sum[int64]{ |
| 2283 |
Temporality: metricdata.CumulativeTemporality, |
| 2284 |
DataPoints: []metricdata.DataPoint[int64]{ |
| 2285 |
{ |
| 2286 |
Attributes: attribute.NewSet( |
| 2287 |
otelconv.SDKSpanLive{}.AttrSpanSamplingResult( |
| 2288 |
otelconv.SpanSamplingResultRecordAndSample, |
| 2289 |
), |
| 2290 |
), |
| 2291 |
Value: 1, |
| 2292 |
}, |
| 2293 |
}, |
| 2294 |
}, |
| 2295 |
}, |
| 2296 |
{ |
| 2297 |
Name: otelconv.SDKSpanStarted{}.Name(), |
| 2298 |
Description: otelconv.SDKSpanStarted{}.Description(), |
| 2299 |
Unit: otelconv.SDKSpanStarted{}.Unit(), |
| 2300 |
Data: metricdata.Sum[int64]{ |
| 2301 |
Temporality: metricdata.CumulativeTemporality, |
| 2302 |
IsMonotonic: true, |
| 2303 |
DataPoints: []metricdata.DataPoint[int64]{ |
| 2304 |
{ |
| 2305 |
Attributes: attribute.NewSet( |
| 2306 |
otelconv.SDKSpanStarted{}.AttrSpanParentOrigin( |
| 2307 |
otelconv.SpanParentOriginNone, |
| 2308 |
), |
| 2309 |
otelconv.SDKSpanStarted{}.AttrSpanSamplingResult( |
| 2310 |
otelconv.SpanSamplingResultRecordAndSample, |
| 2311 |
), |
| 2312 |
), |
| 2313 |
Value: 1, |
| 2314 |
}, |
| 2315 |
}, |
| 2316 |
}, |
| 2317 |
}, |
| 2318 |
}, |
| 2319 |
} |
| 2320 |
|
| 2321 |
got := scopeMetrics() |
| 2322 |
metricdatatest.AssertEqual( |
| 2323 |
t, |
| 2324 |
want, |
| 2325 |
got, |
| 2326 |
metricdatatest.IgnoreTimestamp(), |
| 2327 |
metricdatatest.IgnoreExemplars(), |
| 2328 |
) |
| 2329 |
|
| 2330 |
span.End() |
| 2331 |
|
| 2332 |
want = metricdata.ScopeMetrics{ |
| 2333 |
Scope: instrumentation.Scope{ |
| 2334 |
Name: observ.ScopeName, |
| 2335 |
Version: sdk.Version(), |
| 2336 |
SchemaURL: observ.SchemaURL, |
| 2337 |
}, |
| 2338 |
Metrics: []metricdata.Metrics{ |
| 2339 |
{ |
| 2340 |
Name: otelconv.SDKSpanLive{}.Name(), |
| 2341 |
Description: otelconv.SDKSpanLive{}.Description(), |
| 2342 |
Unit: otelconv.SDKSpanLive{}.Unit(), |
| 2343 |
Data: metricdata.Sum[int64]{ |
| 2344 |
Temporality: metricdata.CumulativeTemporality, |
| 2345 |
DataPoints: []metricdata.DataPoint[int64]{ |
| 2346 |
{ |
| 2347 |
Attributes: attribute.NewSet( |
| 2348 |
otelconv.SDKSpanLive{}.AttrSpanSamplingResult( |
| 2349 |
otelconv.SpanSamplingResultRecordAndSample, |
| 2350 |
), |
| 2351 |
), |
| 2352 |
Value: 0, // No live spans at this point. |
| 2353 |
}, |
| 2354 |
}, |
| 2355 |
}, |
| 2356 |
}, |
| 2357 |
{ |
| 2358 |
Name: otelconv.SDKSpanStarted{}.Name(), |
| 2359 |
Description: otelconv.SDKSpanStarted{}.Description(), |
| 2360 |
Unit: otelconv.SDKSpanStarted{}.Unit(), |
| 2361 |
Data: metricdata.Sum[int64]{ |
| 2362 |
Temporality: metricdata.CumulativeTemporality, |
| 2363 |
IsMonotonic: true, |
| 2364 |
DataPoints: []metricdata.DataPoint[int64]{ |
| 2365 |
{ |
| 2366 |
Attributes: attribute.NewSet( |
| 2367 |
otelconv.SDKSpanStarted{}.AttrSpanParentOrigin( |
| 2368 |
otelconv.SpanParentOriginNone, |
| 2369 |
), |
| 2370 |
otelconv.SDKSpanStarted{}.AttrSpanSamplingResult( |
| 2371 |
otelconv.SpanSamplingResultRecordAndSample, |
| 2372 |
), |
| 2373 |
), |
| 2374 |
Value: 1, |
| 2375 |
}, |
| 2376 |
}, |
| 2377 |
}, |
| 2378 |
}, |
| 2379 |
}, |
| 2380 |
} |
| 2381 |
got = scopeMetrics() |
| 2382 |
metricdatatest.AssertEqual( |
| 2383 |
t, |
| 2384 |
want, |
| 2385 |
got, |
| 2386 |
metricdatatest.IgnoreTimestamp(), |
| 2387 |
metricdatatest.IgnoreExemplars(), |
| 2388 |
) |
| 2389 |
}, |
| 2390 |
}, |
| 2391 |
{ |
| 2392 |
name: "NonRecordingSpan", |
| 2393 |
test: func(t *testing.T, scopeMetrics func() metricdata.ScopeMetrics) { |
| 2394 |
// Create a tracer provider with NeverSample sampler to get non-recording spans. |
| 2395 |
tp := NewTracerProvider(WithSampler(NeverSample())) |
| 2396 |
tp.Tracer("").Start(t.Context(), "NonRecordingSpan") |
| 2397 |
|
| 2398 |
want := metricdata.ScopeMetrics{ |
| 2399 |
Scope: instrumentation.Scope{ |
| 2400 |
Name: observ.ScopeName, |
| 2401 |
Version: sdk.Version(), |
| 2402 |
SchemaURL: observ.SchemaURL, |
| 2403 |
}, |
| 2404 |
Metrics: []metricdata.Metrics{ |
| 2405 |
{ |
| 2406 |
Name: otelconv.SDKSpanStarted{}.Name(), |
| 2407 |
Description: otelconv.SDKSpanStarted{}.Description(), |
| 2408 |
Unit: otelconv.SDKSpanStarted{}.Unit(), |
| 2409 |
Data: metricdata.Sum[int64]{ |
| 2410 |
Temporality: metricdata.CumulativeTemporality, |
| 2411 |
IsMonotonic: true, |
| 2412 |
DataPoints: []metricdata.DataPoint[int64]{ |
| 2413 |
{ |
| 2414 |
Attributes: attribute.NewSet( |
| 2415 |
otelconv.SDKSpanStarted{}.AttrSpanParentOrigin( |
| 2416 |
otelconv.SpanParentOriginNone, |
| 2417 |
), |
| 2418 |
otelconv.SDKSpanStarted{}.AttrSpanSamplingResult( |
| 2419 |
otelconv.SpanSamplingResultDrop, |
| 2420 |
), |
| 2421 |
), |
| 2422 |
Value: 1, |
| 2423 |
}, |
| 2424 |
}, |
| 2425 |
}, |
| 2426 |
}, |
| 2427 |
}, |
| 2428 |
} |
| 2429 |
|
| 2430 |
got := scopeMetrics() |
| 2431 |
metricdatatest.AssertEqual( |
| 2432 |
t, |
| 2433 |
want, |
| 2434 |
got, |
| 2435 |
metricdatatest.IgnoreTimestamp(), |
| 2436 |
metricdatatest.IgnoreExemplars(), |
| 2437 |
) |
| 2438 |
}, |
| 2439 |
}, |
| 2440 |
{ |
| 2441 |
name: "OnlyRecordingSpan", |
| 2442 |
test: func(t *testing.T, scopeMetrics func() metricdata.ScopeMetrics) { |
| 2443 |
// Create a tracer provider with NeverSample sampler to get non-recording spans. |
| 2444 |
tp := NewTracerProvider(WithSampler(RecordingOnly())) |
| 2445 |
tp.Tracer("").Start(t.Context(), "OnlyRecordingSpan") |
| 2446 |
|
| 2447 |
want := metricdata.ScopeMetrics{ |
| 2448 |
Scope: instrumentation.Scope{ |
| 2449 |
Name: observ.ScopeName, |
| 2450 |
Version: sdk.Version(), |
| 2451 |
SchemaURL: observ.SchemaURL, |
| 2452 |
}, |
| 2453 |
Metrics: []metricdata.Metrics{ |
| 2454 |
{ |
| 2455 |
Name: otelconv.SDKSpanLive{}.Name(), |
| 2456 |
Description: otelconv.SDKSpanLive{}.Description(), |
| 2457 |
Unit: otelconv.SDKSpanLive{}.Unit(), |
| 2458 |
Data: metricdata.Sum[int64]{ |
| 2459 |
Temporality: metricdata.CumulativeTemporality, |
| 2460 |
DataPoints: []metricdata.DataPoint[int64]{ |
| 2461 |
{ |
| 2462 |
Attributes: attribute.NewSet( |
| 2463 |
otelconv.SDKSpanLive{}.AttrSpanSamplingResult( |
| 2464 |
otelconv.SpanSamplingResultRecordOnly, |
| 2465 |
), |
| 2466 |
), |
| 2467 |
Value: 1, |
| 2468 |
}, |
| 2469 |
}, |
| 2470 |
}, |
| 2471 |
}, |
| 2472 |
{ |
| 2473 |
Name: otelconv.SDKSpanStarted{}.Name(), |
| 2474 |
Description: otelconv.SDKSpanStarted{}.Description(), |
| 2475 |
Unit: otelconv.SDKSpanStarted{}.Unit(), |
| 2476 |
Data: metricdata.Sum[int64]{ |
| 2477 |
Temporality: metricdata.CumulativeTemporality, |
| 2478 |
IsMonotonic: true, |
| 2479 |
DataPoints: []metricdata.DataPoint[int64]{ |
| 2480 |
{ |
| 2481 |
Attributes: attribute.NewSet( |
| 2482 |
otelconv.SDKSpanStarted{}.AttrSpanParentOrigin( |
| 2483 |
otelconv.SpanParentOriginNone, |
| 2484 |
), |
| 2485 |
otelconv.SDKSpanStarted{}.AttrSpanSamplingResult( |
| 2486 |
otelconv.SpanSamplingResultRecordOnly, |
| 2487 |
), |
| 2488 |
), |
| 2489 |
Value: 1, |
| 2490 |
}, |
| 2491 |
}, |
| 2492 |
}, |
| 2493 |
}, |
| 2494 |
}, |
| 2495 |
} |
| 2496 |
|
| 2497 |
got := scopeMetrics() |
| 2498 |
metricdatatest.AssertEqual( |
| 2499 |
t, |
| 2500 |
want, |
| 2501 |
got, |
| 2502 |
metricdatatest.IgnoreTimestamp(), |
| 2503 |
metricdatatest.IgnoreExemplars(), |
| 2504 |
) |
| 2505 |
}, |
| 2506 |
}, |
| 2507 |
{ |
| 2508 |
name: "RemoteParentSpan", |
| 2509 |
test: func(t *testing.T, scopeMetrics func() metricdata.ScopeMetrics) { |
| 2510 |
// Create a remote parent context |
| 2511 |
tid, _ := trace.TraceIDFromHex("01020304050607080102040810203040") |
| 2512 |
sid, _ := trace.SpanIDFromHex("0102040810203040") |
| 2513 |
remoteCtx := trace.ContextWithRemoteSpanContext(t.Context(), |
| 2514 |
trace.NewSpanContext(trace.SpanContextConfig{ |
| 2515 |
TraceID: tid, |
| 2516 |
SpanID: sid, |
| 2517 |
TraceFlags: 0x1, |
| 2518 |
Remote: true, |
| 2519 |
})) |
| 2520 |
|
| 2521 |
tp := NewTracerProvider() |
| 2522 |
tp.Tracer("").Start(remoteCtx, "ChildSpan") |
| 2523 |
|
| 2524 |
want := metricdata.ScopeMetrics{ |
| 2525 |
Scope: instrumentation.Scope{ |
| 2526 |
Name: observ.ScopeName, |
| 2527 |
Version: sdk.Version(), |
| 2528 |
SchemaURL: observ.SchemaURL, |
| 2529 |
}, |
| 2530 |
Metrics: []metricdata.Metrics{ |
| 2531 |
{ |
| 2532 |
Name: otelconv.SDKSpanLive{}.Name(), |
| 2533 |
Description: otelconv.SDKSpanLive{}.Description(), |
| 2534 |
Unit: otelconv.SDKSpanLive{}.Unit(), |
| 2535 |
Data: metricdata.Sum[int64]{ |
| 2536 |
Temporality: metricdata.CumulativeTemporality, |
| 2537 |
DataPoints: []metricdata.DataPoint[int64]{ |
| 2538 |
{ |
| 2539 |
Attributes: attribute.NewSet( |
| 2540 |
otelconv.SDKSpanLive{}.AttrSpanSamplingResult( |
| 2541 |
otelconv.SpanSamplingResultRecordAndSample, |
| 2542 |
), |
| 2543 |
), |
| 2544 |
Value: 1, |
| 2545 |
}, |
| 2546 |
}, |
| 2547 |
}, |
| 2548 |
}, |
| 2549 |
{ |
| 2550 |
Name: otelconv.SDKSpanStarted{}.Name(), |
| 2551 |
Description: otelconv.SDKSpanStarted{}.Description(), |
| 2552 |
Unit: otelconv.SDKSpanStarted{}.Unit(), |
| 2553 |
Data: metricdata.Sum[int64]{ |
| 2554 |
Temporality: metricdata.CumulativeTemporality, |
| 2555 |
IsMonotonic: true, |
| 2556 |
DataPoints: []metricdata.DataPoint[int64]{ |
| 2557 |
{ |
| 2558 |
Attributes: attribute.NewSet( |
| 2559 |
otelconv.SDKSpanStarted{}.AttrSpanParentOrigin( |
| 2560 |
otelconv.SpanParentOriginRemote, |
| 2561 |
), |
| 2562 |
otelconv.SDKSpanStarted{}.AttrSpanSamplingResult( |
| 2563 |
otelconv.SpanSamplingResultRecordAndSample, |
| 2564 |
), |
| 2565 |
), |
| 2566 |
Value: 1, |
| 2567 |
}, |
| 2568 |
}, |
| 2569 |
}, |
| 2570 |
}, |
| 2571 |
}, |
| 2572 |
} |
| 2573 |
got := scopeMetrics() |
| 2574 |
metricdatatest.AssertEqual( |
| 2575 |
t, |
| 2576 |
want, |
| 2577 |
got, |
| 2578 |
metricdatatest.IgnoreTimestamp(), |
| 2579 |
metricdatatest.IgnoreExemplars(), |
| 2580 |
) |
| 2581 |
}, |
| 2582 |
}, |
| 2583 |
{ |
| 2584 |
name: "LocalParentSpan", |
| 2585 |
test: func(t *testing.T, scopeMetrics func() metricdata.ScopeMetrics) { |
| 2586 |
tp := NewTracerProvider() |
| 2587 |
ctx, parentSpan := tp.Tracer("").Start(t.Context(), "ParentSpan") |
| 2588 |
_, childSpan := tp.Tracer("").Start(ctx, "ChildSpan") |
| 2589 |
|
| 2590 |
want := metricdata.ScopeMetrics{ |
| 2591 |
Scope: instrumentation.Scope{ |
| 2592 |
Name: observ.ScopeName, |
| 2593 |
Version: sdk.Version(), |
| 2594 |
SchemaURL: observ.SchemaURL, |
| 2595 |
}, |
| 2596 |
Metrics: []metricdata.Metrics{ |
| 2597 |
{ |
| 2598 |
Name: otelconv.SDKSpanLive{}.Name(), |
| 2599 |
Description: otelconv.SDKSpanLive{}.Description(), |
| 2600 |
Unit: otelconv.SDKSpanLive{}.Unit(), |
| 2601 |
Data: metricdata.Sum[int64]{ |
| 2602 |
Temporality: metricdata.CumulativeTemporality, |
| 2603 |
DataPoints: []metricdata.DataPoint[int64]{ |
| 2604 |
{ |
| 2605 |
Attributes: attribute.NewSet( |
| 2606 |
otelconv.SDKSpanLive{}.AttrSpanSamplingResult( |
| 2607 |
otelconv.SpanSamplingResultRecordAndSample, |
| 2608 |
), |
| 2609 |
), |
| 2610 |
Value: 2, // Both parent and child spans are active. |
| 2611 |
}, |
| 2612 |
}, |
| 2613 |
}, |
| 2614 |
}, |
| 2615 |
{ |
| 2616 |
Name: otelconv.SDKSpanStarted{}.Name(), |
| 2617 |
Description: otelconv.SDKSpanStarted{}.Description(), |
| 2618 |
Unit: otelconv.SDKSpanStarted{}.Unit(), |
| 2619 |
Data: metricdata.Sum[int64]{ |
| 2620 |
Temporality: metricdata.CumulativeTemporality, |
| 2621 |
IsMonotonic: true, |
| 2622 |
DataPoints: []metricdata.DataPoint[int64]{ |
| 2623 |
{ |
| 2624 |
Attributes: attribute.NewSet( |
| 2625 |
otelconv.SDKSpanStarted{}.AttrSpanParentOrigin( |
| 2626 |
otelconv.SpanParentOriginNone, |
| 2627 |
), |
| 2628 |
otelconv.SDKSpanStarted{}.AttrSpanSamplingResult( |
| 2629 |
otelconv.SpanSamplingResultRecordAndSample, |
| 2630 |
), |
| 2631 |
), |
| 2632 |
Value: 1, // Parent span with no parent of its own. |
| 2633 |
}, |
| 2634 |
{ |
| 2635 |
Attributes: attribute.NewSet( |
| 2636 |
otelconv.SDKSpanStarted{}.AttrSpanParentOrigin( |
| 2637 |
otelconv.SpanParentOriginLocal, |
| 2638 |
), |
| 2639 |
otelconv.SDKSpanStarted{}.AttrSpanSamplingResult( |
| 2640 |
otelconv.SpanSamplingResultRecordAndSample, |
| 2641 |
), |
| 2642 |
), |
| 2643 |
Value: 1, // Child span with local parent. |
| 2644 |
}, |
| 2645 |
}, |
| 2646 |
}, |
| 2647 |
}, |
| 2648 |
}, |
| 2649 |
} |
| 2650 |
|
| 2651 |
got := scopeMetrics() |
| 2652 |
metricdatatest.AssertEqual( |
| 2653 |
t, |
| 2654 |
want, |
| 2655 |
got, |
| 2656 |
metricdatatest.IgnoreTimestamp(), |
| 2657 |
metricdatatest.IgnoreExemplars(), |
| 2658 |
) |
| 2659 |
|
| 2660 |
childSpan.End() |
| 2661 |
parentSpan.End() |
| 2662 |
|
| 2663 |
want = metricdata.ScopeMetrics{ |
| 2664 |
Scope: instrumentation.Scope{ |
| 2665 |
Name: observ.ScopeName, |
| 2666 |
Version: sdk.Version(), |
| 2667 |
SchemaURL: observ.SchemaURL, |
| 2668 |
}, |
| 2669 |
Metrics: []metricdata.Metrics{ |
| 2670 |
{ |
| 2671 |
Name: otelconv.SDKSpanLive{}.Name(), |
| 2672 |
Description: otelconv.SDKSpanLive{}.Description(), |
| 2673 |
Unit: otelconv.SDKSpanLive{}.Unit(), |
| 2674 |
Data: metricdata.Sum[int64]{ |
| 2675 |
Temporality: metricdata.CumulativeTemporality, |
| 2676 |
DataPoints: []metricdata.DataPoint[int64]{ |
| 2677 |
{ |
| 2678 |
Attributes: attribute.NewSet( |
| 2679 |
otelconv.SDKSpanLive{}.AttrSpanSamplingResult( |
| 2680 |
otelconv.SpanSamplingResultRecordAndSample, |
| 2681 |
), |
| 2682 |
), |
| 2683 |
Value: 0, // No live spans after ending both. |
| 2684 |
}, |
| 2685 |
}, |
| 2686 |
}, |
| 2687 |
}, |
| 2688 |
{ |
| 2689 |
Name: otelconv.SDKSpanStarted{}.Name(), |
| 2690 |
Description: otelconv.SDKSpanStarted{}.Description(), |
| 2691 |
Unit: otelconv.SDKSpanStarted{}.Unit(), |
| 2692 |
Data: metricdata.Sum[int64]{ |
| 2693 |
Temporality: metricdata.CumulativeTemporality, |
| 2694 |
IsMonotonic: true, |
| 2695 |
DataPoints: []metricdata.DataPoint[int64]{ |
| 2696 |
{ |
| 2697 |
Attributes: attribute.NewSet( |
| 2698 |
otelconv.SDKSpanStarted{}.AttrSpanParentOrigin( |
| 2699 |
otelconv.SpanParentOriginNone, |
| 2700 |
), |
| 2701 |
otelconv.SDKSpanStarted{}.AttrSpanSamplingResult( |
| 2702 |
otelconv.SpanSamplingResultRecordAndSample, |
| 2703 |
), |
| 2704 |
), |
| 2705 |
Value: 1, |
| 2706 |
}, |
| 2707 |
{ |
| 2708 |
Attributes: attribute.NewSet( |
| 2709 |
otelconv.SDKSpanStarted{}.AttrSpanParentOrigin( |
| 2710 |
otelconv.SpanParentOriginLocal, |
| 2711 |
), |
| 2712 |
otelconv.SDKSpanStarted{}.AttrSpanSamplingResult( |
| 2713 |
otelconv.SpanSamplingResultRecordAndSample, |
| 2714 |
), |
| 2715 |
), |
| 2716 |
Value: 1, |
| 2717 |
}, |
| 2718 |
}, |
| 2719 |
}, |
| 2720 |
}, |
| 2721 |
}, |
| 2722 |
} |
| 2723 |
|
| 2724 |
got = scopeMetrics() |
| 2725 |
metricdatatest.AssertEqual( |
| 2726 |
t, |
| 2727 |
want, |
| 2728 |
got, |
| 2729 |
metricdatatest.IgnoreTimestamp(), |
| 2730 |
metricdatatest.IgnoreExemplars(), |
| 2731 |
) |
| 2732 |
}, |
| 2733 |
}, |
| 2734 |
} |
| 2735 |
for _, tc := range testCases { |
| 2736 |
t.Run(tc.name, func(t *testing.T) { |
| 2737 |
t.Setenv("OTEL_GO_X_OBSERVABILITY", "True") |
| 2738 |
prev := otel.GetMeterProvider() |
| 2739 |
t.Cleanup(func() { otel.SetMeterProvider(prev) }) |
| 2740 |
|
| 2741 |
r := metric.NewManualReader() |
| 2742 |
mp := metric.NewMeterProvider(metric.WithReader(r)) |
| 2743 |
otel.SetMeterProvider(mp) |
| 2744 |
|
| 2745 |
scopeMetrics := func() metricdata.ScopeMetrics { |
| 2746 |
var got metricdata.ResourceMetrics |
| 2747 |
err := r.Collect(t.Context(), &got) |
| 2748 |
require.NoError(t, err) |
| 2749 |
require.Len(t, got.ScopeMetrics, 1) |
| 2750 |
return got.ScopeMetrics[0] |
| 2751 |
} |
| 2752 |
tc.test(t, scopeMetrics) |
| 2753 |
}) |
| 2754 |
} |
| 2755 |
} |
| 2756 |
|
| 2757 |
// ctxKeyT is a custom context value type used for testing context propagation. |
| 2758 |
type ctxKeyT string |
| 2759 |
|
| 2760 |
// ctxKey is a context key used to store and retrieve values in the context. |
| 2761 |
var ctxKey = ctxKeyT("testKey") |
| 2762 |
|
| 2763 |
func TestObservabilityContextPropagation(t *testing.T) { |
| 2764 |
t.Setenv("OTEL_GO_X_OBSERVABILITY", "True") |
| 2765 |
prev := otel.GetMeterProvider() |
| 2766 |
t.Cleanup(func() { otel.SetMeterProvider(prev) }) |
| 2767 |
|
| 2768 |
// Approximate number of expected measuresments. This is not a strict |
| 2769 |
// requirement, but it should be enough to ensure no backpressure. |
| 2770 |
const count = 3 * 2 // 3 measurements per span, 2 spans (parent and child). |
| 2771 |
ctxCh, fltr := filterFn(count) |
| 2772 |
|
| 2773 |
const want = "testValue" |
| 2774 |
n := make(chan int) |
| 2775 |
go func() { |
| 2776 |
// Validate the span context is propagated to all measurements by |
| 2777 |
// testing the context passed to the registered exemplar filter. This |
| 2778 |
// filter receives the measurement context in the standard metric SDK |
| 2779 |
// that we have registered. |
| 2780 |
|
| 2781 |
// Count of how many contexts were received. |
| 2782 |
var count int |
| 2783 |
|
| 2784 |
for ctx := range ctxCh { |
| 2785 |
count++ |
| 2786 |
|
| 2787 |
s := trace.SpanFromContext(ctx) |
| 2788 |
|
| 2789 |
// All spans should have a valid span context. This should be |
| 2790 |
// passed to the measurements in all cases. |
| 2791 |
isValid := s.SpanContext().IsValid() |
| 2792 |
assert.True(t, isValid, "Context should have a valid span") |
| 2793 |
|
| 2794 |
got := ctx.Value(ctxKey) |
| 2795 |
assert.Equal(t, want, got, "Context value not propagated") |
| 2796 |
} |
| 2797 |
n <- count |
| 2798 |
}() |
| 2799 |
|
| 2800 |
// At least one reader is required to not get a no-op MeterProvider and |
| 2801 |
// short-circuit any instrumentation measurements. |
| 2802 |
r := metric.NewManualReader() |
| 2803 |
mp := metric.NewMeterProvider( |
| 2804 |
metric.WithExemplarFilter(fltr), |
| 2805 |
metric.WithReader(r), |
| 2806 |
) |
| 2807 |
otel.SetMeterProvider(mp) |
| 2808 |
|
| 2809 |
tp := NewTracerProvider() |
| 2810 |
|
| 2811 |
wrap := func(parentCtx context.Context, name string, fn func(context.Context)) { |
| 2812 |
const tracer = "TestObservabilityContextPropagation" |
| 2813 |
ctx, s := tp.Tracer(tracer).Start(parentCtx, name) |
| 2814 |
defer s.End() |
| 2815 |
fn(ctx) |
| 2816 |
} |
| 2817 |
|
| 2818 |
ctx := context.WithValue(t.Context(), ctxKey, want) |
| 2819 |
wrap(ctx, "parent", func(ctx context.Context) { |
| 2820 |
wrap(ctx, "child", func(context.Context) {}) |
| 2821 |
}) |
| 2822 |
|
| 2823 |
require.NoError(t, tp.Shutdown(t.Context())) |
| 2824 |
|
| 2825 |
// The TracerProvider shutdown returned, no more measurements will be sent |
| 2826 |
// to the exemplar filter. |
| 2827 |
close(ctxCh) |
| 2828 |
|
| 2829 |
assert.Positive(t, <-n, "Expected at least 1 context propagations") |
| 2830 |
} |
| 2831 |
|
| 2832 |
// filterFn returns a channel that receives contexts passed to the returned |
| 2833 |
// exemplar filter function. |
| 2834 |
func filterFn(n int) (chan context.Context, func(ctx context.Context) bool) { |
| 2835 |
out := make(chan context.Context, n) |
| 2836 |
return out, func(ctx context.Context) bool { |
| 2837 |
out <- ctx |
| 2838 |
return true |
| 2839 |
} |
| 2840 |
} |
| 2841 |
|
| 2842 |
// RecordingOnly creates a Sampler that samples no traces, but enables recording. |
| 2843 |
// The created sampler maintains any tracestate from the parent span context. |
| 2844 |
func RecordingOnly() Sampler { |
| 2845 |
return recordOnlySampler{} |
| 2846 |
} |
| 2847 |
|
| 2848 |
type recordOnlySampler struct{} |
| 2849 |
|
| 2850 |
// ShouldSample implements Sampler interface. It always returns Record but not Sample. |
| 2851 |
func (recordOnlySampler) ShouldSample(p SamplingParameters) SamplingResult { |
| 2852 |
psc := trace.SpanContextFromContext(p.ParentContext) |
| 2853 |
return SamplingResult{ |
| 2854 |
Decision: RecordOnly, |
| 2855 |
Tracestate: psc.TraceState(), |
| 2856 |
} |
| 2857 |
} |
| 2858 |
|
| 2859 |
// Description returns description of the sampler. |
| 2860 |
func (recordOnlySampler) Description() string { |
| 2861 |
return "RecordingOnly" |
| 2862 |
} |
| 2863 |
|
| 2864 |
func TestRecordOnlySampler(t *testing.T) { |
| 2865 |
te := NewTestExporter() |
| 2866 |
tp := NewTracerProvider(WithSyncer(te), WithSampler(RecordingOnly())) |
| 2867 |
|
| 2868 |
_, span := tp.Tracer("RecordOnly").Start(t.Context(), "test-span") |
| 2869 |
|
| 2870 |
assert.True(t, span.IsRecording(), "span should be recording") |
| 2871 |
assert.False(t, span.SpanContext().IsSampled(), "span should not be sampled") |
| 2872 |
|
| 2873 |
span.End() |
| 2874 |
|
| 2875 |
assert.Zero(t, te.Len(), "no spans should be exported") |
| 2876 |
} |
| 2877 |
|
| 2878 |
func BenchmarkTraceStart(b *testing.B) { |
| 2879 |
ctx := trace.ContextWithSpanContext(b.Context(), trace.SpanContext{}) |
| 2880 |
|
| 2881 |
l1 := trace.Link{SpanContext: trace.SpanContext{}, Attributes: []attribute.KeyValue{}} |
| 2882 |
l2 := trace.Link{SpanContext: trace.SpanContext{}, Attributes: []attribute.KeyValue{}} |
| 2883 |
|
| 2884 |
links := []trace.Link{l1, l2} |
| 2885 |
|
| 2886 |
for _, tt := range []struct { |
| 2887 |
name string |
| 2888 |
env map[string]string |
| 2889 |
options []trace.SpanStartOption |
| 2890 |
}{ |
| 2891 |
{ |
| 2892 |
name: "with a simple span", |
| 2893 |
}, |
| 2894 |
{ |
| 2895 |
name: "with several links", |
| 2896 |
options: []trace.SpanStartOption{ |
| 2897 |
trace.WithLinks(links...), |
| 2898 |
}, |
| 2899 |
}, |
| 2900 |
{ |
| 2901 |
name: "with attributes", |
| 2902 |
options: []trace.SpanStartOption{ |
| 2903 |
trace.WithAttributes( |
| 2904 |
attribute.String("key1", "value1"), |
| 2905 |
attribute.String("key2", "value2"), |
| 2906 |
), |
| 2907 |
}, |
| 2908 |
}, |
| 2909 |
{ |
| 2910 |
name: "ObservabilityEnabled", |
| 2911 |
env: map[string]string{ |
| 2912 |
"OTEL_GO_X_OBSERVABILITY": "True", |
| 2913 |
}, |
| 2914 |
}, |
| 2915 |
} { |
| 2916 |
b.Run(tt.name, func(b *testing.B) { |
| 2917 |
for k, v := range tt.env { |
| 2918 |
b.Setenv(k, v) |
| 2919 |
} |
| 2920 |
|
| 2921 |
tracer := NewTracerProvider().Tracer("") |
| 2922 |
|
| 2923 |
spans := make([]trace.Span, b.N) |
| 2924 |
b.ReportAllocs() |
| 2925 |
b.ResetTimer() |
| 2926 |
|
| 2927 |
for i := 0; i < b.N; i++ { |
| 2928 |
_, span := tracer.Start(ctx, "", tt.options...) |
| 2929 |
spans[i] = span |
| 2930 |
} |
| 2931 |
|
| 2932 |
b.StopTimer() |
| 2933 |
for i := 0; i < b.N; i++ { |
| 2934 |
spans[i].End() |
| 2935 |
} |
| 2936 |
}) |
| 2937 |
} |
| 2938 |
} |