1
0
mirror of https://github.com/open-telemetry/opentelemetry-go.git synced 2025-07-13 01:00:22 +02:00

Move tracing code to trace package (#1307)

* Move tracing code to trace package

* Update changelog
This commit is contained in:
Krzesimir Nowak
2020-11-06 23:13:31 +01:00
committed by GitHub
parent 9ac3a08eef
commit 3268501910
58 changed files with 857 additions and 808 deletions

View File

@ -16,7 +16,7 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
### Changed ### Changed
- Move the `go.opentelemetry.io/otel/api/trace` package into `go.opentelemetry.io/otel` with the following changes. (#1229) - Move the `go.opentelemetry.io/otel/api/trace` package into `go.opentelemetry.io/otel/trace` with the following changes. (#1229) (#1307)
- `ID` has been renamed to `TraceID`. - `ID` has been renamed to `TraceID`.
- `IDFromHex` has been renamed to `TraceIDFromHex`. - `IDFromHex` has been renamed to `TraceIDFromHex`.
- `ErrorOption` has been changed to an interface to conform with project design standards which included adding a `NewErrorConfig` function. - `ErrorOption` has been changed to an interface to conform with project design standards which included adding a `NewErrorConfig` function.

View File

@ -32,18 +32,19 @@ import (
"go.opentelemetry.io/otel/internal/trace/noop" "go.opentelemetry.io/otel/internal/trace/noop"
otelparent "go.opentelemetry.io/otel/internal/trace/parent" otelparent "go.opentelemetry.io/otel/internal/trace/parent"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
"go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/otel/bridge/opentracing/migration" "go.opentelemetry.io/otel/bridge/opentracing/migration"
) )
type bridgeSpanContext struct { type bridgeSpanContext struct {
baggageItems baggage.Map baggageItems baggage.Map
otelSpanContext otel.SpanContext otelSpanContext trace.SpanContext
} }
var _ ot.SpanContext = &bridgeSpanContext{} var _ ot.SpanContext = &bridgeSpanContext{}
func newBridgeSpanContext(otelSpanContext otel.SpanContext, parentOtSpanContext ot.SpanContext) *bridgeSpanContext { func newBridgeSpanContext(otelSpanContext trace.SpanContext, parentOtSpanContext ot.SpanContext) *bridgeSpanContext {
bCtx := &bridgeSpanContext{ bCtx := &bridgeSpanContext{
baggageItems: baggage.NewEmptyMap(), baggageItems: baggage.NewEmptyMap(),
otelSpanContext: otelSpanContext, otelSpanContext: otelSpanContext,
@ -75,7 +76,7 @@ func (c *bridgeSpanContext) baggageItem(restrictedKey string) string {
} }
type bridgeSpan struct { type bridgeSpan struct {
otelSpan otel.Span otelSpan trace.Span
ctx *bridgeSpanContext ctx *bridgeSpanContext
tracer *BridgeTracer tracer *BridgeTracer
skipDeferHook bool skipDeferHook bool
@ -84,7 +85,7 @@ type bridgeSpan struct {
var _ ot.Span = &bridgeSpan{} var _ ot.Span = &bridgeSpan{}
func newBridgeSpan(otelSpan otel.Span, bridgeSC *bridgeSpanContext, tracer *BridgeTracer) *bridgeSpan { func newBridgeSpan(otelSpan trace.Span, bridgeSC *bridgeSpanContext, tracer *BridgeTracer) *bridgeSpan {
return &bridgeSpan{ return &bridgeSpan{
otelSpan: otelSpan, otelSpan: otelSpan,
ctx: bridgeSC, ctx: bridgeSC,
@ -99,10 +100,10 @@ func (s *bridgeSpan) Finish() {
} }
func (s *bridgeSpan) FinishWithOptions(opts ot.FinishOptions) { func (s *bridgeSpan) FinishWithOptions(opts ot.FinishOptions) {
var otelOpts []otel.SpanOption var otelOpts []trace.SpanOption
if !opts.FinishTime.IsZero() { if !opts.FinishTime.IsZero() {
otelOpts = append(otelOpts, otel.WithTimestamp(opts.FinishTime)) otelOpts = append(otelOpts, trace.WithTimestamp(opts.FinishTime))
} }
for _, record := range opts.LogRecords { for _, record := range opts.LogRecords {
s.logRecord(record) s.logRecord(record)
@ -116,8 +117,8 @@ func (s *bridgeSpan) FinishWithOptions(opts ot.FinishOptions) {
func (s *bridgeSpan) logRecord(record ot.LogRecord) { func (s *bridgeSpan) logRecord(record ot.LogRecord) {
s.otelSpan.AddEvent( s.otelSpan.AddEvent(
"", "",
otel.WithTimestamp(record.Timestamp), trace.WithTimestamp(record.Timestamp),
otel.WithAttributes(otLogFieldsToOTelLabels(record.Fields)...), trace.WithAttributes(otLogFieldsToOTelLabels(record.Fields)...),
) )
} }
@ -147,7 +148,7 @@ func (s *bridgeSpan) SetTag(key string, value interface{}) ot.Span {
func (s *bridgeSpan) LogFields(fields ...otlog.Field) { func (s *bridgeSpan) LogFields(fields ...otlog.Field) {
s.otelSpan.AddEvent( s.otelSpan.AddEvent(
"", "",
otel.WithAttributes(otLogFieldsToOTelLabels(fields)...), trace.WithAttributes(otLogFieldsToOTelLabels(fields)...),
) )
} }
@ -265,13 +266,13 @@ func (s *bridgeSpan) Log(data ot.LogData) {
type bridgeSetTracer struct { type bridgeSetTracer struct {
isSet bool isSet bool
otelTracer otel.Tracer otelTracer trace.Tracer
warningHandler BridgeWarningHandler warningHandler BridgeWarningHandler
warnOnce sync.Once warnOnce sync.Once
} }
func (s *bridgeSetTracer) tracer() otel.Tracer { func (s *bridgeSetTracer) tracer() trace.Tracer {
if !s.isSet { if !s.isSet {
s.warnOnce.Do(func() { s.warnOnce.Do(func() {
s.warningHandler("The OpenTelemetry tracer is not set, default no-op tracer is used! Call SetOpenTelemetryTracer to set it up.\n") s.warningHandler("The OpenTelemetry tracer is not set, default no-op tracer is used! Call SetOpenTelemetryTracer to set it up.\n")
@ -323,7 +324,7 @@ func (t *BridgeTracer) SetWarningHandler(handler BridgeWarningHandler) {
// SetWarningHandler overrides the underlying OpenTelemetry // SetWarningHandler overrides the underlying OpenTelemetry
// tracer. The passed tracer should know how to operate in the // tracer. The passed tracer should know how to operate in the
// environment that uses OpenTracing API. // environment that uses OpenTracing API.
func (t *BridgeTracer) SetOpenTelemetryTracer(tracer otel.Tracer) { func (t *BridgeTracer) SetOpenTelemetryTracer(tracer trace.Tracer) {
t.setTracer.otelTracer = tracer t.setTracer.otelTracer = tracer
t.setTracer.isSet = true t.setTracer.isSet = true
} }
@ -394,16 +395,16 @@ func (t *BridgeTracer) StartSpan(operationName string, opts ...ot.StartSpanOptio
attributes, kind, hadTrueErrorTag := otTagsToOTelAttributesKindAndError(sso.Tags) attributes, kind, hadTrueErrorTag := otTagsToOTelAttributesKindAndError(sso.Tags)
checkCtx := migration.WithDeferredSetup(context.Background()) checkCtx := migration.WithDeferredSetup(context.Background())
if parentBridgeSC != nil { if parentBridgeSC != nil {
checkCtx = otel.ContextWithRemoteSpanContext(checkCtx, parentBridgeSC.otelSpanContext) checkCtx = trace.ContextWithRemoteSpanContext(checkCtx, parentBridgeSC.otelSpanContext)
} }
checkCtx2, otelSpan := t.setTracer.tracer().Start( checkCtx2, otelSpan := t.setTracer.tracer().Start(
checkCtx, checkCtx,
operationName, operationName,
otel.WithAttributes(attributes...), trace.WithAttributes(attributes...),
otel.WithTimestamp(sso.StartTime), trace.WithTimestamp(sso.StartTime),
otel.WithLinks(links...), trace.WithLinks(links...),
otel.WithRecord(), trace.WithRecord(),
otel.WithSpanKind(kind), trace.WithSpanKind(kind),
) )
if checkCtx != checkCtx2 { if checkCtx != checkCtx2 {
t.warnOnce.Do(func() { t.warnOnce.Do(func() {
@ -435,7 +436,7 @@ func (t *BridgeTracer) StartSpan(operationName string, opts ...ot.StartSpanOptio
// This function should be used by the OpenTelemetry tracers that want // This function should be used by the OpenTelemetry tracers that want
// to be aware how to operate in the environment using OpenTracing // to be aware how to operate in the environment using OpenTracing
// API. // API.
func (t *BridgeTracer) ContextWithBridgeSpan(ctx context.Context, span otel.Span) context.Context { func (t *BridgeTracer) ContextWithBridgeSpan(ctx context.Context, span trace.Span) context.Context {
var otSpanContext ot.SpanContext var otSpanContext ot.SpanContext
if parentSpan := ot.SpanFromContext(ctx); parentSpan != nil { if parentSpan := ot.SpanFromContext(ctx); parentSpan != nil {
otSpanContext = parentSpan.Context() otSpanContext = parentSpan.Context()
@ -465,8 +466,8 @@ func (t *BridgeTracer) ContextWithSpanHook(ctx context.Context, span ot.Span) co
return ctx return ctx
} }
func otTagsToOTelAttributesKindAndError(tags map[string]interface{}) ([]label.KeyValue, otel.SpanKind, bool) { func otTagsToOTelAttributesKindAndError(tags map[string]interface{}) ([]label.KeyValue, trace.SpanKind, bool) {
kind := otel.SpanKindInternal kind := trace.SpanKindInternal
err := false err := false
var pairs []label.KeyValue var pairs []label.KeyValue
for k, v := range tags { for k, v := range tags {
@ -475,13 +476,13 @@ func otTagsToOTelAttributesKindAndError(tags map[string]interface{}) ([]label.Ke
if s, ok := v.(string); ok { if s, ok := v.(string); ok {
switch strings.ToLower(s) { switch strings.ToLower(s) {
case "client": case "client":
kind = otel.SpanKindClient kind = trace.SpanKindClient
case "server": case "server":
kind = otel.SpanKindServer kind = trace.SpanKindServer
case "producer": case "producer":
kind = otel.SpanKindProducer kind = trace.SpanKindProducer
case "consumer": case "consumer":
kind = otel.SpanKindConsumer kind = trace.SpanKindConsumer
} }
} }
case string(otext.Error): case string(otext.Error):
@ -527,10 +528,10 @@ func otTagToOTelLabelKey(k string) label.Key {
return label.Key(k) return label.Key(k)
} }
func otSpanReferencesToParentAndLinks(references []ot.SpanReference) (*bridgeSpanContext, []otel.Link) { func otSpanReferencesToParentAndLinks(references []ot.SpanReference) (*bridgeSpanContext, []trace.Link) {
var ( var (
parent *bridgeSpanContext parent *bridgeSpanContext
links []otel.Link links []trace.Link
) )
for _, reference := range references { for _, reference := range references {
bridgeSC, ok := reference.ReferencedContext.(*bridgeSpanContext) bridgeSC, ok := reference.ReferencedContext.(*bridgeSpanContext)
@ -556,8 +557,8 @@ func otSpanReferencesToParentAndLinks(references []ot.SpanReference) (*bridgeSpa
return parent, links return parent, links
} }
func otSpanReferenceToOTelLink(bridgeSC *bridgeSpanContext, refType ot.SpanReferenceType) otel.Link { func otSpanReferenceToOTelLink(bridgeSC *bridgeSpanContext, refType ot.SpanReferenceType) trace.Link {
return otel.Link{ return trace.Link{
SpanContext: bridgeSC.otelSpanContext, SpanContext: bridgeSC.otelSpanContext,
Attributes: otSpanReferenceTypeToOTelLinkAttributes(refType), Attributes: otSpanReferenceTypeToOTelLinkAttributes(refType),
} }
@ -586,11 +587,11 @@ func otSpanReferenceTypeToString(refType ot.SpanReferenceType) string {
// fakeSpan is just a holder of span context, nothing more. It's for // fakeSpan is just a holder of span context, nothing more. It's for
// propagators, so they can get the span context from Go context. // propagators, so they can get the span context from Go context.
type fakeSpan struct { type fakeSpan struct {
otel.Span trace.Span
sc otel.SpanContext sc trace.SpanContext
} }
func (s fakeSpan) SpanContext() otel.SpanContext { func (s fakeSpan) SpanContext() trace.SpanContext {
return s.sc return s.sc
} }
@ -618,7 +619,7 @@ func (t *BridgeTracer) Inject(sm ot.SpanContext, format interface{}, carrier int
Span: noop.Span, Span: noop.Span,
sc: bridgeSC.otelSpanContext, sc: bridgeSC.otelSpanContext,
} }
ctx := otel.ContextWithSpan(context.Background(), fs) ctx := trace.ContextWithSpan(context.Background(), fs)
ctx = baggage.ContextWithMap(ctx, bridgeSC.baggageItems) ctx = baggage.ContextWithMap(ctx, bridgeSC.baggageItems)
t.getPropagator().Inject(ctx, header) t.getPropagator().Inject(ctx, header)
return nil return nil

View File

@ -21,11 +21,11 @@ import (
"sync" "sync"
"time" "time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/internal/baggage" "go.opentelemetry.io/otel/internal/baggage"
otelparent "go.opentelemetry.io/otel/internal/trace/parent" otelparent "go.opentelemetry.io/otel/internal/trace/parent"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
"go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/otel/bridge/opentracing/migration" "go.opentelemetry.io/otel/bridge/opentracing/migration"
) )
@ -47,15 +47,15 @@ type MockContextKeyValue struct {
type MockTracer struct { type MockTracer struct {
Resources baggage.Map Resources baggage.Map
FinishedSpans []*MockSpan FinishedSpans []*MockSpan
SpareTraceIDs []otel.TraceID SpareTraceIDs []trace.TraceID
SpareSpanIDs []otel.SpanID SpareSpanIDs []trace.SpanID
SpareContextKeyValues []MockContextKeyValue SpareContextKeyValues []MockContextKeyValue
randLock sync.Mutex randLock sync.Mutex
rand *rand.Rand rand *rand.Rand
} }
var _ otel.Tracer = &MockTracer{} var _ trace.Tracer = &MockTracer{}
var _ migration.DeferredContextSetupTracerExtension = &MockTracer{} var _ migration.DeferredContextSetupTracerExtension = &MockTracer{}
func NewMockTracer() *MockTracer { func NewMockTracer() *MockTracer {
@ -70,13 +70,13 @@ func NewMockTracer() *MockTracer {
} }
} }
func (t *MockTracer) Start(ctx context.Context, name string, opts ...otel.SpanOption) (context.Context, otel.Span) { func (t *MockTracer) Start(ctx context.Context, name string, opts ...trace.SpanOption) (context.Context, trace.Span) {
config := otel.NewSpanConfig(opts...) config := trace.NewSpanConfig(opts...)
startTime := config.Timestamp startTime := config.Timestamp
if startTime.IsZero() { if startTime.IsZero() {
startTime = time.Now() startTime = time.Now()
} }
spanContext := otel.SpanContext{ spanContext := trace.SpanContext{
TraceID: t.getTraceID(ctx, config), TraceID: t.getTraceID(ctx, config),
SpanID: t.getSpanID(), SpanID: t.getSpanID(),
TraceFlags: 0, TraceFlags: 0,
@ -93,10 +93,10 @@ func (t *MockTracer) Start(ctx context.Context, name string, opts ...otel.SpanOp
EndTime: time.Time{}, EndTime: time.Time{},
ParentSpanID: t.getParentSpanID(ctx, config), ParentSpanID: t.getParentSpanID(ctx, config),
Events: nil, Events: nil,
SpanKind: otel.ValidateSpanKind(config.SpanKind), SpanKind: trace.ValidateSpanKind(config.SpanKind),
} }
if !migration.SkipContextSetup(ctx) { if !migration.SkipContextSetup(ctx) {
ctx = otel.ContextWithSpan(ctx, span) ctx = trace.ContextWithSpan(ctx, span)
ctx = t.addSpareContextValue(ctx) ctx = t.addSpareContextValue(ctx)
} }
return ctx, span return ctx, span
@ -115,7 +115,7 @@ func (t *MockTracer) addSpareContextValue(ctx context.Context) context.Context {
return ctx return ctx
} }
func (t *MockTracer) getTraceID(ctx context.Context, config *otel.SpanConfig) otel.TraceID { func (t *MockTracer) getTraceID(ctx context.Context, config *trace.SpanConfig) trace.TraceID {
if parent := t.getParentSpanContext(ctx, config); parent.IsValid() { if parent := t.getParentSpanContext(ctx, config); parent.IsValid() {
return parent.TraceID return parent.TraceID
} }
@ -130,19 +130,19 @@ func (t *MockTracer) getTraceID(ctx context.Context, config *otel.SpanConfig) ot
return t.getRandTraceID() return t.getRandTraceID()
} }
func (t *MockTracer) getParentSpanID(ctx context.Context, config *otel.SpanConfig) otel.SpanID { func (t *MockTracer) getParentSpanID(ctx context.Context, config *trace.SpanConfig) trace.SpanID {
if parent := t.getParentSpanContext(ctx, config); parent.IsValid() { if parent := t.getParentSpanContext(ctx, config); parent.IsValid() {
return parent.SpanID return parent.SpanID
} }
return otel.SpanID{} return trace.SpanID{}
} }
func (t *MockTracer) getParentSpanContext(ctx context.Context, config *otel.SpanConfig) otel.SpanContext { func (t *MockTracer) getParentSpanContext(ctx context.Context, config *trace.SpanConfig) trace.SpanContext {
spanCtx, _, _ := otelparent.GetSpanContextAndLinks(ctx, config.NewRoot) spanCtx, _, _ := otelparent.GetSpanContextAndLinks(ctx, config.NewRoot)
return spanCtx return spanCtx
} }
func (t *MockTracer) getSpanID() otel.SpanID { func (t *MockTracer) getSpanID() trace.SpanID {
if len(t.SpareSpanIDs) > 0 { if len(t.SpareSpanIDs) > 0 {
spanID := t.SpareSpanIDs[0] spanID := t.SpareSpanIDs[0]
t.SpareSpanIDs = t.SpareSpanIDs[1:] t.SpareSpanIDs = t.SpareSpanIDs[1:]
@ -154,27 +154,27 @@ func (t *MockTracer) getSpanID() otel.SpanID {
return t.getRandSpanID() return t.getRandSpanID()
} }
func (t *MockTracer) getRandSpanID() otel.SpanID { func (t *MockTracer) getRandSpanID() trace.SpanID {
t.randLock.Lock() t.randLock.Lock()
defer t.randLock.Unlock() defer t.randLock.Unlock()
sid := otel.SpanID{} sid := trace.SpanID{}
t.rand.Read(sid[:]) t.rand.Read(sid[:])
return sid return sid
} }
func (t *MockTracer) getRandTraceID() otel.TraceID { func (t *MockTracer) getRandTraceID() trace.TraceID {
t.randLock.Lock() t.randLock.Lock()
defer t.randLock.Unlock() defer t.randLock.Unlock()
tid := otel.TraceID{} tid := trace.TraceID{}
t.rand.Read(tid[:]) t.rand.Read(tid[:])
return tid return tid
} }
func (t *MockTracer) DeferredContextSetupHook(ctx context.Context, span otel.Span) context.Context { func (t *MockTracer) DeferredContextSetupHook(ctx context.Context, span trace.Span) context.Context {
return t.addSpareContextValue(ctx) return t.addSpareContextValue(ctx)
} }
@ -186,22 +186,22 @@ type MockEvent struct {
type MockSpan struct { type MockSpan struct {
mockTracer *MockTracer mockTracer *MockTracer
officialTracer otel.Tracer officialTracer trace.Tracer
spanContext otel.SpanContext spanContext trace.SpanContext
SpanKind otel.SpanKind SpanKind trace.SpanKind
recording bool recording bool
Attributes baggage.Map Attributes baggage.Map
StartTime time.Time StartTime time.Time
EndTime time.Time EndTime time.Time
ParentSpanID otel.SpanID ParentSpanID trace.SpanID
Events []MockEvent Events []MockEvent
} }
var _ otel.Span = &MockSpan{} var _ trace.Span = &MockSpan{}
var _ migration.OverrideTracerSpanExtension = &MockSpan{} var _ migration.OverrideTracerSpanExtension = &MockSpan{}
func (s *MockSpan) SpanContext() otel.SpanContext { func (s *MockSpan) SpanContext() trace.SpanContext {
return s.spanContext return s.spanContext
} }
@ -231,11 +231,11 @@ func (s *MockSpan) applyUpdate(update baggage.MapUpdate) {
s.Attributes = s.Attributes.Apply(update) s.Attributes = s.Attributes.Apply(update)
} }
func (s *MockSpan) End(options ...otel.SpanOption) { func (s *MockSpan) End(options ...trace.SpanOption) {
if !s.EndTime.IsZero() { if !s.EndTime.IsZero() {
return // already finished return // already finished
} }
config := otel.NewSpanConfig(options...) config := trace.NewSpanConfig(options...)
endTime := config.Timestamp endTime := config.Timestamp
if endTime.IsZero() { if endTime.IsZero() {
endTime = time.Now() endTime = time.Now()
@ -244,7 +244,7 @@ func (s *MockSpan) End(options ...otel.SpanOption) {
s.mockTracer.FinishedSpans = append(s.mockTracer.FinishedSpans, s) s.mockTracer.FinishedSpans = append(s.mockTracer.FinishedSpans, s)
} }
func (s *MockSpan) RecordError(err error, opts ...otel.EventOption) { func (s *MockSpan) RecordError(err error, opts ...trace.EventOption) {
if err == nil { if err == nil {
return // no-op on nil error return // no-op on nil error
} }
@ -254,19 +254,19 @@ func (s *MockSpan) RecordError(err error, opts ...otel.EventOption) {
} }
s.SetStatus(codes.Error, "") s.SetStatus(codes.Error, "")
opts = append(opts, otel.WithAttributes( opts = append(opts, trace.WithAttributes(
label.String("error.type", reflect.TypeOf(err).String()), label.String("error.type", reflect.TypeOf(err).String()),
label.String("error.message", err.Error()), label.String("error.message", err.Error()),
)) ))
s.AddEvent("error", opts...) s.AddEvent("error", opts...)
} }
func (s *MockSpan) Tracer() otel.Tracer { func (s *MockSpan) Tracer() trace.Tracer {
return s.officialTracer return s.officialTracer
} }
func (s *MockSpan) AddEvent(name string, o ...otel.EventOption) { func (s *MockSpan) AddEvent(name string, o ...trace.EventOption) {
c := otel.NewEventConfig(o...) c := trace.NewEventConfig(o...)
s.Events = append(s.Events, MockEvent{ s.Events = append(s.Events, MockEvent{
Timestamp: c.Timestamp, Timestamp: c.Timestamp,
Name: name, Name: name,
@ -276,6 +276,6 @@ func (s *MockSpan) AddEvent(name string, o ...otel.EventOption) {
}) })
} }
func (s *MockSpan) OverrideTracer(tracer otel.Tracer) { func (s *MockSpan) OverrideTracer(tracer trace.Tracer) {
s.officialTracer = tracer s.officialTracer = tracer
} }

View File

@ -20,7 +20,7 @@ package migration // import "go.opentelemetry.io/otel/bridge/opentracing/migrati
import ( import (
"context" "context"
"go.opentelemetry.io/otel" "go.opentelemetry.io/otel/trace"
) )
// DeferredContextSetupTracerExtension is an interface an // DeferredContextSetupTracerExtension is an interface an
@ -41,7 +41,7 @@ type DeferredContextSetupTracerExtension interface {
// opentracing.ContextWithSpan happens. When bridge // opentracing.ContextWithSpan happens. When bridge
// OpenTracing tracer calls OpenTelemetry tracer's Start() // OpenTracing tracer calls OpenTelemetry tracer's Start()
// function, it passes a context that shouldn't be modified. // function, it passes a context that shouldn't be modified.
DeferredContextSetupHook(ctx context.Context, span otel.Span) context.Context DeferredContextSetupHook(ctx context.Context, span trace.Span) context.Context
} }
// OverrideTracerSpanExtension is an interface an OpenTelemetry span // OverrideTracerSpanExtension is an interface an OpenTelemetry span
@ -56,7 +56,7 @@ type DeferredContextSetupTracerExtension interface {
// OpenTelemetry Span object and have WrapperTracer to alter the // OpenTelemetry Span object and have WrapperTracer to alter the
// current OpenTelemetry span in the context so it points to the // current OpenTelemetry span in the context so it points to the
// wrapped object, so the code in the tracer like // wrapped object, so the code in the tracer like
// `otel.SpanFromContent().(*realSpan)` would still work. Another // `trace.SpanFromContent().(*realSpan)` would still work. Another
// argument for getting rid of this interface is that is only called // argument for getting rid of this interface is that is only called
// by the WrapperTracer - WrapperTracer likely shouldn't require any // by the WrapperTracer - WrapperTracer likely shouldn't require any
// changes in the underlying OpenTelemetry tracer to have things // changes in the underlying OpenTelemetry tracer to have things
@ -72,5 +72,5 @@ type OverrideTracerSpanExtension interface {
// API calls. In such case, there is no need to use the // API calls. In such case, there is no need to use the
// WrapperTracer and thus no need to override the result of // WrapperTracer and thus no need to override the result of
// the Tracer() function. // the Tracer() function.
OverrideTracer(tracer otel.Tracer) OverrideTracer(tracer trace.Tracer)
} }

View File

@ -21,10 +21,10 @@ import (
ot "github.com/opentracing/opentracing-go" ot "github.com/opentracing/opentracing-go"
"go.opentelemetry.io/otel"
otelglobal "go.opentelemetry.io/otel/global" otelglobal "go.opentelemetry.io/otel/global"
otelbaggage "go.opentelemetry.io/otel/internal/baggage" otelbaggage "go.opentelemetry.io/otel/internal/baggage"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
"go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/otel/bridge/opentracing/internal" "go.opentelemetry.io/otel/bridge/opentracing/internal"
) )
@ -142,8 +142,8 @@ func TestMixedAPIs(t *testing.T) {
// simple test // simple test
type simpleTest struct { type simpleTest struct {
traceID otel.TraceID traceID trace.TraceID
spanIDs []otel.SpanID spanIDs []trace.SpanID
} }
func newSimpleTest() *simpleTest { func newSimpleTest() *simpleTest {
@ -177,11 +177,11 @@ func (st *simpleTest) noop(t *testing.T, ctx context.Context) context.Context {
// current/active span test // current/active span test
type currentActiveSpanTest struct { type currentActiveSpanTest struct {
traceID otel.TraceID traceID trace.TraceID
spanIDs []otel.SpanID spanIDs []trace.SpanID
recordedCurrentOtelSpanIDs []otel.SpanID recordedCurrentOtelSpanIDs []trace.SpanID
recordedActiveOTSpanIDs []otel.SpanID recordedActiveOTSpanIDs []trace.SpanID
} }
func newCurrentActiveSpanTest() *currentActiveSpanTest { func newCurrentActiveSpanTest() *currentActiveSpanTest {
@ -229,10 +229,10 @@ func (cast *currentActiveSpanTest) runOTOtelOT(t *testing.T, ctx context.Context
} }
func (cast *currentActiveSpanTest) recordSpans(t *testing.T, ctx context.Context) context.Context { func (cast *currentActiveSpanTest) recordSpans(t *testing.T, ctx context.Context) context.Context {
spanID := otel.SpanContextFromContext(ctx).SpanID spanID := trace.SpanContextFromContext(ctx).SpanID
cast.recordedCurrentOtelSpanIDs = append(cast.recordedCurrentOtelSpanIDs, spanID) cast.recordedCurrentOtelSpanIDs = append(cast.recordedCurrentOtelSpanIDs, spanID)
spanID = otel.SpanID{} spanID = trace.SpanID{}
if bridgeSpan, ok := ot.SpanFromContext(ctx).(*bridgeSpan); ok { if bridgeSpan, ok := ot.SpanFromContext(ctx).(*bridgeSpan); ok {
spanID = bridgeSpan.otelSpan.SpanContext().SpanID spanID = bridgeSpan.otelSpan.SpanContext().SpanID
} }
@ -423,7 +423,7 @@ func (bip *baggageItemsPreservationTest) addAndRecordBaggage(t *testing.T, ctx c
type tracerMessTest struct { type tracerMessTest struct {
recordedOTSpanTracers []ot.Tracer recordedOTSpanTracers []ot.Tracer
recordedOtelSpanTracers []otel.Tracer recordedOtelSpanTracers []trace.Tracer
} }
func newTracerMessTest() *tracerMessTest { func newTracerMessTest() *tracerMessTest {
@ -475,7 +475,7 @@ func (tm *tracerMessTest) recordTracers(t *testing.T, ctx context.Context) conte
tm.recordedOTSpanTracers = append(tm.recordedOTSpanTracers, otSpan.Tracer()) tm.recordedOTSpanTracers = append(tm.recordedOTSpanTracers, otSpan.Tracer())
} }
otelSpan := otel.SpanFromContext(ctx) otelSpan := trace.SpanFromContext(ctx)
tm.recordedOtelSpanTracers = append(tm.recordedOtelSpanTracers, otelSpan.Tracer()) tm.recordedOtelSpanTracers = append(tm.recordedOtelSpanTracers, otelSpan.Tracer())
return ctx return ctx
} }
@ -613,23 +613,23 @@ func generateBaggageKeys(key string) (otKey, otelKey string) {
// helpers // helpers
func checkTraceAndSpans(t *testing.T, tracer *internal.MockTracer, expectedTraceID otel.TraceID, expectedSpanIDs []otel.SpanID) { func checkTraceAndSpans(t *testing.T, tracer *internal.MockTracer, expectedTraceID trace.TraceID, expectedSpanIDs []trace.SpanID) {
expectedSpanCount := len(expectedSpanIDs) expectedSpanCount := len(expectedSpanIDs)
// reverse spanIDs, since first span ID belongs to root, that // reverse spanIDs, since first span ID belongs to root, that
// finishes last // finishes last
spanIDs := make([]otel.SpanID, len(expectedSpanIDs)) spanIDs := make([]trace.SpanID, len(expectedSpanIDs))
copy(spanIDs, expectedSpanIDs) copy(spanIDs, expectedSpanIDs)
reverse(len(spanIDs), func(i, j int) { reverse(len(spanIDs), func(i, j int) {
spanIDs[i], spanIDs[j] = spanIDs[j], spanIDs[i] spanIDs[i], spanIDs[j] = spanIDs[j], spanIDs[i]
}) })
// the last finished span has no parent // the last finished span has no parent
parentSpanIDs := append(spanIDs[1:], otel.SpanID{}) parentSpanIDs := append(spanIDs[1:], trace.SpanID{})
sks := map[otel.SpanID]otel.SpanKind{ sks := map[trace.SpanID]trace.SpanKind{
{125}: otel.SpanKindProducer, {125}: trace.SpanKindProducer,
{124}: otel.SpanKindInternal, {124}: trace.SpanKindInternal,
{123}: otel.SpanKindClient, {123}: trace.SpanKindClient,
} }
if len(tracer.FinishedSpans) != expectedSpanCount { if len(tracer.FinishedSpans) != expectedSpanCount {
@ -660,12 +660,12 @@ func reverse(length int, swap func(i, j int)) {
} }
} }
func simpleTraceID() otel.TraceID { func simpleTraceID() trace.TraceID {
return [16]byte{123, 42} return [16]byte{123, 42}
} }
func simpleSpanIDs(count int) []otel.SpanID { func simpleSpanIDs(count int) []trace.SpanID {
base := []otel.SpanID{ base := []trace.SpanID{
{123}, {123},
{124}, {124},
{125}, {125},
@ -685,7 +685,7 @@ func min(a, b int) int {
func runOtelOTOtel(t *testing.T, ctx context.Context, name string, callback func(*testing.T, context.Context) context.Context) { func runOtelOTOtel(t *testing.T, ctx context.Context, name string, callback func(*testing.T, context.Context) context.Context) {
tr := otelglobal.Tracer("") tr := otelglobal.Tracer("")
ctx, span := tr.Start(ctx, fmt.Sprintf("%s_Otel_OTOtel", name), otel.WithSpanKind(otel.SpanKindClient)) ctx, span := tr.Start(ctx, fmt.Sprintf("%s_Otel_OTOtel", name), trace.WithSpanKind(trace.SpanKindClient))
defer span.End() defer span.End()
ctx = callback(t, ctx) ctx = callback(t, ctx)
func(ctx2 context.Context) { func(ctx2 context.Context) {
@ -693,7 +693,7 @@ func runOtelOTOtel(t *testing.T, ctx context.Context, name string, callback func
defer span.Finish() defer span.Finish()
ctx2 = callback(t, ctx2) ctx2 = callback(t, ctx2)
func(ctx3 context.Context) { func(ctx3 context.Context) {
ctx3, span := tr.Start(ctx3, fmt.Sprintf("%sOtelOT_Otel_", name), otel.WithSpanKind(otel.SpanKindProducer)) ctx3, span := tr.Start(ctx3, fmt.Sprintf("%sOtelOT_Otel_", name), trace.WithSpanKind(trace.SpanKindProducer))
defer span.End() defer span.End()
_ = callback(t, ctx3) _ = callback(t, ctx3)
}(ctx2) }(ctx2)

View File

@ -17,7 +17,7 @@ package opentracing // import "go.opentelemetry.io/otel/bridge/opentracing"
import ( import (
"context" "context"
"go.opentelemetry.io/otel" "go.opentelemetry.io/otel/trace"
) )
// NewTracerPair is a utility function that creates a BridgeTracer and a // NewTracerPair is a utility function that creates a BridgeTracer and a
@ -26,14 +26,14 @@ import (
// that wraps the passed tracer. BridgeTracer and WrapperTracerProvider are // that wraps the passed tracer. BridgeTracer and WrapperTracerProvider are
// returned to the caller and the caller is expected to register BridgeTracer // returned to the caller and the caller is expected to register BridgeTracer
// with opentracing and WrapperTracerProvider with opentelemetry. // with opentracing and WrapperTracerProvider with opentelemetry.
func NewTracerPair(tracer otel.Tracer) (*BridgeTracer, *WrapperTracerProvider) { func NewTracerPair(tracer trace.Tracer) (*BridgeTracer, *WrapperTracerProvider) {
bridgeTracer := NewBridgeTracer() bridgeTracer := NewBridgeTracer()
wrapperProvider := NewWrappedTracerProvider(bridgeTracer, tracer) wrapperProvider := NewWrappedTracerProvider(bridgeTracer, tracer)
bridgeTracer.SetOpenTelemetryTracer(wrapperProvider.Tracer("")) bridgeTracer.SetOpenTelemetryTracer(wrapperProvider.Tracer(""))
return bridgeTracer, wrapperProvider return bridgeTracer, wrapperProvider
} }
func NewTracerPairWithContext(ctx context.Context, tracer otel.Tracer) (context.Context, *BridgeTracer, *WrapperTracerProvider) { func NewTracerPairWithContext(ctx context.Context, tracer trace.Tracer) (context.Context, *BridgeTracer, *WrapperTracerProvider) {
bridgeTracer, wrapperProvider := NewTracerPair(tracer) bridgeTracer, wrapperProvider := NewTracerPair(tracer)
ctx = bridgeTracer.NewHookedContext(ctx) ctx = bridgeTracer.NewHookedContext(ctx)
return ctx, bridgeTracer, wrapperProvider return ctx, bridgeTracer, wrapperProvider

View File

@ -17,7 +17,8 @@ package opentracing // import "go.opentelemetry.io/otel/bridge/opentracing"
import ( import (
"context" "context"
"go.opentelemetry.io/otel" "go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/otel/bridge/opentracing/migration" "go.opentelemetry.io/otel/bridge/opentracing/migration"
) )
@ -25,16 +26,16 @@ type WrapperTracerProvider struct {
wTracer *WrapperTracer wTracer *WrapperTracer
} }
var _ otel.TracerProvider = (*WrapperTracerProvider)(nil) var _ trace.TracerProvider = (*WrapperTracerProvider)(nil)
// Tracer returns the WrapperTracer associated with the WrapperTracerProvider. // Tracer returns the WrapperTracer associated with the WrapperTracerProvider.
func (p *WrapperTracerProvider) Tracer(_ string, _ ...otel.TracerOption) otel.Tracer { func (p *WrapperTracerProvider) Tracer(_ string, _ ...trace.TracerOption) trace.Tracer {
return p.wTracer return p.wTracer
} }
// NewWrappedTracerProvider creates a new trace provider that creates a single // NewWrappedTracerProvider creates a new trace provider that creates a single
// instance of WrapperTracer that wraps OpenTelemetry tracer. // instance of WrapperTracer that wraps OpenTelemetry tracer.
func NewWrappedTracerProvider(bridge *BridgeTracer, tracer otel.Tracer) *WrapperTracerProvider { func NewWrappedTracerProvider(bridge *BridgeTracer, tracer trace.Tracer) *WrapperTracerProvider {
return &WrapperTracerProvider{ return &WrapperTracerProvider{
wTracer: NewWrapperTracer(bridge, tracer), wTracer: NewWrapperTracer(bridge, tracer),
} }
@ -50,30 +51,30 @@ func NewWrappedTracerProvider(bridge *BridgeTracer, tracer otel.Tracer) *Wrapper
// used. // used.
type WrapperTracer struct { type WrapperTracer struct {
bridge *BridgeTracer bridge *BridgeTracer
tracer otel.Tracer tracer trace.Tracer
} }
var _ otel.Tracer = &WrapperTracer{} var _ trace.Tracer = &WrapperTracer{}
var _ migration.DeferredContextSetupTracerExtension = &WrapperTracer{} var _ migration.DeferredContextSetupTracerExtension = &WrapperTracer{}
// NewWrapperTracer wraps the passed tracer and also talks to the // NewWrapperTracer wraps the passed tracer and also talks to the
// passed bridge tracer when setting up the context with the new // passed bridge tracer when setting up the context with the new
// active OpenTracing span. // active OpenTracing span.
func NewWrapperTracer(bridge *BridgeTracer, tracer otel.Tracer) *WrapperTracer { func NewWrapperTracer(bridge *BridgeTracer, tracer trace.Tracer) *WrapperTracer {
return &WrapperTracer{ return &WrapperTracer{
bridge: bridge, bridge: bridge,
tracer: tracer, tracer: tracer,
} }
} }
func (t *WrapperTracer) otelTracer() otel.Tracer { func (t *WrapperTracer) otelTracer() trace.Tracer {
return t.tracer return t.tracer
} }
// Start forwards the call to the wrapped tracer. It also tries to // Start forwards the call to the wrapped tracer. It also tries to
// override the tracer of the returned span if the span implements the // override the tracer of the returned span if the span implements the
// OverrideTracerSpanExtension interface. // OverrideTracerSpanExtension interface.
func (t *WrapperTracer) Start(ctx context.Context, name string, opts ...otel.SpanOption) (context.Context, otel.Span) { func (t *WrapperTracer) Start(ctx context.Context, name string, opts ...trace.SpanOption) (context.Context, trace.Span) {
ctx, span := t.otelTracer().Start(ctx, name, opts...) ctx, span := t.otelTracer().Start(ctx, name, opts...)
if spanWithExtension, ok := span.(migration.OverrideTracerSpanExtension); ok { if spanWithExtension, ok := span.(migration.OverrideTracerSpanExtension); ok {
spanWithExtension.OverrideTracer(t) spanWithExtension.OverrideTracer(t)
@ -88,10 +89,10 @@ func (t *WrapperTracer) Start(ctx context.Context, name string, opts ...otel.Spa
// DeferredContextSetupTracerExtension interface. It will try to // DeferredContextSetupTracerExtension interface. It will try to
// forward the call to the wrapped tracer if it implements the // forward the call to the wrapped tracer if it implements the
// interface. // interface.
func (t *WrapperTracer) DeferredContextSetupHook(ctx context.Context, span otel.Span) context.Context { func (t *WrapperTracer) DeferredContextSetupHook(ctx context.Context, span trace.Span) context.Context {
if tracerWithExtension, ok := t.otelTracer().(migration.DeferredContextSetupTracerExtension); ok { if tracerWithExtension, ok := t.otelTracer().(migration.DeferredContextSetupTracerExtension); ok {
ctx = tracerWithExtension.DeferredContextSetupHook(ctx, span) ctx = tracerWithExtension.DeferredContextSetupHook(ctx, span)
} }
ctx = otel.ContextWithSpan(ctx, span) ctx = trace.ContextWithSpan(ctx, span)
return ctx return ctx
} }

166
config.go
View File

@ -15,170 +15,9 @@
package otel // import "go.opentelemetry.io/otel" package otel // import "go.opentelemetry.io/otel"
import ( import (
"time"
"go.opentelemetry.io/otel/label"
"go.opentelemetry.io/otel/unit" "go.opentelemetry.io/otel/unit"
) )
// TracerConfig is a group of options for a Tracer.
type TracerConfig struct {
// InstrumentationVersion is the version of the library providing
// instrumentation.
InstrumentationVersion string
}
// NewTracerConfig applies all the options to a returned TracerConfig.
func NewTracerConfig(options ...TracerOption) *TracerConfig {
config := new(TracerConfig)
for _, option := range options {
option.ApplyTracer(config)
}
return config
}
// TracerOption applies an option to a TracerConfig.
type TracerOption interface {
ApplyTracer(*TracerConfig)
}
// SpanConfig is a group of options for a Span.
type SpanConfig struct {
// Attributes describe the associated qualities of a Span.
Attributes []label.KeyValue
// Timestamp is a time in a Span life-cycle.
Timestamp time.Time
// Links are the associations a Span has with other Spans.
Links []Link
// Record is the recording state of a Span.
Record bool
// NewRoot identifies a Span as the root Span for a new trace. This is
// commonly used when an existing trace crosses trust boundaries and the
// remote parent span context should be ignored for security.
NewRoot bool
// SpanKind is the role a Span has in a trace.
SpanKind SpanKind
}
// NewSpanConfig applies all the options to a returned SpanConfig.
// No validation is performed on the returned SpanConfig (e.g. no uniqueness
// checking or bounding of data), it is left to the SDK to perform this
// action.
func NewSpanConfig(options ...SpanOption) *SpanConfig {
c := new(SpanConfig)
for _, option := range options {
option.ApplySpan(c)
}
return c
}
// SpanOption applies an option to a SpanConfig.
type SpanOption interface {
ApplySpan(*SpanConfig)
}
// NewEventConfig applies all the EventOptions to a returned SpanConfig. If no
// timestamp option is passed, the returned SpanConfig will have a Timestamp
// set to the call time, otherwise no validation is performed on the returned
// SpanConfig.
func NewEventConfig(options ...EventOption) *SpanConfig {
c := new(SpanConfig)
for _, option := range options {
option.ApplyEvent(c)
}
if c.Timestamp.IsZero() {
c.Timestamp = time.Now()
}
return c
}
// EventOption applies span event options to a SpanConfig.
type EventOption interface {
ApplyEvent(*SpanConfig)
}
// LifeCycleOption applies span life-cycle options to a SpanConfig. These
// options set values releated to events in a spans life-cycle like starting,
// ending, experiencing an error and other user defined notable events.
type LifeCycleOption interface {
SpanOption
EventOption
}
type attributeSpanOption []label.KeyValue
func (o attributeSpanOption) ApplySpan(c *SpanConfig) { o.apply(c) }
func (o attributeSpanOption) ApplyEvent(c *SpanConfig) { o.apply(c) }
func (o attributeSpanOption) apply(c *SpanConfig) {
c.Attributes = append(c.Attributes, []label.KeyValue(o)...)
}
// WithAttributes adds the attributes related to a span life-cycle event.
// These attributes are used to describe the work a Span represents when this
// option is provided to a Span's start or end events. Otherwise, these
// attributes provide additional information about the event being recorded
// (e.g. error, state change, processing progress, system event).
//
// If multiple of these options are passed the attributes of each successive
// option will extend the attributes instead of overwriting. There is no
// guarantee of uniqueness in the resulting attributes.
func WithAttributes(attributes ...label.KeyValue) LifeCycleOption {
return attributeSpanOption(attributes)
}
type timestampSpanOption time.Time
func (o timestampSpanOption) ApplySpan(c *SpanConfig) { o.apply(c) }
func (o timestampSpanOption) ApplyEvent(c *SpanConfig) { o.apply(c) }
func (o timestampSpanOption) apply(c *SpanConfig) { c.Timestamp = time.Time(o) }
// WithTimestamp sets the time of a Span life-cycle moment (e.g. started,
// stopped, errored).
func WithTimestamp(t time.Time) LifeCycleOption {
return timestampSpanOption(t)
}
type linksSpanOption []Link
func (o linksSpanOption) ApplySpan(c *SpanConfig) { c.Links = append(c.Links, []Link(o)...) }
// WithLinks adds links to a Span. The links are added to the existing Span
// links, i.e. this does not overwrite.
func WithLinks(links ...Link) SpanOption {
return linksSpanOption(links)
}
type recordSpanOption bool
func (o recordSpanOption) ApplySpan(c *SpanConfig) { c.Record = bool(o) }
// WithRecord specifies that the span should be recorded. It is important to
// note that implementations may override this option, i.e. if the span is a
// child of an un-sampled trace.
func WithRecord() SpanOption {
return recordSpanOption(true)
}
type newRootSpanOption bool
func (o newRootSpanOption) ApplySpan(c *SpanConfig) { c.NewRoot = bool(o) }
// WithNewRoot specifies that the Span should be treated as a root Span. Any
// existing parent span context will be ignored when defining the Span's trace
// identifiers.
func WithNewRoot() SpanOption {
return newRootSpanOption(true)
}
type spanKindSpanOption SpanKind
func (o spanKindSpanOption) ApplySpan(c *SpanConfig) { c.SpanKind = SpanKind(o) }
// WithSpanKind sets the SpanKind of a Span.
func WithSpanKind(kind SpanKind) SpanOption {
return spanKindSpanOption(kind)
}
// InstrumentConfig contains options for metric instrument descriptors. // InstrumentConfig contains options for metric instrument descriptors.
type InstrumentConfig struct { type InstrumentConfig struct {
// Description describes the instrument in human-readable terms. // Description describes the instrument in human-readable terms.
@ -271,7 +110,6 @@ func NewMeterConfig(opts ...MeterOption) MeterConfig {
type InstrumentationOption interface { type InstrumentationOption interface {
InstrumentOption InstrumentOption
MeterOption MeterOption
TracerOption
} }
// WithInstrumentationVersion sets the instrumentation version. // WithInstrumentationVersion sets the instrumentation version.
@ -288,7 +126,3 @@ func (i instrumentationVersionOption) ApplyMeter(config *MeterConfig) {
func (i instrumentationVersionOption) ApplyInstrument(config *InstrumentConfig) { func (i instrumentationVersionOption) ApplyInstrument(config *InstrumentConfig) {
config.InstrumentationVersion = string(i) config.InstrumentationVersion = string(i)
} }
func (i instrumentationVersionOption) ApplyTracer(config *TracerConfig) {
config.InstrumentationVersion = string(i)
}

View File

@ -27,6 +27,7 @@ import (
"go.opentelemetry.io/otel/sdk/metric/processor/basic" "go.opentelemetry.io/otel/sdk/metric/processor/basic"
"go.opentelemetry.io/otel/sdk/metric/selector/simple" "go.opentelemetry.io/otel/sdk/metric/selector/simple"
sdktrace "go.opentelemetry.io/otel/sdk/trace" sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/trace"
) )
var ( var (
@ -83,11 +84,11 @@ func main() {
defer valuerecorder.Unbind() defer valuerecorder.Unbind()
err = func(ctx context.Context) error { err = func(ctx context.Context) error {
var span otel.Span var span trace.Span
ctx, span = tracer.Start(ctx, "operation") ctx, span = tracer.Start(ctx, "operation")
defer span.End() defer span.End()
span.AddEvent("Nice operation!", otel.WithAttributes(label.Int("bogons", 100))) span.AddEvent("Nice operation!", trace.WithAttributes(label.Int("bogons", 100)))
span.SetAttributes(anotherKey.String("yes")) span.SetAttributes(anotherKey.String("yes"))
meter.RecordBatch( meter.RecordBatch(
@ -99,7 +100,7 @@ func main() {
) )
return func(ctx context.Context) error { return func(ctx context.Context) error {
var span otel.Span var span trace.Span
ctx, span = tracer.Start(ctx, "Sub operation...") ctx, span = tracer.Start(ctx, "Sub operation...")
defer span.End() defer span.End()

View File

@ -17,9 +17,9 @@ package foo // import "go.opentelemetry.io/otel/example/namedtracer/foo"
import ( import (
"context" "context"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/global"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
"go.opentelemetry.io/otel/trace"
) )
var ( var (
@ -33,7 +33,7 @@ func SubOperation(ctx context.Context) error {
// for its component to get the instance of the provider. // for its component to get the instance of the provider.
tr := global.Tracer("example/namedtracer/foo") tr := global.Tracer("example/namedtracer/foo")
var span otel.Span var span trace.Span
_, span = tr.Start(ctx, "Sub operation...") _, span = tr.Start(ctx, "Sub operation...")
defer span.End() defer span.End()
span.SetAttributes(lemonsKey.String("five")) span.SetAttributes(lemonsKey.String("five"))

View File

@ -24,6 +24,7 @@ import (
"go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/global"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
sdktrace "go.opentelemetry.io/otel/sdk/trace" sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/trace"
) )
var ( var (
@ -64,10 +65,10 @@ func main() {
defer func() { _ = tp.Shutdown(ctx) }() defer func() { _ = tp.Shutdown(ctx) }()
ctx = otel.ContextWithBaggageValues(ctx, fooKey.String("foo1"), barKey.String("bar1")) ctx = otel.ContextWithBaggageValues(ctx, fooKey.String("foo1"), barKey.String("bar1"))
var span otel.Span var span trace.Span
ctx, span = tracer.Start(ctx, "operation") ctx, span = tracer.Start(ctx, "operation")
defer span.End() defer span.End()
span.AddEvent("Nice operation!", otel.WithAttributes(label.Int("bogons", 100))) span.AddEvent("Nice operation!", trace.WithAttributes(label.Int("bogons", 100)))
span.SetAttributes(anotherKey.String("yes")) span.SetAttributes(anotherKey.String("yes"))
if err := foo.SubOperation(ctx); err != nil { if err := foo.SubOperation(ctx); err != nil {
panic(err) panic(err)

View File

@ -36,6 +36,7 @@ import (
"go.opentelemetry.io/otel/sdk/resource" "go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace" sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/semconv" "go.opentelemetry.io/otel/semconv"
"go.opentelemetry.io/otel/trace"
) )
// Initializes an OTLP exporter, and configures the corresponding trace and // Initializes an OTLP exporter, and configures the corresponding trace and
@ -121,7 +122,7 @@ func main() {
ctx, span := tracer.Start( ctx, span := tracer.Start(
context.Background(), context.Background(),
"CollectorExporter-Example", "CollectorExporter-Example",
otel.WithAttributes(commonLabels...)) trace.WithAttributes(commonLabels...))
defer span.End() defer span.End()
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
_, iSpan := tracer.Start(ctx, fmt.Sprintf("Sample-%d", i)) _, iSpan := tracer.Start(ctx, fmt.Sprintf("Sample-%d", i))

View File

@ -15,13 +15,13 @@
package transform package transform
import ( import (
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
tracepb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/trace/v1" tracepb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/trace/v1"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
export "go.opentelemetry.io/otel/sdk/export/trace" export "go.opentelemetry.io/otel/sdk/export/trace"
"go.opentelemetry.io/otel/sdk/instrumentation" "go.opentelemetry.io/otel/sdk/instrumentation"
"go.opentelemetry.io/otel/trace"
) )
const ( const (
@ -140,7 +140,7 @@ func status(status codes.Code, message string) *tracepb.Status {
} }
// links transforms span Links to OTLP span links. // links transforms span Links to OTLP span links.
func links(links []otel.Link) []*tracepb.Span_Link { func links(links []trace.Link) []*tracepb.Span_Link {
if len(links) == 0 { if len(links) == 0 {
return nil return nil
} }
@ -193,17 +193,17 @@ func spanEvents(es []export.Event) []*tracepb.Span_Event {
} }
// spanKind transforms a SpanKind to an OTLP span kind. // spanKind transforms a SpanKind to an OTLP span kind.
func spanKind(kind otel.SpanKind) tracepb.Span_SpanKind { func spanKind(kind trace.SpanKind) tracepb.Span_SpanKind {
switch kind { switch kind {
case otel.SpanKindInternal: case trace.SpanKindInternal:
return tracepb.Span_SPAN_KIND_INTERNAL return tracepb.Span_SPAN_KIND_INTERNAL
case otel.SpanKindClient: case trace.SpanKindClient:
return tracepb.Span_SPAN_KIND_CLIENT return tracepb.Span_SPAN_KIND_CLIENT
case otel.SpanKindServer: case trace.SpanKindServer:
return tracepb.Span_SPAN_KIND_SERVER return tracepb.Span_SPAN_KIND_SERVER
case otel.SpanKindProducer: case trace.SpanKindProducer:
return tracepb.Span_SPAN_KIND_PRODUCER return tracepb.Span_SPAN_KIND_PRODUCER
case otel.SpanKindConsumer: case trace.SpanKindConsumer:
return tracepb.Span_SPAN_KIND_CONSUMER return tracepb.Span_SPAN_KIND_CONSUMER
default: default:
return tracepb.Span_SPAN_KIND_UNSPECIFIED return tracepb.Span_SPAN_KIND_UNSPECIFIED

View File

@ -24,9 +24,9 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"go.opentelemetry.io/otel"
tracepb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/trace/v1" tracepb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/trace/v1"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
"go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
export "go.opentelemetry.io/otel/sdk/export/trace" export "go.opentelemetry.io/otel/sdk/export/trace"
@ -36,31 +36,31 @@ import (
func TestSpanKind(t *testing.T) { func TestSpanKind(t *testing.T) {
for _, test := range []struct { for _, test := range []struct {
kind otel.SpanKind kind trace.SpanKind
expected tracepb.Span_SpanKind expected tracepb.Span_SpanKind
}{ }{
{ {
otel.SpanKindInternal, trace.SpanKindInternal,
tracepb.Span_SPAN_KIND_INTERNAL, tracepb.Span_SPAN_KIND_INTERNAL,
}, },
{ {
otel.SpanKindClient, trace.SpanKindClient,
tracepb.Span_SPAN_KIND_CLIENT, tracepb.Span_SPAN_KIND_CLIENT,
}, },
{ {
otel.SpanKindServer, trace.SpanKindServer,
tracepb.Span_SPAN_KIND_SERVER, tracepb.Span_SPAN_KIND_SERVER,
}, },
{ {
otel.SpanKindProducer, trace.SpanKindProducer,
tracepb.Span_SPAN_KIND_PRODUCER, tracepb.Span_SPAN_KIND_PRODUCER,
}, },
{ {
otel.SpanKindConsumer, trace.SpanKindConsumer,
tracepb.Span_SPAN_KIND_CONSUMER, tracepb.Span_SPAN_KIND_CONSUMER,
}, },
{ {
otel.SpanKind(-1), trace.SpanKind(-1),
tracepb.Span_SPAN_KIND_UNSPECIFIED, tracepb.Span_SPAN_KIND_UNSPECIFIED,
}, },
} { } {
@ -117,15 +117,15 @@ func TestNilLinks(t *testing.T) {
} }
func TestEmptyLinks(t *testing.T) { func TestEmptyLinks(t *testing.T) {
assert.Nil(t, links([]otel.Link{})) assert.Nil(t, links([]trace.Link{}))
} }
func TestLinks(t *testing.T) { func TestLinks(t *testing.T) {
attrs := []label.KeyValue{label.Int("one", 1), label.Int("two", 2)} attrs := []label.KeyValue{label.Int("one", 1), label.Int("two", 2)}
l := []otel.Link{ l := []trace.Link{
{}, {},
{ {
SpanContext: otel.SpanContext{}, SpanContext: trace.SpanContext{},
Attributes: attrs, Attributes: attrs,
}, },
} }
@ -200,12 +200,12 @@ func TestSpanData(t *testing.T) {
startTime := time.Unix(1585674086, 1234) startTime := time.Unix(1585674086, 1234)
endTime := startTime.Add(10 * time.Second) endTime := startTime.Add(10 * time.Second)
spanData := &export.SpanData{ spanData := &export.SpanData{
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F},
SpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8},
}, },
SpanKind: otel.SpanKindServer, SpanKind: trace.SpanKindServer,
ParentSpanID: otel.SpanID{0xEF, 0xEE, 0xED, 0xEC, 0xEB, 0xEA, 0xE9, 0xE8}, ParentSpanID: trace.SpanID{0xEF, 0xEE, 0xED, 0xEC, 0xEB, 0xEA, 0xE9, 0xE8},
Name: "span data to span data", Name: "span data to span data",
StartTime: startTime, StartTime: startTime,
EndTime: endTime, EndTime: endTime,
@ -221,11 +221,11 @@ func TestSpanData(t *testing.T) {
}, },
}, },
}, },
Links: []otel.Link{ Links: []trace.Link{
{ {
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: otel.TraceID{0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF}, TraceID: trace.TraceID{0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF},
SpanID: otel.SpanID{0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7}, SpanID: trace.SpanID{0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7},
TraceFlags: 0, TraceFlags: 0,
}, },
Attributes: []label.KeyValue{ Attributes: []label.KeyValue{
@ -233,9 +233,9 @@ func TestSpanData(t *testing.T) {
}, },
}, },
{ {
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: otel.TraceID{0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF}, TraceID: trace.TraceID{0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF},
SpanID: otel.SpanID{0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7}, SpanID: trace.SpanID{0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7},
TraceFlags: 0, TraceFlags: 0,
}, },
Attributes: []label.KeyValue{ Attributes: []label.KeyValue{

View File

@ -22,13 +22,13 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"google.golang.org/grpc" "google.golang.org/grpc"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
coltracepb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/collector/trace/v1" coltracepb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/collector/trace/v1"
commonpb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/common/v1" commonpb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/common/v1"
resourcepb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/resource/v1" resourcepb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/resource/v1"
tracepb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/trace/v1" tracepb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/trace/v1"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
"go.opentelemetry.io/otel/trace"
tracesdk "go.opentelemetry.io/otel/sdk/export/trace" tracesdk "go.opentelemetry.io/otel/sdk/export/trace"
"go.opentelemetry.io/otel/sdk/instrumentation" "go.opentelemetry.io/otel/sdk/instrumentation"
@ -82,12 +82,12 @@ func TestExportSpans(t *testing.T) {
{ {
[]*tracesdk.SpanData{ []*tracesdk.SpanData{
{ {
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: otel.TraceID([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}), TraceID: trace.TraceID([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}),
SpanID: otel.SpanID([8]byte{0, 0, 0, 0, 0, 0, 0, 1}), SpanID: trace.SpanID([8]byte{0, 0, 0, 0, 0, 0, 0, 1}),
TraceFlags: byte(1), TraceFlags: byte(1),
}, },
SpanKind: otel.SpanKindServer, SpanKind: trace.SpanKindServer,
Name: "parent process", Name: "parent process",
StartTime: startTime, StartTime: startTime,
EndTime: endTime, EndTime: endTime,
@ -104,12 +104,12 @@ func TestExportSpans(t *testing.T) {
}, },
}, },
{ {
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: otel.TraceID([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}), TraceID: trace.TraceID([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}),
SpanID: otel.SpanID([8]byte{0, 0, 0, 0, 0, 0, 0, 1}), SpanID: trace.SpanID([8]byte{0, 0, 0, 0, 0, 0, 0, 1}),
TraceFlags: byte(1), TraceFlags: byte(1),
}, },
SpanKind: otel.SpanKindServer, SpanKind: trace.SpanKindServer,
Name: "secondary parent process", Name: "secondary parent process",
StartTime: startTime, StartTime: startTime,
EndTime: endTime, EndTime: endTime,
@ -126,13 +126,13 @@ func TestExportSpans(t *testing.T) {
}, },
}, },
{ {
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: otel.TraceID([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}), TraceID: trace.TraceID([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}),
SpanID: otel.SpanID([8]byte{0, 0, 0, 0, 0, 0, 0, 2}), SpanID: trace.SpanID([8]byte{0, 0, 0, 0, 0, 0, 0, 2}),
TraceFlags: byte(1), TraceFlags: byte(1),
}, },
ParentSpanID: otel.SpanID([8]byte{0, 0, 0, 0, 0, 0, 0, 1}), ParentSpanID: trace.SpanID([8]byte{0, 0, 0, 0, 0, 0, 0, 1}),
SpanKind: otel.SpanKindInternal, SpanKind: trace.SpanKindInternal,
Name: "internal process", Name: "internal process",
StartTime: startTime, StartTime: startTime,
EndTime: endTime, EndTime: endTime,
@ -149,12 +149,12 @@ func TestExportSpans(t *testing.T) {
}, },
}, },
{ {
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: otel.TraceID([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}), TraceID: trace.TraceID([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}),
SpanID: otel.SpanID([8]byte{0, 0, 0, 0, 0, 0, 0, 1}), SpanID: trace.SpanID([8]byte{0, 0, 0, 0, 0, 0, 0, 1}),
TraceFlags: byte(1), TraceFlags: byte(1),
}, },
SpanKind: otel.SpanKindServer, SpanKind: trace.SpanKindServer,
Name: "parent process", Name: "parent process",
StartTime: startTime, StartTime: startTime,
EndTime: endTime, EndTime: endTime,

View File

@ -22,6 +22,7 @@ import (
"go.opentelemetry.io/otel/exporters/stdout" "go.opentelemetry.io/otel/exporters/stdout"
"go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/global"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
"go.opentelemetry.io/otel/trace"
) )
const ( const (
@ -32,7 +33,7 @@ const (
var ( var (
tracer = global.TracerProvider().Tracer( tracer = global.TracerProvider().Tracer(
instrumentationName, instrumentationName,
otel.WithInstrumentationVersion(instrumentationVersion), trace.WithInstrumentationVersion(instrumentationVersion),
) )
meter = global.MeterProvider().Meter( meter = global.MeterProvider().Meter(
@ -49,7 +50,7 @@ var (
func add(ctx context.Context, x, y int64) int64 { func add(ctx context.Context, x, y int64) int64 {
nameKV := nameKey.String("add") nameKV := nameKey.String("add")
var span otel.Span var span trace.Span
ctx, span = tracer.Start(ctx, "Addition") ctx, span = tracer.Start(ctx, "Addition")
defer span.End() defer span.End()
@ -63,7 +64,7 @@ func add(ctx context.Context, x, y int64) int64 {
func multiply(ctx context.Context, x, y int64) int64 { func multiply(ctx context.Context, x, y int64) int64 {
nameKV := nameKey.String("multiply") nameKV := nameKey.String("multiply")
var span otel.Span var span trace.Span
ctx, span = tracer.Start(ctx, "Multiplication") ctx, span = tracer.Start(ctx, "Multiplication")
defer span.End() defer span.End()

View File

@ -15,7 +15,6 @@
package stdout // import "go.opentelemetry.io/otel/exporters/stdout" package stdout // import "go.opentelemetry.io/otel/exporters/stdout"
import ( import (
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/global"
"go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/export/metric"
exporttrace "go.opentelemetry.io/otel/sdk/export/trace" exporttrace "go.opentelemetry.io/otel/sdk/export/trace"
@ -23,6 +22,7 @@ import (
"go.opentelemetry.io/otel/sdk/metric/processor/basic" "go.opentelemetry.io/otel/sdk/metric/processor/basic"
"go.opentelemetry.io/otel/sdk/metric/selector/simple" "go.opentelemetry.io/otel/sdk/metric/selector/simple"
sdktrace "go.opentelemetry.io/otel/sdk/trace" sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/trace"
) )
type Exporter struct { type Exporter struct {
@ -50,7 +50,7 @@ func NewExporter(options ...Option) (*Exporter, error) {
// NewExportPipeline creates a complete export pipeline with the default // NewExportPipeline creates a complete export pipeline with the default
// selectors, processors, and trace registration. It is the responsibility // selectors, processors, and trace registration. It is the responsibility
// of the caller to stop the returned push Controller. // of the caller to stop the returned push Controller.
func NewExportPipeline(exportOpts []Option, pushOpts []push.Option) (otel.TracerProvider, *push.Controller, error) { func NewExportPipeline(exportOpts []Option, pushOpts []push.Option) (trace.TracerProvider, *push.Controller, error) {
exporter, err := NewExporter(exportOpts...) exporter, err := NewExporter(exportOpts...)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err

View File

@ -22,12 +22,12 @@ import (
"testing" "testing"
"time" "time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/exporters/stdout" "go.opentelemetry.io/otel/exporters/stdout"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
export "go.opentelemetry.io/otel/sdk/export/trace" export "go.opentelemetry.io/otel/sdk/export/trace"
"go.opentelemetry.io/otel/sdk/resource" "go.opentelemetry.io/otel/sdk/resource"
"go.opentelemetry.io/otel/trace"
) )
func TestExporter_ExportSpan(t *testing.T) { func TestExporter_ExportSpan(t *testing.T) {
@ -40,14 +40,14 @@ func TestExporter_ExportSpan(t *testing.T) {
// setup test span // setup test span
now := time.Now() now := time.Now()
traceID, _ := otel.TraceIDFromHex("0102030405060708090a0b0c0d0e0f10") traceID, _ := trace.TraceIDFromHex("0102030405060708090a0b0c0d0e0f10")
spanID, _ := otel.SpanIDFromHex("0102030405060708") spanID, _ := trace.SpanIDFromHex("0102030405060708")
keyValue := "value" keyValue := "value"
doubleValue := 123.456 doubleValue := 123.456
resource := resource.NewWithAttributes(label.String("rk1", "rv11")) resource := resource.NewWithAttributes(label.String("rk1", "rv11"))
testSpan := &export.SpanData{ testSpan := &export.SpanData{
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: traceID, TraceID: traceID,
SpanID: spanID, SpanID: spanID,
}, },
@ -62,7 +62,7 @@ func TestExporter_ExportSpan(t *testing.T) {
{Name: "foo", Attributes: []label.KeyValue{label.String("key", keyValue)}, Time: now}, {Name: "foo", Attributes: []label.KeyValue{label.String("key", keyValue)}, Time: now},
{Name: "bar", Attributes: []label.KeyValue{label.Float64("double", doubleValue)}, Time: now}, {Name: "bar", Attributes: []label.KeyValue{label.Float64("double", doubleValue)}, Time: now},
}, },
SpanKind: otel.SpanKindInternal, SpanKind: trace.SpanKindInternal,
StatusCode: codes.Error, StatusCode: codes.Error,
StatusMessage: "interesting", StatusMessage: "interesting",
Resource: resource, Resource: resource,

View File

@ -22,13 +22,13 @@ import (
"google.golang.org/api/support/bundler" "google.golang.org/api/support/bundler"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
gen "go.opentelemetry.io/otel/exporters/trace/jaeger/internal/gen-go/jaeger" gen "go.opentelemetry.io/otel/exporters/trace/jaeger/internal/gen-go/jaeger"
"go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/global"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
export "go.opentelemetry.io/otel/sdk/export/trace" export "go.opentelemetry.io/otel/sdk/export/trace"
sdktrace "go.opentelemetry.io/otel/sdk/trace" sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/trace"
) )
const ( const (
@ -151,14 +151,14 @@ func NewRawExporter(endpointOption EndpointOption, opts ...Option) (*Exporter, e
// NewExportPipeline sets up a complete export pipeline // NewExportPipeline sets up a complete export pipeline
// with the recommended setup for trace provider // with the recommended setup for trace provider
func NewExportPipeline(endpointOption EndpointOption, opts ...Option) (otel.TracerProvider, func(), error) { func NewExportPipeline(endpointOption EndpointOption, opts ...Option) (trace.TracerProvider, func(), error) {
o := options{} o := options{}
opts = append(opts, WithDisabledFromEnv()) opts = append(opts, WithDisabledFromEnv())
for _, opt := range opts { for _, opt := range opts {
opt(&o) opt(&o)
} }
if o.Disabled { if o.Disabled {
return otel.NewNoopTracerProvider(), func() {}, nil return trace.NewNoopTracerProvider(), func() {}, nil
} }
exporter, err := NewRawExporter(endpointOption, opts...) exporter, err := NewRawExporter(endpointOption, opts...)

View File

@ -28,7 +28,6 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"google.golang.org/api/support/bundler" "google.golang.org/api/support/bundler"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
gen "go.opentelemetry.io/otel/exporters/trace/jaeger/internal/gen-go/jaeger" gen "go.opentelemetry.io/otel/exporters/trace/jaeger/internal/gen-go/jaeger"
"go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/global"
@ -38,6 +37,7 @@ import (
"go.opentelemetry.io/otel/sdk/instrumentation" "go.opentelemetry.io/otel/sdk/instrumentation"
"go.opentelemetry.io/otel/sdk/resource" "go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace" sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/trace"
) )
const ( const (
@ -50,7 +50,7 @@ func TestInstallNewPipeline(t *testing.T) {
name string name string
endpoint EndpointOption endpoint EndpointOption
options []Option options []Option
expectedProvider otel.TracerProvider expectedProvider trace.TracerProvider
}{ }{
{ {
name: "simple pipeline", name: "simple pipeline",
@ -68,7 +68,7 @@ func TestInstallNewPipeline(t *testing.T) {
options: []Option{ options: []Option{
WithDisabled(true), WithDisabled(true),
}, },
expectedProvider: otel.NewNoopTracerProvider(), expectedProvider: trace.NewNoopTracerProvider(),
}, },
} }
@ -93,7 +93,7 @@ func TestNewExportPipeline(t *testing.T) {
name string name string
endpoint EndpointOption endpoint EndpointOption
options []Option options []Option
expectedProviderType otel.TracerProvider expectedProviderType trace.TracerProvider
testSpanSampling, spanShouldBeSampled bool testSpanSampling, spanShouldBeSampled bool
}{ }{
{ {
@ -107,7 +107,7 @@ func TestNewExportPipeline(t *testing.T) {
options: []Option{ options: []Option{
WithDisabled(true), WithDisabled(true),
}, },
expectedProviderType: otel.NewNoopTracerProvider(), expectedProviderType: trace.NewNoopTracerProvider(),
}, },
{ {
name: "always on", name: "always on",
@ -172,7 +172,7 @@ func TestNewExportPipelineWithDisabledFromEnv(t *testing.T) {
) )
defer fn() defer fn()
assert.NoError(t, err) assert.NoError(t, err)
assert.IsType(t, otel.NewNoopTracerProvider(), tp) assert.IsType(t, trace.NewNoopTracerProvider(), tp)
} }
func TestNewRawExporter(t *testing.T) { func TestNewRawExporter(t *testing.T) {
@ -355,11 +355,11 @@ func TestExporter_ExportSpan(t *testing.T) {
func Test_spanDataToThrift(t *testing.T) { func Test_spanDataToThrift(t *testing.T) {
now := time.Now() now := time.Now()
traceID, _ := otel.TraceIDFromHex("0102030405060708090a0b0c0d0e0f10") traceID, _ := trace.TraceIDFromHex("0102030405060708090a0b0c0d0e0f10")
spanID, _ := otel.SpanIDFromHex("0102030405060708") spanID, _ := trace.SpanIDFromHex("0102030405060708")
linkTraceID, _ := otel.TraceIDFromHex("0102030405060709090a0b0c0d0e0f11") linkTraceID, _ := trace.TraceIDFromHex("0102030405060709090a0b0c0d0e0f11")
linkSpanID, _ := otel.SpanIDFromHex("0102030405060709") linkSpanID, _ := trace.SpanIDFromHex("0102030405060709")
eventNameValue := "event-test" eventNameValue := "event-test"
keyValue := "value" keyValue := "value"
@ -382,16 +382,16 @@ func Test_spanDataToThrift(t *testing.T) {
{ {
name: "no parent", name: "no parent",
data: &export.SpanData{ data: &export.SpanData{
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: traceID, TraceID: traceID,
SpanID: spanID, SpanID: spanID,
}, },
Name: "/foo", Name: "/foo",
StartTime: now, StartTime: now,
EndTime: now, EndTime: now,
Links: []otel.Link{ Links: []trace.Link{
{ {
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: linkTraceID, TraceID: linkTraceID,
SpanID: linkSpanID, SpanID: linkSpanID,
}, },
@ -408,7 +408,7 @@ func Test_spanDataToThrift(t *testing.T) {
}, },
StatusCode: codes.Error, StatusCode: codes.Error,
StatusMessage: statusMessage, StatusMessage: statusMessage,
SpanKind: otel.SpanKindClient, SpanKind: trace.SpanKindClient,
Resource: resource.NewWithAttributes(label.String("rk1", rv1), label.Int64("rk2", rv2)), Resource: resource.NewWithAttributes(label.String("rk1", rv1), label.Int64("rk2", rv2)),
InstrumentationLibrary: instrumentation.Library{ InstrumentationLibrary: instrumentation.Library{
Name: instrLibName, Name: instrLibName,

View File

@ -21,9 +21,9 @@ import (
zkmodel "github.com/openzipkin/zipkin-go/model" zkmodel "github.com/openzipkin/zipkin-go/model"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
export "go.opentelemetry.io/otel/sdk/export/trace" export "go.opentelemetry.io/otel/sdk/export/trace"
"go.opentelemetry.io/otel/trace"
) )
const ( const (
@ -67,18 +67,18 @@ func toZipkinSpanContext(data *export.SpanData) zkmodel.SpanContext {
} }
} }
func toZipkinTraceID(traceID otel.TraceID) zkmodel.TraceID { func toZipkinTraceID(traceID trace.TraceID) zkmodel.TraceID {
return zkmodel.TraceID{ return zkmodel.TraceID{
High: binary.BigEndian.Uint64(traceID[:8]), High: binary.BigEndian.Uint64(traceID[:8]),
Low: binary.BigEndian.Uint64(traceID[8:]), Low: binary.BigEndian.Uint64(traceID[8:]),
} }
} }
func toZipkinID(spanID otel.SpanID) zkmodel.ID { func toZipkinID(spanID trace.SpanID) zkmodel.ID {
return zkmodel.ID(binary.BigEndian.Uint64(spanID[:])) return zkmodel.ID(binary.BigEndian.Uint64(spanID[:]))
} }
func toZipkinParentID(spanID otel.SpanID) *zkmodel.ID { func toZipkinParentID(spanID trace.SpanID) *zkmodel.ID {
if spanID.IsValid() { if spanID.IsValid() {
id := toZipkinID(spanID) id := toZipkinID(spanID)
return &id return &id
@ -86,21 +86,21 @@ func toZipkinParentID(spanID otel.SpanID) *zkmodel.ID {
return nil return nil
} }
func toZipkinKind(kind otel.SpanKind) zkmodel.Kind { func toZipkinKind(kind trace.SpanKind) zkmodel.Kind {
switch kind { switch kind {
case otel.SpanKindUnspecified: case trace.SpanKindUnspecified:
return zkmodel.Undetermined return zkmodel.Undetermined
case otel.SpanKindInternal: case trace.SpanKindInternal:
// The spec says we should set the kind to nil, but // The spec says we should set the kind to nil, but
// the model does not allow that. // the model does not allow that.
return zkmodel.Undetermined return zkmodel.Undetermined
case otel.SpanKindServer: case trace.SpanKindServer:
return zkmodel.Server return zkmodel.Server
case otel.SpanKindClient: case trace.SpanKindClient:
return zkmodel.Client return zkmodel.Client
case otel.SpanKindProducer: case trace.SpanKindProducer:
return zkmodel.Producer return zkmodel.Producer
case otel.SpanKindConsumer: case trace.SpanKindConsumer:
return zkmodel.Consumer return zkmodel.Consumer
} }
return zkmodel.Undetermined return zkmodel.Undetermined

View File

@ -24,23 +24,23 @@ import (
zkmodel "github.com/openzipkin/zipkin-go/model" zkmodel "github.com/openzipkin/zipkin-go/model"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
export "go.opentelemetry.io/otel/sdk/export/trace" export "go.opentelemetry.io/otel/sdk/export/trace"
"go.opentelemetry.io/otel/sdk/instrumentation" "go.opentelemetry.io/otel/sdk/instrumentation"
"go.opentelemetry.io/otel/trace"
) )
func TestModelConversion(t *testing.T) { func TestModelConversion(t *testing.T) {
inputBatch := []*export.SpanData{ inputBatch := []*export.SpanData{
// typical span data // typical span data
{ {
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F},
SpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8},
}, },
ParentSpanID: otel.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, ParentSpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38},
SpanKind: otel.SpanKindServer, SpanKind: trace.SpanKindServer,
Name: "foo", Name: "foo",
StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC),
EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC),
@ -68,12 +68,12 @@ func TestModelConversion(t *testing.T) {
// span data with no parent (same as typical, but has // span data with no parent (same as typical, but has
// invalid parent) // invalid parent)
{ {
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F},
SpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8},
}, },
ParentSpanID: otel.SpanID{}, ParentSpanID: trace.SpanID{},
SpanKind: otel.SpanKindServer, SpanKind: trace.SpanKindServer,
Name: "foo", Name: "foo",
StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC),
EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC),
@ -100,12 +100,12 @@ func TestModelConversion(t *testing.T) {
}, },
// span data of unspecified kind // span data of unspecified kind
{ {
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F},
SpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8},
}, },
ParentSpanID: otel.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, ParentSpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38},
SpanKind: otel.SpanKindUnspecified, SpanKind: trace.SpanKindUnspecified,
Name: "foo", Name: "foo",
StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC),
EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC),
@ -132,12 +132,12 @@ func TestModelConversion(t *testing.T) {
}, },
// span data of internal kind // span data of internal kind
{ {
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F},
SpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8},
}, },
ParentSpanID: otel.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, ParentSpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38},
SpanKind: otel.SpanKindInternal, SpanKind: trace.SpanKindInternal,
Name: "foo", Name: "foo",
StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC),
EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC),
@ -164,12 +164,12 @@ func TestModelConversion(t *testing.T) {
}, },
// span data of client kind // span data of client kind
{ {
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F},
SpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8},
}, },
ParentSpanID: otel.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, ParentSpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38},
SpanKind: otel.SpanKindClient, SpanKind: trace.SpanKindClient,
Name: "foo", Name: "foo",
StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC),
EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC),
@ -196,12 +196,12 @@ func TestModelConversion(t *testing.T) {
}, },
// span data of producer kind // span data of producer kind
{ {
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F},
SpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8},
}, },
ParentSpanID: otel.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, ParentSpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38},
SpanKind: otel.SpanKindProducer, SpanKind: trace.SpanKindProducer,
Name: "foo", Name: "foo",
StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC),
EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC),
@ -228,12 +228,12 @@ func TestModelConversion(t *testing.T) {
}, },
// span data of consumer kind // span data of consumer kind
{ {
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F},
SpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8},
}, },
ParentSpanID: otel.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, ParentSpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38},
SpanKind: otel.SpanKindConsumer, SpanKind: trace.SpanKindConsumer,
Name: "foo", Name: "foo",
StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC),
EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC),
@ -260,12 +260,12 @@ func TestModelConversion(t *testing.T) {
}, },
// span data with no events // span data with no events
{ {
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F},
SpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8},
}, },
ParentSpanID: otel.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, ParentSpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38},
SpanKind: otel.SpanKindServer, SpanKind: trace.SpanKindServer,
Name: "foo", Name: "foo",
StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC),
EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC),
@ -279,12 +279,12 @@ func TestModelConversion(t *testing.T) {
}, },
// span data with an "error" attribute set to "false" // span data with an "error" attribute set to "false"
{ {
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F},
SpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8},
}, },
ParentSpanID: otel.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, ParentSpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38},
SpanKind: otel.SpanKindServer, SpanKind: trace.SpanKindServer,
Name: "foo", Name: "foo",
StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC),
EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC),

View File

@ -30,11 +30,11 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/global"
export "go.opentelemetry.io/otel/sdk/export/trace" export "go.opentelemetry.io/otel/sdk/export/trace"
sdktrace "go.opentelemetry.io/otel/sdk/trace" sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/trace"
) )
const ( const (
@ -241,12 +241,12 @@ func TestExportSpans(t *testing.T) {
spans := []*export.SpanData{ spans := []*export.SpanData{
// parent // parent
{ {
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F},
SpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8},
}, },
ParentSpanID: otel.SpanID{}, ParentSpanID: trace.SpanID{},
SpanKind: otel.SpanKindServer, SpanKind: trace.SpanKindServer,
Name: "foo", Name: "foo",
StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC),
EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC),
@ -257,12 +257,12 @@ func TestExportSpans(t *testing.T) {
}, },
// child // child
{ {
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F},
SpanID: otel.SpanID{0xDF, 0xDE, 0xDD, 0xDC, 0xDB, 0xDA, 0xD9, 0xD8}, SpanID: trace.SpanID{0xDF, 0xDE, 0xDD, 0xDC, 0xDB, 0xDA, 0xD9, 0xD8},
}, },
ParentSpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, ParentSpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8},
SpanKind: otel.SpanKindServer, SpanKind: trace.SpanKindServer,
Name: "bar", Name: "bar",
StartTime: time.Date(2020, time.March, 11, 19, 24, 15, 0, time.UTC), StartTime: time.Date(2020, time.March, 11, 19, 24, 15, 0, time.UTC),
EndTime: time.Date(2020, time.March, 11, 19, 24, 45, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 24, 45, 0, time.UTC),

View File

@ -19,11 +19,12 @@ import (
"sync/atomic" "sync/atomic"
"go.opentelemetry.io/otel" "go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
) )
type ( type (
tracerProviderHolder struct { tracerProviderHolder struct {
tp otel.TracerProvider tp trace.TracerProvider
} }
meterProviderHolder struct { meterProviderHolder struct {
@ -46,12 +47,12 @@ var (
) )
// TracerProvider is the internal implementation for global.TracerProvider. // TracerProvider is the internal implementation for global.TracerProvider.
func TracerProvider() otel.TracerProvider { func TracerProvider() trace.TracerProvider {
return globalTracer.Load().(tracerProviderHolder).tp return globalTracer.Load().(tracerProviderHolder).tp
} }
// SetTracerProvider is the internal implementation for global.SetTracerProvider. // SetTracerProvider is the internal implementation for global.SetTracerProvider.
func SetTracerProvider(tp otel.TracerProvider) { func SetTracerProvider(tp trace.TracerProvider) {
delegateTraceOnce.Do(func() { delegateTraceOnce.Do(func() {
current := TracerProvider() current := TracerProvider()
if current == tp { if current == tp {

View File

@ -35,8 +35,8 @@ import (
"context" "context"
"sync" "sync"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/internal/trace/noop" "go.opentelemetry.io/otel/internal/trace/noop"
"go.opentelemetry.io/otel/trace"
) )
// tracerProvider is a placeholder for a configured SDK TracerProvider. // tracerProvider is a placeholder for a configured SDK TracerProvider.
@ -47,12 +47,12 @@ type tracerProvider struct {
mtx sync.Mutex mtx sync.Mutex
tracers []*tracer tracers []*tracer
delegate otel.TracerProvider delegate trace.TracerProvider
} }
// Compile-time guarantee that tracerProvider implements the TracerProvider // Compile-time guarantee that tracerProvider implements the TracerProvider
// interface. // interface.
var _ otel.TracerProvider = &tracerProvider{} var _ trace.TracerProvider = &tracerProvider{}
// setDelegate configures p to delegate all TracerProvider functionality to // setDelegate configures p to delegate all TracerProvider functionality to
// provider. // provider.
@ -62,7 +62,7 @@ var _ otel.TracerProvider = &tracerProvider{}
// //
// Delegation only happens on the first call to this method. All subsequent // Delegation only happens on the first call to this method. All subsequent
// calls result in no delegation changes. // calls result in no delegation changes.
func (p *tracerProvider) setDelegate(provider otel.TracerProvider) { func (p *tracerProvider) setDelegate(provider trace.TracerProvider) {
if p.delegate != nil { if p.delegate != nil {
return return
} }
@ -79,7 +79,7 @@ func (p *tracerProvider) setDelegate(provider otel.TracerProvider) {
} }
// Tracer implements TracerProvider. // Tracer implements TracerProvider.
func (p *tracerProvider) Tracer(name string, opts ...otel.TracerOption) otel.Tracer { func (p *tracerProvider) Tracer(name string, opts ...trace.TracerOption) trace.Tracer {
p.mtx.Lock() p.mtx.Lock()
defer p.mtx.Unlock() defer p.mtx.Unlock()
@ -92,20 +92,20 @@ func (p *tracerProvider) Tracer(name string, opts ...otel.TracerOption) otel.Tra
return t return t
} }
// tracer is a placeholder for a otel.Tracer. // tracer is a placeholder for a trace.Tracer.
// //
// All Tracer functionality is forwarded to a delegate once configured. // All Tracer functionality is forwarded to a delegate once configured.
// Otherwise, all functionality is forwarded to a NoopTracer. // Otherwise, all functionality is forwarded to a NoopTracer.
type tracer struct { type tracer struct {
once sync.Once once sync.Once
name string name string
opts []otel.TracerOption opts []trace.TracerOption
delegate otel.Tracer delegate trace.Tracer
} }
// Compile-time guarantee that tracer implements the otel.Tracer interface. // Compile-time guarantee that tracer implements the trace.Tracer interface.
var _ otel.Tracer = &tracer{} var _ trace.Tracer = &tracer{}
// setDelegate configures t to delegate all Tracer functionality to Tracers // setDelegate configures t to delegate all Tracer functionality to Tracers
// created by provider. // created by provider.
@ -114,13 +114,13 @@ var _ otel.Tracer = &tracer{}
// //
// Delegation only happens on the first call to this method. All subsequent // Delegation only happens on the first call to this method. All subsequent
// calls result in no delegation changes. // calls result in no delegation changes.
func (t *tracer) setDelegate(provider otel.TracerProvider) { func (t *tracer) setDelegate(provider trace.TracerProvider) {
t.once.Do(func() { t.delegate = provider.Tracer(t.name, t.opts...) }) t.once.Do(func() { t.delegate = provider.Tracer(t.name, t.opts...) })
} }
// Start implements otel.Tracer by forwarding the call to t.delegate if // Start implements trace.Tracer by forwarding the call to t.delegate if
// set, otherwise it forwards the call to a NoopTracer. // set, otherwise it forwards the call to a NoopTracer.
func (t *tracer) Start(ctx context.Context, name string, opts ...otel.SpanOption) (context.Context, otel.Span) { func (t *tracer) Start(ctx context.Context, name string, opts ...trace.SpanOption) (context.Context, trace.Span) {
if t.delegate != nil { if t.delegate != nil {
return t.delegate.Start(ctx, name, opts...) return t.delegate.Start(ctx, name, opts...)
} }

View File

@ -15,15 +15,15 @@
package global // import "go.opentelemetry.io/otel/global" package global // import "go.opentelemetry.io/otel/global"
import ( import (
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/global/internal" "go.opentelemetry.io/otel/global/internal"
"go.opentelemetry.io/otel/trace"
) )
// Tracer creates a named tracer that implements Tracer interface. // Tracer creates a named tracer that implements Tracer interface.
// If the name is an empty string then provider uses default name. // If the name is an empty string then provider uses default name.
// //
// This is short for TracerProvider().Tracer(name) // This is short for TracerProvider().Tracer(name)
func Tracer(name string) otel.Tracer { func Tracer(name string) trace.Tracer {
return TracerProvider().Tracer(name) return TracerProvider().Tracer(name)
} }
@ -34,11 +34,11 @@ func Tracer(name string) otel.Tracer {
// tracer := global.TracerProvider().Tracer("example.com/foo") // tracer := global.TracerProvider().Tracer("example.com/foo")
// or // or
// tracer := global.Tracer("example.com/foo") // tracer := global.Tracer("example.com/foo")
func TracerProvider() otel.TracerProvider { func TracerProvider() trace.TracerProvider {
return internal.TracerProvider() return internal.TracerProvider()
} }
// SetTracerProvider registers `tp` as the global trace provider. // SetTracerProvider registers `tp` as the global trace provider.
func SetTracerProvider(tp otel.TracerProvider) { func SetTracerProvider(tp trace.TracerProvider) {
internal.SetTracerProvider(tp) internal.SetTracerProvider(tp)
} }

View File

@ -17,22 +17,22 @@ package global_test
import ( import (
"testing" "testing"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/global"
"go.opentelemetry.io/otel/internal/trace/noop" "go.opentelemetry.io/otel/internal/trace/noop"
"go.opentelemetry.io/otel/trace"
) )
type testTracerProvider struct{} type testTracerProvider struct{}
var _ otel.TracerProvider = &testTracerProvider{} var _ trace.TracerProvider = &testTracerProvider{}
func (*testTracerProvider) Tracer(_ string, _ ...otel.TracerOption) otel.Tracer { func (*testTracerProvider) Tracer(_ string, _ ...trace.TracerOption) trace.Tracer {
return noop.Tracer return noop.Tracer
} }
func TestMultipleGlobalTracerProvider(t *testing.T) { func TestMultipleGlobalTracerProvider(t *testing.T) {
p1 := testTracerProvider{} p1 := testTracerProvider{}
p2 := otel.NewNoopTracerProvider() p2 := trace.NewNoopTracerProvider()
global.SetTracerProvider(&p1) global.SetTracerProvider(&p1)
global.SetTracerProvider(p2) global.SetTracerProvider(p2)

View File

@ -18,18 +18,18 @@ package noop
import ( import (
"context" "context"
"go.opentelemetry.io/otel" "go.opentelemetry.io/otel/trace"
) )
var ( var (
// Tracer is a noop tracer that starts noop spans. // Tracer is a noop tracer that starts noop spans.
Tracer otel.Tracer Tracer trace.Tracer
// Span is a noop Span. // Span is a noop Span.
Span otel.Span Span trace.Span
) )
func init() { func init() {
Tracer = otel.NewNoopTracerProvider().Tracer("") Tracer = trace.NewNoopTracerProvider().Tracer("")
_, Span = Tracer.Start(context.Background(), "") _, Span = Tracer.Start(context.Background(), "")
} }

View File

@ -17,19 +17,19 @@ package parent
import ( import (
"context" "context"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
"go.opentelemetry.io/otel/trace"
) )
func GetSpanContextAndLinks(ctx context.Context, ignoreContext bool) (otel.SpanContext, bool, []otel.Link) { func GetSpanContextAndLinks(ctx context.Context, ignoreContext bool) (trace.SpanContext, bool, []trace.Link) {
lsctx := otel.SpanContextFromContext(ctx) lsctx := trace.SpanContextFromContext(ctx)
rsctx := otel.RemoteSpanContextFromContext(ctx) rsctx := trace.RemoteSpanContextFromContext(ctx)
if ignoreContext { if ignoreContext {
links := addLinkIfValid(nil, lsctx, "current") links := addLinkIfValid(nil, lsctx, "current")
links = addLinkIfValid(links, rsctx, "remote") links = addLinkIfValid(links, rsctx, "remote")
return otel.SpanContext{}, false, links return trace.SpanContext{}, false, links
} }
if lsctx.IsValid() { if lsctx.IsValid() {
return lsctx, false, nil return lsctx, false, nil
@ -37,14 +37,14 @@ func GetSpanContextAndLinks(ctx context.Context, ignoreContext bool) (otel.SpanC
if rsctx.IsValid() { if rsctx.IsValid() {
return rsctx, true, nil return rsctx, true, nil
} }
return otel.SpanContext{}, false, nil return trace.SpanContext{}, false, nil
} }
func addLinkIfValid(links []otel.Link, sc otel.SpanContext, kind string) []otel.Link { func addLinkIfValid(links []trace.Link, sc trace.SpanContext, kind string) []trace.Link {
if !sc.IsValid() { if !sc.IsValid() {
return links return links
} }
return append(links, otel.Link{ return append(links, trace.Link{
SpanContext: sc, SpanContext: sc,
Attributes: []label.KeyValue{ Attributes: []label.KeyValue{
label.String("ignored-on-demand", kind), label.String("ignored-on-demand", kind),

View File

@ -20,17 +20,17 @@ import (
"sync" "sync"
"sync/atomic" "sync/atomic"
"go.opentelemetry.io/otel" "go.opentelemetry.io/otel/trace"
) )
// defaultSpanContextFunc returns the default SpanContextFunc. // defaultSpanContextFunc returns the default SpanContextFunc.
func defaultSpanContextFunc() func(context.Context) otel.SpanContext { func defaultSpanContextFunc() func(context.Context) trace.SpanContext {
var traceID, spanID uint64 = 1, 1 var traceID, spanID uint64 = 1, 1
return func(ctx context.Context) otel.SpanContext { return func(ctx context.Context) trace.SpanContext {
var sc otel.SpanContext var sc trace.SpanContext
if lsc := otel.SpanContextFromContext(ctx); lsc.IsValid() { if lsc := trace.SpanContextFromContext(ctx); lsc.IsValid() {
sc = lsc sc = lsc
} else if rsc := otel.RemoteSpanContextFromContext(ctx); rsc.IsValid() { } else if rsc := trace.RemoteSpanContextFromContext(ctx); rsc.IsValid() {
sc = rsc sc = rsc
} else { } else {
binary.BigEndian.PutUint64(sc.TraceID[:], atomic.AddUint64(&traceID, 1)) binary.BigEndian.PutUint64(sc.TraceID[:], atomic.AddUint64(&traceID, 1))
@ -43,7 +43,7 @@ func defaultSpanContextFunc() func(context.Context) otel.SpanContext {
type config struct { type config struct {
// SpanContextFunc returns a SpanContext from an parent Context for a // SpanContextFunc returns a SpanContext from an parent Context for a
// new span. // new span.
SpanContextFunc func(context.Context) otel.SpanContext SpanContextFunc func(context.Context) trace.SpanContext
// SpanRecorder keeps track of spans. // SpanRecorder keeps track of spans.
SpanRecorder SpanRecorder SpanRecorder SpanRecorder
@ -66,7 +66,7 @@ type Option interface {
} }
type spanContextFuncOption struct { type spanContextFuncOption struct {
SpanContextFunc func(context.Context) otel.SpanContext SpanContextFunc func(context.Context) trace.SpanContext
} }
func (o spanContextFuncOption) Apply(c *config) { func (o spanContextFuncOption) Apply(c *config) {
@ -75,7 +75,7 @@ func (o spanContextFuncOption) Apply(c *config) {
// WithSpanContextFunc sets the SpanContextFunc used to generate a new Spans // WithSpanContextFunc sets the SpanContextFunc used to generate a new Spans
// context from a parent SpanContext. // context from a parent SpanContext.
func WithSpanContextFunc(f func(context.Context) otel.SpanContext) Option { func WithSpanContextFunc(f func(context.Context) trace.SpanContext) Option {
return spanContextFuncOption{f} return spanContextFuncOption{f}
} }

View File

@ -20,10 +20,10 @@ import (
"testing" "testing"
"time" "time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/internal/matchers" "go.opentelemetry.io/otel/internal/matchers"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
"go.opentelemetry.io/otel/trace"
) )
// Harness is a testing harness used to test implementations of the // Harness is a testing harness used to test implementations of the
@ -41,7 +41,7 @@ func NewHarness(t *testing.T) *Harness {
// TestTracer runs validation tests for an implementation of the OpenTelemetry // TestTracer runs validation tests for an implementation of the OpenTelemetry
// Tracer API. // Tracer API.
func (h *Harness) TestTracer(subjectFactory func() otel.Tracer) { func (h *Harness) TestTracer(subjectFactory func() trace.Tracer) {
h.t.Run("#Start", func(t *testing.T) { h.t.Run("#Start", func(t *testing.T) {
t.Run("propagates the original context", func(t *testing.T) { t.Run("propagates the original context", func(t *testing.T) {
t.Parallel() t.Parallel()
@ -81,8 +81,8 @@ func (h *Harness) TestTracer(subjectFactory func() otel.Tracer) {
ctx, span := subject.Start(context.Background(), "test") ctx, span := subject.Start(context.Background(), "test")
e.Expect(span).NotToBeNil() e.Expect(span).NotToBeNil()
e.Expect(span.SpanContext()).NotToEqual(otel.SpanContext{}) e.Expect(span.SpanContext()).NotToEqual(trace.SpanContext{})
e.Expect(otel.SpanFromContext(ctx)).ToEqual(span) e.Expect(trace.SpanFromContext(ctx)).ToEqual(span)
}) })
t.Run("starts spans with unique trace and span IDs", func(t *testing.T) { t.Run("starts spans with unique trace and span IDs", func(t *testing.T) {
@ -107,7 +107,7 @@ func (h *Harness) TestTracer(subjectFactory func() otel.Tracer) {
e := matchers.NewExpecter(t) e := matchers.NewExpecter(t)
subject := subjectFactory() subject := subjectFactory()
_, span := subject.Start(context.Background(), "span", otel.WithRecord()) _, span := subject.Start(context.Background(), "span", trace.WithRecord())
e.Expect(span.IsRecording()).ToBeTrue() e.Expect(span.IsRecording()).ToBeTrue()
}) })
@ -135,7 +135,7 @@ func (h *Harness) TestTracer(subjectFactory func() otel.Tracer) {
subject := subjectFactory() subject := subjectFactory()
ctx, parent := subject.Start(context.Background(), "parent") ctx, parent := subject.Start(context.Background(), "parent")
_, child := subject.Start(ctx, "child", otel.WithNewRoot()) _, child := subject.Start(ctx, "child", trace.WithNewRoot())
psc := parent.SpanContext() psc := parent.SpanContext()
csc := child.SpanContext() csc := child.SpanContext()
@ -151,7 +151,7 @@ func (h *Harness) TestTracer(subjectFactory func() otel.Tracer) {
subject := subjectFactory() subject := subjectFactory()
_, remoteParent := subject.Start(context.Background(), "remote parent") _, remoteParent := subject.Start(context.Background(), "remote parent")
parentCtx := otel.ContextWithRemoteSpanContext(context.Background(), remoteParent.SpanContext()) parentCtx := trace.ContextWithRemoteSpanContext(context.Background(), remoteParent.SpanContext())
_, child := subject.Start(parentCtx, "child") _, child := subject.Start(parentCtx, "child")
psc := remoteParent.SpanContext() psc := remoteParent.SpanContext()
@ -168,8 +168,8 @@ func (h *Harness) TestTracer(subjectFactory func() otel.Tracer) {
subject := subjectFactory() subject := subjectFactory()
_, remoteParent := subject.Start(context.Background(), "remote parent") _, remoteParent := subject.Start(context.Background(), "remote parent")
parentCtx := otel.ContextWithRemoteSpanContext(context.Background(), remoteParent.SpanContext()) parentCtx := trace.ContextWithRemoteSpanContext(context.Background(), remoteParent.SpanContext())
_, child := subject.Start(parentCtx, "child", otel.WithNewRoot()) _, child := subject.Start(parentCtx, "child", trace.WithNewRoot())
psc := remoteParent.SpanContext() psc := remoteParent.SpanContext()
csc := child.SpanContext() csc := child.SpanContext()
@ -182,29 +182,29 @@ func (h *Harness) TestTracer(subjectFactory func() otel.Tracer) {
h.testSpan(subjectFactory) h.testSpan(subjectFactory)
} }
func (h *Harness) testSpan(tracerFactory func() otel.Tracer) { func (h *Harness) testSpan(tracerFactory func() trace.Tracer) {
var methods = map[string]func(span otel.Span){ var methods = map[string]func(span trace.Span){
"#End": func(span otel.Span) { "#End": func(span trace.Span) {
span.End() span.End()
}, },
"#AddEvent": func(span otel.Span) { "#AddEvent": func(span trace.Span) {
span.AddEvent("test event") span.AddEvent("test event")
}, },
"#AddEventWithTimestamp": func(span otel.Span) { "#AddEventWithTimestamp": func(span trace.Span) {
span.AddEvent("test event", otel.WithTimestamp(time.Now().Add(1*time.Second))) span.AddEvent("test event", trace.WithTimestamp(time.Now().Add(1*time.Second)))
}, },
"#SetStatus": func(span otel.Span) { "#SetStatus": func(span trace.Span) {
span.SetStatus(codes.Error, "internal") span.SetStatus(codes.Error, "internal")
}, },
"#SetName": func(span otel.Span) { "#SetName": func(span trace.Span) {
span.SetName("new name") span.SetName("new name")
}, },
"#SetAttributes": func(span otel.Span) { "#SetAttributes": func(span trace.Span) {
span.SetAttributes(label.String("key1", "value"), label.Int("key2", 123)) span.SetAttributes(label.String("key1", "value"), label.Int("key2", 123))
}, },
} }
var mechanisms = map[string]func() otel.Span{ var mechanisms = map[string]func() trace.Span{
"Span created via Tracer#Start": func() otel.Span { "Span created via Tracer#Start": func() trace.Span {
tracer := tracerFactory() tracer := tracerFactory()
_, subject := tracer.Start(context.Background(), "test") _, subject := tracer.Start(context.Background(), "test")

View File

@ -17,7 +17,7 @@ package oteltest // import "go.opentelemetry.io/otel/oteltest"
import ( import (
"sync" "sync"
"go.opentelemetry.io/otel" "go.opentelemetry.io/otel/trace"
) )
// TracerProvider is a testing TracerProvider. It is an functioning // TracerProvider is a testing TracerProvider. It is an functioning
@ -31,7 +31,7 @@ type TracerProvider struct {
tracers map[instrumentation]*Tracer tracers map[instrumentation]*Tracer
} }
var _ otel.TracerProvider = (*TracerProvider)(nil) var _ trace.TracerProvider = (*TracerProvider)(nil)
// NewTracerProvider returns a *TracerProvider configured with options. // NewTracerProvider returns a *TracerProvider configured with options.
func NewTracerProvider(options ...Option) *TracerProvider { func NewTracerProvider(options ...Option) *TracerProvider {
@ -46,8 +46,8 @@ type instrumentation struct {
} }
// Tracer returns an OpenTelemetry Tracer used for testing. // Tracer returns an OpenTelemetry Tracer used for testing.
func (p *TracerProvider) Tracer(instName string, opts ...otel.TracerOption) otel.Tracer { func (p *TracerProvider) Tracer(instName string, opts ...trace.TracerOption) trace.Tracer {
conf := otel.NewTracerConfig(opts...) conf := trace.NewTracerConfig(opts...)
inst := instrumentation{ inst := instrumentation{
Name: instName, Name: instName,
@ -68,6 +68,6 @@ func (p *TracerProvider) Tracer(instName string, opts ...otel.TracerOption) otel
} }
// DefaulTracer returns a default tracer for testing purposes. // DefaulTracer returns a default tracer for testing purposes.
func DefaultTracer() otel.Tracer { func DefaultTracer() trace.Tracer {
return NewTracerProvider().Tracer("") return NewTracerProvider().Tracer("")
} }

View File

@ -20,9 +20,9 @@ import (
"sync" "sync"
"time" "time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
"go.opentelemetry.io/otel/trace"
) )
const ( const (
@ -31,14 +31,14 @@ const (
errorEventName = "error" errorEventName = "error"
) )
var _ otel.Span = (*Span)(nil) var _ trace.Span = (*Span)(nil)
// Span is an OpenTelemetry Span used for testing. // Span is an OpenTelemetry Span used for testing.
type Span struct { type Span struct {
lock sync.RWMutex lock sync.RWMutex
tracer *Tracer tracer *Tracer
spanContext otel.SpanContext spanContext trace.SpanContext
parentSpanID otel.SpanID parentSpanID trace.SpanID
ended bool ended bool
name string name string
startTime time.Time startTime time.Time
@ -47,19 +47,19 @@ type Span struct {
statusMessage string statusMessage string
attributes map[label.Key]label.Value attributes map[label.Key]label.Value
events []Event events []Event
links map[otel.SpanContext][]label.KeyValue links map[trace.SpanContext][]label.KeyValue
spanKind otel.SpanKind spanKind trace.SpanKind
} }
// Tracer returns the Tracer that created s. // Tracer returns the Tracer that created s.
func (s *Span) Tracer() otel.Tracer { func (s *Span) Tracer() trace.Tracer {
return s.tracer return s.tracer
} }
// End ends s. If the Tracer that created s was configured with a // End ends s. If the Tracer that created s was configured with a
// SpanRecorder, that recorder's OnEnd method is called as the final part of // SpanRecorder, that recorder's OnEnd method is called as the final part of
// this method. // this method.
func (s *Span) End(opts ...otel.SpanOption) { func (s *Span) End(opts ...trace.SpanOption) {
s.lock.Lock() s.lock.Lock()
defer s.lock.Unlock() defer s.lock.Unlock()
@ -67,7 +67,7 @@ func (s *Span) End(opts ...otel.SpanOption) {
return return
} }
c := otel.NewSpanConfig(opts...) c := trace.NewSpanConfig(opts...)
s.endTime = time.Now() s.endTime = time.Now()
if endTime := c.Timestamp; !endTime.IsZero() { if endTime := c.Timestamp; !endTime.IsZero() {
s.endTime = endTime s.endTime = endTime
@ -80,7 +80,7 @@ func (s *Span) End(opts ...otel.SpanOption) {
} }
// RecordError records an error as a Span event. // RecordError records an error as a Span event.
func (s *Span) RecordError(err error, opts ...otel.EventOption) { func (s *Span) RecordError(err error, opts ...trace.EventOption) {
if err == nil || s.ended { if err == nil || s.ended {
return return
} }
@ -92,7 +92,7 @@ func (s *Span) RecordError(err error, opts ...otel.EventOption) {
} }
s.SetStatus(codes.Error, "") s.SetStatus(codes.Error, "")
opts = append(opts, otel.WithAttributes( opts = append(opts, trace.WithAttributes(
errorTypeKey.String(errTypeString), errorTypeKey.String(errTypeString),
errorMessageKey.String(err.Error()), errorMessageKey.String(err.Error()),
)) ))
@ -101,7 +101,7 @@ func (s *Span) RecordError(err error, opts ...otel.EventOption) {
} }
// AddEvent adds an event to s. // AddEvent adds an event to s.
func (s *Span) AddEvent(name string, o ...otel.EventOption) { func (s *Span) AddEvent(name string, o ...trace.EventOption) {
s.lock.Lock() s.lock.Lock()
defer s.lock.Unlock() defer s.lock.Unlock()
@ -109,7 +109,7 @@ func (s *Span) AddEvent(name string, o ...otel.EventOption) {
return return
} }
c := otel.NewEventConfig(o...) c := trace.NewEventConfig(o...)
var attributes map[label.Key]label.Value var attributes map[label.Key]label.Value
if l := len(c.Attributes); l > 0 { if l := len(c.Attributes); l > 0 {
@ -132,7 +132,7 @@ func (s *Span) IsRecording() bool {
} }
// SpanContext returns the SpanContext of s. // SpanContext returns the SpanContext of s.
func (s *Span) SpanContext() otel.SpanContext { func (s *Span) SpanContext() trace.SpanContext {
return s.spanContext return s.spanContext
} }
@ -182,7 +182,7 @@ func (s *Span) Name() string { return s.name }
// ParentSpanID returns the SpanID of the parent Span. If s is a root Span, // ParentSpanID returns the SpanID of the parent Span. If s is a root Span,
// and therefore does not have a parent, the returned SpanID will be invalid // and therefore does not have a parent, the returned SpanID will be invalid
// (i.e., it will contain all zeroes). // (i.e., it will contain all zeroes).
func (s *Span) ParentSpanID() otel.SpanID { return s.parentSpanID } func (s *Span) ParentSpanID() trace.SpanID { return s.parentSpanID }
// Attributes returns the attributes set on s, either at or after creation // Attributes returns the attributes set on s, either at or after creation
// time. If the same attribute key was set multiple times, the last call will // time. If the same attribute key was set multiple times, the last call will
@ -206,8 +206,8 @@ func (s *Span) Events() []Event { return s.events }
// Links returns the links set on s at creation time. If multiple links for // Links returns the links set on s at creation time. If multiple links for
// the same SpanContext were set, the last link will be used. // the same SpanContext were set, the last link will be used.
func (s *Span) Links() map[otel.SpanContext][]label.KeyValue { func (s *Span) Links() map[trace.SpanContext][]label.KeyValue {
links := make(map[otel.SpanContext][]label.KeyValue) links := make(map[trace.SpanContext][]label.KeyValue)
for sc, attributes := range s.links { for sc, attributes := range s.links {
links[sc] = append([]label.KeyValue{}, attributes...) links[sc] = append([]label.KeyValue{}, attributes...)
@ -239,4 +239,4 @@ func (s *Span) StatusCode() codes.Code { return s.statusCode }
func (s *Span) StatusMessage() string { return s.statusMessage } func (s *Span) StatusMessage() string { return s.statusMessage }
// SpanKind returns the span kind of s. // SpanKind returns the span kind of s.
func (s *Span) SpanKind() otel.SpanKind { return s.spanKind } func (s *Span) SpanKind() trace.SpanKind { return s.spanKind }

View File

@ -22,12 +22,12 @@ import (
"testing" "testing"
"time" "time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/internal/matchers" "go.opentelemetry.io/otel/internal/matchers"
ottest "go.opentelemetry.io/otel/internal/testing" ottest "go.opentelemetry.io/otel/internal/testing"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
"go.opentelemetry.io/otel/oteltest" "go.opentelemetry.io/otel/oteltest"
"go.opentelemetry.io/otel/trace"
) )
func TestSpan(t *testing.T) { func TestSpan(t *testing.T) {
@ -113,7 +113,7 @@ func TestSpan(t *testing.T) {
e.Expect(ok).ToBeTrue() e.Expect(ok).ToBeTrue()
expectedEndTime := time.Now().AddDate(5, 0, 0) expectedEndTime := time.Now().AddDate(5, 0, 0)
subject.End(otel.WithTimestamp(expectedEndTime)) subject.End(trace.WithTimestamp(expectedEndTime))
e.Expect(subject.Ended()).ToBeTrue() e.Expect(subject.Ended()).ToBeTrue()
@ -156,7 +156,7 @@ func TestSpan(t *testing.T) {
e.Expect(ok).ToBeTrue() e.Expect(ok).ToBeTrue()
testTime := time.Now() testTime := time.Now()
subject.RecordError(s.err, otel.WithTimestamp(testTime)) subject.RecordError(s.err, trace.WithTimestamp(testTime))
expectedEvents := []oteltest.Event{{ expectedEvents := []oteltest.Event{{
Timestamp: testTime, Timestamp: testTime,
@ -186,7 +186,7 @@ func TestSpan(t *testing.T) {
errMsg := "test error message" errMsg := "test error message"
testErr := ottest.NewTestError(errMsg) testErr := ottest.NewTestError(errMsg)
testTime := time.Now() testTime := time.Now()
subject.RecordError(testErr, otel.WithTimestamp(testTime)) subject.RecordError(testErr, trace.WithTimestamp(testTime))
expectedEvents := []oteltest.Event{{ expectedEvents := []oteltest.Event{{
Timestamp: testTime, Timestamp: testTime,
@ -464,7 +464,7 @@ func TestSpan(t *testing.T) {
} }
event1Start := time.Now() event1Start := time.Now()
subject.AddEvent(event1Name, otel.WithAttributes(event1Attributes...)) subject.AddEvent(event1Name, trace.WithAttributes(event1Attributes...))
event1End := time.Now() event1End := time.Now()
event2Timestamp := time.Now().AddDate(5, 0, 0) event2Timestamp := time.Now().AddDate(5, 0, 0)
@ -473,7 +473,7 @@ func TestSpan(t *testing.T) {
label.String("event2Attr", "abc"), label.String("event2Attr", "abc"),
} }
subject.AddEvent(event2Name, otel.WithTimestamp(event2Timestamp), otel.WithAttributes(event2Attributes...)) subject.AddEvent(event2Name, trace.WithTimestamp(event2Timestamp), trace.WithAttributes(event2Attributes...))
events := subject.Events() events := subject.Events()
@ -601,13 +601,13 @@ func TestSpan(t *testing.T) {
tracer := tp.Tracer(t.Name()) tracer := tp.Tracer(t.Name())
_, span := tracer.Start(context.Background(), "test", _, span := tracer.Start(context.Background(), "test",
otel.WithSpanKind(otel.SpanKindConsumer)) trace.WithSpanKind(trace.SpanKindConsumer))
subject, ok := span.(*oteltest.Span) subject, ok := span.(*oteltest.Span)
e.Expect(ok).ToBeTrue() e.Expect(ok).ToBeTrue()
subject.End() subject.End()
e.Expect(subject.SpanKind()).ToEqual(otel.SpanKindConsumer) e.Expect(subject.SpanKind()).ToEqual(trace.SpanKindConsumer)
}) })
}) })
} }

View File

@ -18,11 +18,11 @@ import (
"context" "context"
"time" "time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
"go.opentelemetry.io/otel/trace"
) )
var _ otel.Tracer = (*Tracer)(nil) var _ trace.Tracer = (*Tracer)(nil)
// Tracer is an OpenTelemetry Tracer implementation used for testing. // Tracer is an OpenTelemetry Tracer implementation used for testing.
type Tracer struct { type Tracer struct {
@ -36,8 +36,8 @@ type Tracer struct {
// Start creates a span. If t is configured with a SpanRecorder its OnStart // Start creates a span. If t is configured with a SpanRecorder its OnStart
// method will be called after the created Span has been initialized. // method will be called after the created Span has been initialized.
func (t *Tracer) Start(ctx context.Context, name string, opts ...otel.SpanOption) (context.Context, otel.Span) { func (t *Tracer) Start(ctx context.Context, name string, opts ...trace.SpanOption) (context.Context, trace.Span) {
c := otel.NewSpanConfig(opts...) c := trace.NewSpanConfig(opts...)
startTime := time.Now() startTime := time.Now()
if st := c.Timestamp; !st.IsZero() { if st := c.Timestamp; !st.IsZero() {
startTime = st startTime = st
@ -47,26 +47,26 @@ func (t *Tracer) Start(ctx context.Context, name string, opts ...otel.SpanOption
tracer: t, tracer: t,
startTime: startTime, startTime: startTime,
attributes: make(map[label.Key]label.Value), attributes: make(map[label.Key]label.Value),
links: make(map[otel.SpanContext][]label.KeyValue), links: make(map[trace.SpanContext][]label.KeyValue),
spanKind: c.SpanKind, spanKind: c.SpanKind,
} }
if c.NewRoot { if c.NewRoot {
span.spanContext = otel.SpanContext{} span.spanContext = trace.SpanContext{}
iodKey := label.Key("ignored-on-demand") iodKey := label.Key("ignored-on-demand")
if lsc := otel.SpanContextFromContext(ctx); lsc.IsValid() { if lsc := trace.SpanContextFromContext(ctx); lsc.IsValid() {
span.links[lsc] = []label.KeyValue{iodKey.String("current")} span.links[lsc] = []label.KeyValue{iodKey.String("current")}
} }
if rsc := otel.RemoteSpanContextFromContext(ctx); rsc.IsValid() { if rsc := trace.RemoteSpanContextFromContext(ctx); rsc.IsValid() {
span.links[rsc] = []label.KeyValue{iodKey.String("remote")} span.links[rsc] = []label.KeyValue{iodKey.String("remote")}
} }
} else { } else {
span.spanContext = t.config.SpanContextFunc(ctx) span.spanContext = t.config.SpanContextFunc(ctx)
if lsc := otel.SpanContextFromContext(ctx); lsc.IsValid() { if lsc := trace.SpanContextFromContext(ctx); lsc.IsValid() {
span.spanContext.TraceID = lsc.TraceID span.spanContext.TraceID = lsc.TraceID
span.parentSpanID = lsc.SpanID span.parentSpanID = lsc.SpanID
} else if rsc := otel.RemoteSpanContextFromContext(ctx); rsc.IsValid() { } else if rsc := trace.RemoteSpanContextFromContext(ctx); rsc.IsValid() {
span.spanContext.TraceID = rsc.TraceID span.spanContext.TraceID = rsc.TraceID
span.parentSpanID = rsc.SpanID span.parentSpanID = rsc.SpanID
} }
@ -82,5 +82,5 @@ func (t *Tracer) Start(ctx context.Context, name string, opts ...otel.SpanOption
if t.config.SpanRecorder != nil { if t.config.SpanRecorder != nil {
t.config.SpanRecorder.OnStart(span) t.config.SpanRecorder.OnStart(span)
} }
return otel.ContextWithSpan(ctx, span), span return trace.ContextWithSpan(ctx, span), span
} }

View File

@ -22,25 +22,25 @@ import (
"testing" "testing"
"time" "time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/internal/matchers" "go.opentelemetry.io/otel/internal/matchers"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
"go.opentelemetry.io/otel/oteltest" "go.opentelemetry.io/otel/oteltest"
"go.opentelemetry.io/otel/trace"
) )
func TestTracer(t *testing.T) { func TestTracer(t *testing.T) {
tp := oteltest.NewTracerProvider() tp := oteltest.NewTracerProvider()
oteltest.NewHarness(t).TestTracer(func() func() otel.Tracer { oteltest.NewHarness(t).TestTracer(func() func() trace.Tracer {
tp := oteltest.NewTracerProvider() tp := oteltest.NewTracerProvider()
var i uint64 var i uint64
return func() otel.Tracer { return func() trace.Tracer {
return tp.Tracer(fmt.Sprintf("tracer %d", atomic.AddUint64(&i, 1))) return tp.Tracer(fmt.Sprintf("tracer %d", atomic.AddUint64(&i, 1)))
} }
}()) }())
t.Run("#Start", func(t *testing.T) { t.Run("#Start", func(t *testing.T) {
testTracedSpan(t, func(tracer otel.Tracer, name string) (otel.Span, error) { testTracedSpan(t, func(tracer trace.Tracer, name string) (trace.Span, error) {
_, span := tracer.Start(context.Background(), name) _, span := tracer.Start(context.Background(), name)
return span, nil return span, nil
@ -54,7 +54,7 @@ func TestTracer(t *testing.T) {
expectedStartTime := time.Now().AddDate(5, 0, 0) expectedStartTime := time.Now().AddDate(5, 0, 0)
subject := tp.Tracer(t.Name()) subject := tp.Tracer(t.Name())
_, span := subject.Start(context.Background(), "test", otel.WithTimestamp(expectedStartTime)) _, span := subject.Start(context.Background(), "test", trace.WithTimestamp(expectedStartTime))
testSpan, ok := span.(*oteltest.Span) testSpan, ok := span.(*oteltest.Span)
e.Expect(ok).ToBeTrue() e.Expect(ok).ToBeTrue()
@ -71,7 +71,7 @@ func TestTracer(t *testing.T) {
attr2 := label.String("b", "2") attr2 := label.String("b", "2")
subject := tp.Tracer(t.Name()) subject := tp.Tracer(t.Name())
_, span := subject.Start(context.Background(), "test", otel.WithAttributes(attr1, attr2)) _, span := subject.Start(context.Background(), "test", trace.WithAttributes(attr1, attr2))
testSpan, ok := span.(*oteltest.Span) testSpan, ok := span.(*oteltest.Span)
e.Expect(ok).ToBeTrue() e.Expect(ok).ToBeTrue()
@ -111,7 +111,7 @@ func TestTracer(t *testing.T) {
parent, parentSpan := subject.Start(context.Background(), "parent") parent, parentSpan := subject.Start(context.Background(), "parent")
_, remoteParentSpan := subject.Start(context.Background(), "remote not-a-parent") _, remoteParentSpan := subject.Start(context.Background(), "remote not-a-parent")
parent = otel.ContextWithRemoteSpanContext(parent, remoteParentSpan.SpanContext()) parent = trace.ContextWithRemoteSpanContext(parent, remoteParentSpan.SpanContext())
parentSpanContext := parentSpan.SpanContext() parentSpanContext := parentSpan.SpanContext()
_, span := subject.Start(parent, "child") _, span := subject.Start(parent, "child")
@ -133,7 +133,7 @@ func TestTracer(t *testing.T) {
subject := tp.Tracer(t.Name()) subject := tp.Tracer(t.Name())
_, remoteParentSpan := subject.Start(context.Background(), "remote parent") _, remoteParentSpan := subject.Start(context.Background(), "remote parent")
parent := otel.ContextWithRemoteSpanContext(context.Background(), remoteParentSpan.SpanContext()) parent := trace.ContextWithRemoteSpanContext(context.Background(), remoteParentSpan.SpanContext())
remoteParentSpanContext := remoteParentSpan.SpanContext() remoteParentSpanContext := remoteParentSpan.SpanContext()
_, span := subject.Start(parent, "child") _, span := subject.Start(parent, "child")
@ -183,9 +183,9 @@ func TestTracer(t *testing.T) {
_, remoteParentSpan := subject.Start(context.Background(), "remote not-a-parent") _, remoteParentSpan := subject.Start(context.Background(), "remote not-a-parent")
parentSpanContext := parentSpan.SpanContext() parentSpanContext := parentSpan.SpanContext()
remoteParentSpanContext := remoteParentSpan.SpanContext() remoteParentSpanContext := remoteParentSpan.SpanContext()
parentCtx = otel.ContextWithRemoteSpanContext(parentCtx, remoteParentSpanContext) parentCtx = trace.ContextWithRemoteSpanContext(parentCtx, remoteParentSpanContext)
_, span := subject.Start(parentCtx, "child", otel.WithNewRoot()) _, span := subject.Start(parentCtx, "child", trace.WithNewRoot())
testSpan, ok := span.(*oteltest.Span) testSpan, ok := span.(*oteltest.Span)
e.Expect(ok).ToBeTrue() e.Expect(ok).ToBeTrue()
@ -197,7 +197,7 @@ func TestTracer(t *testing.T) {
e.Expect(childSpanContext.SpanID).NotToEqual(remoteParentSpanContext.SpanID) e.Expect(childSpanContext.SpanID).NotToEqual(remoteParentSpanContext.SpanID)
e.Expect(testSpan.ParentSpanID().IsValid()).ToBeFalse() e.Expect(testSpan.ParentSpanID().IsValid()).ToBeFalse()
expectedLinks := []otel.Link{ expectedLinks := []trace.Link{
{ {
SpanContext: parentSpanContext, SpanContext: parentSpanContext,
Attributes: []label.KeyValue{ Attributes: []label.KeyValue{
@ -212,9 +212,9 @@ func TestTracer(t *testing.T) {
}, },
} }
tsLinks := testSpan.Links() tsLinks := testSpan.Links()
gotLinks := make([]otel.Link, 0, len(tsLinks)) gotLinks := make([]trace.Link, 0, len(tsLinks))
for sc, attributes := range tsLinks { for sc, attributes := range tsLinks {
gotLinks = append(gotLinks, otel.Link{ gotLinks = append(gotLinks, trace.Link{
SpanContext: sc, SpanContext: sc,
Attributes: attributes, Attributes: attributes,
}) })
@ -230,7 +230,7 @@ func TestTracer(t *testing.T) {
subject := tp.Tracer(t.Name()) subject := tp.Tracer(t.Name())
_, span := subject.Start(context.Background(), "link1") _, span := subject.Start(context.Background(), "link1")
link1 := otel.Link{ link1 := trace.Link{
SpanContext: span.SpanContext(), SpanContext: span.SpanContext(),
Attributes: []label.KeyValue{ Attributes: []label.KeyValue{
label.String("a", "1"), label.String("a", "1"),
@ -238,14 +238,14 @@ func TestTracer(t *testing.T) {
} }
_, span = subject.Start(context.Background(), "link2") _, span = subject.Start(context.Background(), "link2")
link2 := otel.Link{ link2 := trace.Link{
SpanContext: span.SpanContext(), SpanContext: span.SpanContext(),
Attributes: []label.KeyValue{ Attributes: []label.KeyValue{
label.String("b", "2"), label.String("b", "2"),
}, },
} }
_, span = subject.Start(context.Background(), "test", otel.WithLinks(link1, link2)) _, span = subject.Start(context.Background(), "test", trace.WithLinks(link1, link2))
testSpan, ok := span.(*oteltest.Span) testSpan, ok := span.(*oteltest.Span)
e.Expect(ok).ToBeTrue() e.Expect(ok).ToBeTrue()
@ -257,7 +257,7 @@ func TestTracer(t *testing.T) {
}) })
} }
func testTracedSpan(t *testing.T, fn func(tracer otel.Tracer, name string) (otel.Span, error)) { func testTracedSpan(t *testing.T, fn func(tracer trace.Tracer, name string) (trace.Span, error)) {
tp := oteltest.NewTracerProvider() tp := oteltest.NewTracerProvider()
t.Run("starts a span with the expected name", func(t *testing.T) { t.Run("starts a span with the expected name", func(t *testing.T) {
t.Parallel() t.Parallel()

View File

@ -23,6 +23,7 @@ import (
"go.opentelemetry.io/otel" "go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/propagators" "go.opentelemetry.io/otel/propagators"
"go.opentelemetry.io/otel/trace"
) )
const ( const (
@ -35,18 +36,18 @@ var (
spanID = mustSpanIDFromHex(spanIDStr) spanID = mustSpanIDFromHex(spanIDStr)
) )
func mustTraceIDFromHex(s string) (t otel.TraceID) { func mustTraceIDFromHex(s string) (t trace.TraceID) {
var err error var err error
t, err = otel.TraceIDFromHex(s) t, err = trace.TraceIDFromHex(s)
if err != nil { if err != nil {
panic(err) panic(err)
} }
return return
} }
func mustSpanIDFromHex(s string) (t otel.SpanID) { func mustSpanIDFromHex(s string) (t trace.SpanID) {
var err error var err error
t, err = otel.SpanIDFromHex(s) t, err = trace.SpanIDFromHex(s)
if err != nil { if err != nil {
panic(err) panic(err)
} }
@ -60,13 +61,13 @@ type outOfThinAirPropagator struct {
var _ otel.TextMapPropagator = outOfThinAirPropagator{} var _ otel.TextMapPropagator = outOfThinAirPropagator{}
func (p outOfThinAirPropagator) Extract(ctx context.Context, carrier otel.TextMapCarrier) context.Context { func (p outOfThinAirPropagator) Extract(ctx context.Context, carrier otel.TextMapCarrier) context.Context {
sc := otel.SpanContext{ sc := trace.SpanContext{
TraceID: traceID, TraceID: traceID,
SpanID: spanID, SpanID: spanID,
TraceFlags: 0, TraceFlags: 0,
} }
require.True(p.t, sc.IsValid()) require.True(p.t, sc.IsValid())
return otel.ContextWithRemoteSpanContext(ctx, sc) return trace.ContextWithRemoteSpanContext(ctx, sc)
} }
func (outOfThinAirPropagator) Inject(context.Context, otel.TextMapCarrier) {} func (outOfThinAirPropagator) Inject(context.Context, otel.TextMapCarrier) {}
@ -96,7 +97,7 @@ func TestMultiplePropagators(t *testing.T) {
// generates the valid span context out of thin air // generates the valid span context out of thin air
{ {
ctx := ootaProp.Extract(bg, ns) ctx := ootaProp.Extract(bg, ns)
sc := otel.RemoteSpanContextFromContext(ctx) sc := trace.RemoteSpanContextFromContext(ctx)
require.True(t, sc.IsValid(), "oota prop failed sanity check") require.True(t, sc.IsValid(), "oota prop failed sanity check")
} }
// sanity check for real propagators, ensuring that they // sanity check for real propagators, ensuring that they
@ -104,13 +105,13 @@ func TestMultiplePropagators(t *testing.T) {
// go context in absence of the HTTP headers. // go context in absence of the HTTP headers.
for _, prop := range testProps { for _, prop := range testProps {
ctx := prop.Extract(bg, ns) ctx := prop.Extract(bg, ns)
sc := otel.RemoteSpanContextFromContext(ctx) sc := trace.RemoteSpanContextFromContext(ctx)
require.Falsef(t, sc.IsValid(), "%#v failed sanity check", prop) require.Falsef(t, sc.IsValid(), "%#v failed sanity check", prop)
} }
for _, prop := range testProps { for _, prop := range testProps {
props := otel.NewCompositeTextMapPropagator(ootaProp, prop) props := otel.NewCompositeTextMapPropagator(ootaProp, prop)
ctx := props.Extract(bg, ns) ctx := props.Extract(bg, ns)
sc := otel.RemoteSpanContextFromContext(ctx) sc := trace.RemoteSpanContextFromContext(ctx)
assert.Truef(t, sc.IsValid(), "%#v clobbers span context", prop) assert.Truef(t, sc.IsValid(), "%#v clobbers span context", prop)
} }
} }

View File

@ -21,6 +21,7 @@ import (
"regexp" "regexp"
"go.opentelemetry.io/otel" "go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
) )
const ( const (
@ -56,7 +57,7 @@ func (tc TraceContext) Inject(ctx context.Context, carrier otel.TextMapCarrier)
carrier.Set(tracestateHeader, state) carrier.Set(tracestateHeader, state)
} }
sc := otel.SpanContextFromContext(ctx) sc := trace.SpanContextFromContext(ctx)
if !sc.IsValid() { if !sc.IsValid() {
return return
} }
@ -64,7 +65,7 @@ func (tc TraceContext) Inject(ctx context.Context, carrier otel.TextMapCarrier)
supportedVersion, supportedVersion,
sc.TraceID, sc.TraceID,
sc.SpanID, sc.SpanID,
sc.TraceFlags&otel.FlagsSampled) sc.TraceFlags&trace.FlagsSampled)
carrier.Set(traceparentHeader, h) carrier.Set(traceparentHeader, h)
} }
@ -79,72 +80,72 @@ func (tc TraceContext) Extract(ctx context.Context, carrier otel.TextMapCarrier)
if !sc.IsValid() { if !sc.IsValid() {
return ctx return ctx
} }
return otel.ContextWithRemoteSpanContext(ctx, sc) return trace.ContextWithRemoteSpanContext(ctx, sc)
} }
func (tc TraceContext) extract(carrier otel.TextMapCarrier) otel.SpanContext { func (tc TraceContext) extract(carrier otel.TextMapCarrier) trace.SpanContext {
h := carrier.Get(traceparentHeader) h := carrier.Get(traceparentHeader)
if h == "" { if h == "" {
return otel.SpanContext{} return trace.SpanContext{}
} }
matches := traceCtxRegExp.FindStringSubmatch(h) matches := traceCtxRegExp.FindStringSubmatch(h)
if len(matches) == 0 { if len(matches) == 0 {
return otel.SpanContext{} return trace.SpanContext{}
} }
if len(matches) < 5 { // four subgroups plus the overall match if len(matches) < 5 { // four subgroups plus the overall match
return otel.SpanContext{} return trace.SpanContext{}
} }
if len(matches[1]) != 2 { if len(matches[1]) != 2 {
return otel.SpanContext{} return trace.SpanContext{}
} }
ver, err := hex.DecodeString(matches[1]) ver, err := hex.DecodeString(matches[1])
if err != nil { if err != nil {
return otel.SpanContext{} return trace.SpanContext{}
} }
version := int(ver[0]) version := int(ver[0])
if version > maxVersion { if version > maxVersion {
return otel.SpanContext{} return trace.SpanContext{}
} }
if version == 0 && len(matches) != 5 { // four subgroups plus the overall match if version == 0 && len(matches) != 5 { // four subgroups plus the overall match
return otel.SpanContext{} return trace.SpanContext{}
} }
if len(matches[2]) != 32 { if len(matches[2]) != 32 {
return otel.SpanContext{} return trace.SpanContext{}
} }
var sc otel.SpanContext var sc trace.SpanContext
sc.TraceID, err = otel.TraceIDFromHex(matches[2][:32]) sc.TraceID, err = trace.TraceIDFromHex(matches[2][:32])
if err != nil { if err != nil {
return otel.SpanContext{} return trace.SpanContext{}
} }
if len(matches[3]) != 16 { if len(matches[3]) != 16 {
return otel.SpanContext{} return trace.SpanContext{}
} }
sc.SpanID, err = otel.SpanIDFromHex(matches[3]) sc.SpanID, err = trace.SpanIDFromHex(matches[3])
if err != nil { if err != nil {
return otel.SpanContext{} return trace.SpanContext{}
} }
if len(matches[4]) != 2 { if len(matches[4]) != 2 {
return otel.SpanContext{} return trace.SpanContext{}
} }
opts, err := hex.DecodeString(matches[4]) opts, err := hex.DecodeString(matches[4])
if err != nil || len(opts) < 1 || (version == 0 && opts[0] > 2) { if err != nil || len(opts) < 1 || (version == 0 && opts[0] > 2) {
return otel.SpanContext{} return trace.SpanContext{}
} }
// Clear all flags other than the trace-context supported sampling bit. // Clear all flags other than the trace-context supported sampling bit.
sc.TraceFlags = opts[0] & otel.FlagsSampled sc.TraceFlags = opts[0] & trace.FlagsSampled
if !sc.IsValid() { if !sc.IsValid() {
return otel.SpanContext{} return trace.SpanContext{}
} }
return sc return sc

View File

@ -19,9 +19,9 @@ import (
"net/http" "net/http"
"testing" "testing"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/oteltest" "go.opentelemetry.io/otel/oteltest"
"go.opentelemetry.io/otel/propagators" "go.opentelemetry.io/otel/propagators"
"go.opentelemetry.io/otel/trace"
) )
func BenchmarkInject(b *testing.B) { func BenchmarkInject(b *testing.B) {
@ -38,17 +38,17 @@ func BenchmarkInject(b *testing.B) {
func injectSubBenchmarks(b *testing.B, fn func(context.Context, *testing.B)) { func injectSubBenchmarks(b *testing.B, fn func(context.Context, *testing.B)) {
b.Run("SampledSpanContext", func(b *testing.B) { b.Run("SampledSpanContext", func(b *testing.B) {
spanID, _ := otel.SpanIDFromHex("00f067aa0ba902b7") spanID, _ := trace.SpanIDFromHex("00f067aa0ba902b7")
traceID, _ := otel.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736") traceID, _ := trace.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736")
mockTracer := oteltest.DefaultTracer() mockTracer := oteltest.DefaultTracer()
b.ReportAllocs() b.ReportAllocs()
sc := otel.SpanContext{ sc := trace.SpanContext{
TraceID: traceID, TraceID: traceID,
SpanID: spanID, SpanID: spanID,
TraceFlags: otel.FlagsSampled, TraceFlags: trace.FlagsSampled,
} }
ctx := otel.ContextWithRemoteSpanContext(context.Background(), sc) ctx := trace.ContextWithRemoteSpanContext(context.Background(), sc)
ctx, _ = mockTracer.Start(ctx, "inject") ctx, _ = mockTracer.Start(ctx, "inject")
fn(ctx, b) fn(ctx, b)
}) })

View File

@ -21,9 +21,9 @@ import (
"github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/oteltest" "go.opentelemetry.io/otel/oteltest"
"go.opentelemetry.io/otel/propagators" "go.opentelemetry.io/otel/propagators"
"go.opentelemetry.io/otel/trace"
) )
func TestExtractValidTraceContextFromHTTPReq(t *testing.T) { func TestExtractValidTraceContextFromHTTPReq(t *testing.T) {
@ -31,12 +31,12 @@ func TestExtractValidTraceContextFromHTTPReq(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
header string header string
wantSc otel.SpanContext wantSc trace.SpanContext
}{ }{
{ {
name: "valid w3cHeader", name: "valid w3cHeader",
header: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00", header: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00",
wantSc: otel.SpanContext{ wantSc: trace.SpanContext{
TraceID: traceID, TraceID: traceID,
SpanID: spanID, SpanID: spanID,
}, },
@ -44,34 +44,34 @@ func TestExtractValidTraceContextFromHTTPReq(t *testing.T) {
{ {
name: "valid w3cHeader and sampled", name: "valid w3cHeader and sampled",
header: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01", header: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
wantSc: otel.SpanContext{ wantSc: trace.SpanContext{
TraceID: traceID, TraceID: traceID,
SpanID: spanID, SpanID: spanID,
TraceFlags: otel.FlagsSampled, TraceFlags: trace.FlagsSampled,
}, },
}, },
{ {
name: "future version", name: "future version",
header: "02-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01", header: "02-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
wantSc: otel.SpanContext{ wantSc: trace.SpanContext{
TraceID: traceID, TraceID: traceID,
SpanID: spanID, SpanID: spanID,
TraceFlags: otel.FlagsSampled, TraceFlags: trace.FlagsSampled,
}, },
}, },
{ {
name: "future options with sampled bit set", name: "future options with sampled bit set",
header: "02-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-09", header: "02-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-09",
wantSc: otel.SpanContext{ wantSc: trace.SpanContext{
TraceID: traceID, TraceID: traceID,
SpanID: spanID, SpanID: spanID,
TraceFlags: otel.FlagsSampled, TraceFlags: trace.FlagsSampled,
}, },
}, },
{ {
name: "future options with sampled bit cleared", name: "future options with sampled bit cleared",
header: "02-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-08", header: "02-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-08",
wantSc: otel.SpanContext{ wantSc: trace.SpanContext{
TraceID: traceID, TraceID: traceID,
SpanID: spanID, SpanID: spanID,
}, },
@ -79,28 +79,28 @@ func TestExtractValidTraceContextFromHTTPReq(t *testing.T) {
{ {
name: "future additional data", name: "future additional data",
header: "02-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-09-XYZxsf09", header: "02-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-09-XYZxsf09",
wantSc: otel.SpanContext{ wantSc: trace.SpanContext{
TraceID: traceID, TraceID: traceID,
SpanID: spanID, SpanID: spanID,
TraceFlags: otel.FlagsSampled, TraceFlags: trace.FlagsSampled,
}, },
}, },
{ {
name: "valid b3Header ending in dash", name: "valid b3Header ending in dash",
header: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01-", header: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01-",
wantSc: otel.SpanContext{ wantSc: trace.SpanContext{
TraceID: traceID, TraceID: traceID,
SpanID: spanID, SpanID: spanID,
TraceFlags: otel.FlagsSampled, TraceFlags: trace.FlagsSampled,
}, },
}, },
{ {
name: "future valid b3Header ending in dash", name: "future valid b3Header ending in dash",
header: "01-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-09-", header: "01-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-09-",
wantSc: otel.SpanContext{ wantSc: trace.SpanContext{
TraceID: traceID, TraceID: traceID,
SpanID: spanID, SpanID: spanID,
TraceFlags: otel.FlagsSampled, TraceFlags: trace.FlagsSampled,
}, },
}, },
} }
@ -112,7 +112,7 @@ func TestExtractValidTraceContextFromHTTPReq(t *testing.T) {
ctx := context.Background() ctx := context.Background()
ctx = prop.Extract(ctx, req.Header) ctx = prop.Extract(ctx, req.Header)
gotSc := otel.RemoteSpanContextFromContext(ctx) gotSc := trace.RemoteSpanContextFromContext(ctx)
if diff := cmp.Diff(gotSc, tt.wantSc); diff != "" { if diff := cmp.Diff(gotSc, tt.wantSc); diff != "" {
t.Errorf("Extract Tracecontext: %s: -got +want %s", tt.name, diff) t.Errorf("Extract Tracecontext: %s: -got +want %s", tt.name, diff)
} }
@ -121,7 +121,7 @@ func TestExtractValidTraceContextFromHTTPReq(t *testing.T) {
} }
func TestExtractInvalidTraceContextFromHTTPReq(t *testing.T) { func TestExtractInvalidTraceContextFromHTTPReq(t *testing.T) {
wantSc := otel.SpanContext{} wantSc := trace.SpanContext{}
prop := propagators.TraceContext{} prop := propagators.TraceContext{}
tests := []struct { tests := []struct {
name string name string
@ -200,7 +200,7 @@ func TestExtractInvalidTraceContextFromHTTPReq(t *testing.T) {
ctx := context.Background() ctx := context.Background()
ctx = prop.Extract(ctx, req.Header) ctx = prop.Extract(ctx, req.Header)
gotSc := otel.RemoteSpanContextFromContext(ctx) gotSc := trace.RemoteSpanContextFromContext(ctx)
if diff := cmp.Diff(gotSc, wantSc); diff != "" { if diff := cmp.Diff(gotSc, wantSc); diff != "" {
t.Errorf("Extract Tracecontext: %s: -got +want %s", tt.name, diff) t.Errorf("Extract Tracecontext: %s: -got +want %s", tt.name, diff)
} }
@ -213,21 +213,21 @@ func TestInjectTraceContextToHTTPReq(t *testing.T) {
prop := propagators.TraceContext{} prop := propagators.TraceContext{}
tests := []struct { tests := []struct {
name string name string
sc otel.SpanContext sc trace.SpanContext
wantHeader string wantHeader string
}{ }{
{ {
name: "valid spancontext, sampled", name: "valid spancontext, sampled",
sc: otel.SpanContext{ sc: trace.SpanContext{
TraceID: traceID, TraceID: traceID,
SpanID: spanID, SpanID: spanID,
TraceFlags: otel.FlagsSampled, TraceFlags: trace.FlagsSampled,
}, },
wantHeader: "00-4bf92f3577b34da6a3ce929d0e0e4736-0000000000000002-01", wantHeader: "00-4bf92f3577b34da6a3ce929d0e0e4736-0000000000000002-01",
}, },
{ {
name: "valid spancontext, not sampled", name: "valid spancontext, not sampled",
sc: otel.SpanContext{ sc: trace.SpanContext{
TraceID: traceID, TraceID: traceID,
SpanID: spanID, SpanID: spanID,
}, },
@ -235,7 +235,7 @@ func TestInjectTraceContextToHTTPReq(t *testing.T) {
}, },
{ {
name: "valid spancontext, with unsupported bit set in traceflags", name: "valid spancontext, with unsupported bit set in traceflags",
sc: otel.SpanContext{ sc: trace.SpanContext{
TraceID: traceID, TraceID: traceID,
SpanID: spanID, SpanID: spanID,
TraceFlags: 0xff, TraceFlags: 0xff,
@ -244,7 +244,7 @@ func TestInjectTraceContextToHTTPReq(t *testing.T) {
}, },
{ {
name: "invalid spancontext", name: "invalid spancontext",
sc: otel.SpanContext{}, sc: trace.SpanContext{},
wantHeader: "", wantHeader: "",
}, },
} }
@ -253,7 +253,7 @@ func TestInjectTraceContextToHTTPReq(t *testing.T) {
req, _ := http.NewRequest("GET", "http://example.com", nil) req, _ := http.NewRequest("GET", "http://example.com", nil)
ctx := context.Background() ctx := context.Background()
if tt.sc.IsValid() { if tt.sc.IsValid() {
ctx = otel.ContextWithRemoteSpanContext(ctx, tt.sc) ctx = trace.ContextWithRemoteSpanContext(ctx, tt.sc)
ctx, _ = mockTracer.Start(ctx, "inject") ctx, _ = mockTracer.Start(ctx, "inject")
} }
prop.Inject(ctx, req.Header) prop.Inject(ctx, req.Header)

View File

@ -18,9 +18,10 @@ import (
"context" "context"
"time" "time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
"go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/otel/sdk/instrumentation" "go.opentelemetry.io/otel/sdk/instrumentation"
"go.opentelemetry.io/otel/sdk/resource" "go.opentelemetry.io/otel/sdk/resource"
) )
@ -49,9 +50,9 @@ type SpanExporter interface {
// SpanData contains all the information collected by a completed span. // SpanData contains all the information collected by a completed span.
type SpanData struct { type SpanData struct {
SpanContext otel.SpanContext SpanContext trace.SpanContext
ParentSpanID otel.SpanID ParentSpanID trace.SpanID
SpanKind otel.SpanKind SpanKind trace.SpanKind
Name string Name string
StartTime time.Time StartTime time.Time
// The wall clock time of EndTime will be adjusted to always be offset // The wall clock time of EndTime will be adjusted to always be offset
@ -59,7 +60,7 @@ type SpanData struct {
EndTime time.Time EndTime time.Time
Attributes []label.KeyValue Attributes []label.KeyValue
MessageEvents []Event MessageEvents []Event
Links []otel.Link Links []trace.Link
StatusCode codes.Code StatusCode codes.Code
StatusMessage string StatusMessage string
HasRemoteParent bool HasRemoteParent bool

View File

@ -21,7 +21,8 @@ import (
"testing" "testing"
"time" "time"
"go.opentelemetry.io/otel" "go.opentelemetry.io/otel/trace"
export "go.opentelemetry.io/otel/sdk/export/trace" export "go.opentelemetry.io/otel/sdk/export/trace"
sdktrace "go.opentelemetry.io/otel/sdk/trace" sdktrace "go.opentelemetry.io/otel/sdk/trace"
) )
@ -190,15 +191,15 @@ func createAndRegisterBatchSP(option testOption, te *testBatchExporter) *sdktrac
return sdktrace.NewBatchSpanProcessor(te, options...) return sdktrace.NewBatchSpanProcessor(te, options...)
} }
func generateSpan(t *testing.T, parallel bool, tr otel.Tracer, option testOption) { func generateSpan(t *testing.T, parallel bool, tr trace.Tracer, option testOption) {
sc := getSpanContext() sc := getSpanContext()
wg := &sync.WaitGroup{} wg := &sync.WaitGroup{}
for i := 0; i < option.genNumSpans; i++ { for i := 0; i < option.genNumSpans; i++ {
binary.BigEndian.PutUint64(sc.TraceID[0:8], uint64(i+1)) binary.BigEndian.PutUint64(sc.TraceID[0:8], uint64(i+1))
wg.Add(1) wg.Add(1)
f := func(sc otel.SpanContext) { f := func(sc trace.SpanContext) {
ctx := otel.ContextWithRemoteSpanContext(context.Background(), sc) ctx := trace.ContextWithRemoteSpanContext(context.Background(), sc)
_, span := tr.Start(ctx, option.name) _, span := tr.Start(ctx, option.name)
span.End() span.End()
wg.Done() wg.Done()
@ -212,10 +213,10 @@ func generateSpan(t *testing.T, parallel bool, tr otel.Tracer, option testOption
wg.Wait() wg.Wait()
} }
func getSpanContext() otel.SpanContext { func getSpanContext() trace.SpanContext {
tid, _ := otel.TraceIDFromHex("01020304050607080102040810203040") tid, _ := trace.TraceIDFromHex("01020304050607080102040810203040")
sid, _ := otel.SpanIDFromHex("0102040810203040") sid, _ := trace.SpanIDFromHex("0102040810203040")
return otel.SpanContext{ return trace.SpanContext{
TraceID: tid, TraceID: tid,
SpanID: sid, SpanID: sid,
TraceFlags: 0x1, TraceFlags: 0x1,

View File

@ -18,13 +18,14 @@ import (
"context" "context"
"testing" "testing"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
"go.opentelemetry.io/otel/trace"
sdktrace "go.opentelemetry.io/otel/sdk/trace" sdktrace "go.opentelemetry.io/otel/sdk/trace"
) )
func BenchmarkStartEndSpan(b *testing.B) { func BenchmarkStartEndSpan(b *testing.B) {
traceBenchmark(b, "Benchmark StartEndSpan", func(b *testing.B, t otel.Tracer) { traceBenchmark(b, "Benchmark StartEndSpan", func(b *testing.B, t trace.Tracer) {
ctx := context.Background() ctx := context.Background()
b.ResetTimer() b.ResetTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
@ -35,7 +36,7 @@ func BenchmarkStartEndSpan(b *testing.B) {
} }
func BenchmarkSpanWithAttributes_4(b *testing.B) { func BenchmarkSpanWithAttributes_4(b *testing.B) {
traceBenchmark(b, "Benchmark Start With 4 Attributes", func(b *testing.B, t otel.Tracer) { traceBenchmark(b, "Benchmark Start With 4 Attributes", func(b *testing.B, t trace.Tracer) {
ctx := context.Background() ctx := context.Background()
b.ResetTimer() b.ResetTimer()
@ -53,7 +54,7 @@ func BenchmarkSpanWithAttributes_4(b *testing.B) {
} }
func BenchmarkSpanWithAttributes_8(b *testing.B) { func BenchmarkSpanWithAttributes_8(b *testing.B) {
traceBenchmark(b, "Benchmark Start With 8 Attributes", func(b *testing.B, t otel.Tracer) { traceBenchmark(b, "Benchmark Start With 8 Attributes", func(b *testing.B, t trace.Tracer) {
ctx := context.Background() ctx := context.Background()
b.ResetTimer() b.ResetTimer()
@ -75,7 +76,7 @@ func BenchmarkSpanWithAttributes_8(b *testing.B) {
} }
func BenchmarkSpanWithAttributes_all(b *testing.B) { func BenchmarkSpanWithAttributes_all(b *testing.B) {
traceBenchmark(b, "Benchmark Start With all Attribute types", func(b *testing.B, t otel.Tracer) { traceBenchmark(b, "Benchmark Start With all Attribute types", func(b *testing.B, t trace.Tracer) {
ctx := context.Background() ctx := context.Background()
b.ResetTimer() b.ResetTimer()
@ -99,7 +100,7 @@ func BenchmarkSpanWithAttributes_all(b *testing.B) {
} }
func BenchmarkSpanWithAttributes_all_2x(b *testing.B) { func BenchmarkSpanWithAttributes_all_2x(b *testing.B) {
traceBenchmark(b, "Benchmark Start With all Attributes types twice", func(b *testing.B, t otel.Tracer) { traceBenchmark(b, "Benchmark Start With all Attributes types twice", func(b *testing.B, t trace.Tracer) {
ctx := context.Background() ctx := context.Background()
b.ResetTimer() b.ResetTimer()
@ -133,8 +134,8 @@ func BenchmarkSpanWithAttributes_all_2x(b *testing.B) {
} }
func BenchmarkTraceID_DotString(b *testing.B) { func BenchmarkTraceID_DotString(b *testing.B) {
t, _ := otel.TraceIDFromHex("0000000000000001000000000000002a") t, _ := trace.TraceIDFromHex("0000000000000001000000000000002a")
sc := otel.SpanContext{TraceID: t} sc := trace.SpanContext{TraceID: t}
want := "0000000000000001000000000000002a" want := "0000000000000001000000000000002a"
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
@ -145,7 +146,7 @@ func BenchmarkTraceID_DotString(b *testing.B) {
} }
func BenchmarkSpanID_DotString(b *testing.B) { func BenchmarkSpanID_DotString(b *testing.B) {
sc := otel.SpanContext{SpanID: otel.SpanID{1}} sc := trace.SpanContext{SpanID: trace.SpanID{1}}
want := "0100000000000000" want := "0100000000000000"
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
if got := sc.SpanID.String(); got != want { if got := sc.SpanID.String(); got != want {
@ -154,7 +155,7 @@ func BenchmarkSpanID_DotString(b *testing.B) {
} }
} }
func traceBenchmark(b *testing.B, name string, fn func(*testing.B, otel.Tracer)) { func traceBenchmark(b *testing.B, name string, fn func(*testing.B, trace.Tracer)) {
b.Run("AlwaysSample", func(b *testing.B) { b.Run("AlwaysSample", func(b *testing.B) {
b.ReportAllocs() b.ReportAllocs()
fn(b, tracer(b, name, sdktrace.AlwaysSample())) fn(b, tracer(b, name, sdktrace.AlwaysSample()))
@ -165,7 +166,7 @@ func traceBenchmark(b *testing.B, name string, fn func(*testing.B, otel.Tracer))
}) })
} }
func tracer(b *testing.B, name string, sampler sdktrace.Sampler) otel.Tracer { func tracer(b *testing.B, name string, sampler sdktrace.Sampler) trace.Tracer {
tp := sdktrace.NewTracerProvider(sdktrace.WithConfig(sdktrace.Config{DefaultSampler: sampler})) tp := sdktrace.NewTracerProvider(sdktrace.WithConfig(sdktrace.Config{DefaultSampler: sampler}))
return tp.Tracer(name) return tp.Tracer(name)
} }

View File

@ -18,7 +18,8 @@ import (
"math/rand" "math/rand"
"sync" "sync"
"go.opentelemetry.io/otel" "go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/otel/sdk/trace/internal" "go.opentelemetry.io/otel/sdk/trace/internal"
) )
@ -30,20 +31,20 @@ type defaultIDGenerator struct {
var _ internal.IDGenerator = &defaultIDGenerator{} var _ internal.IDGenerator = &defaultIDGenerator{}
// NewSpanID returns a non-zero span ID from a randomly-chosen sequence. // NewSpanID returns a non-zero span ID from a randomly-chosen sequence.
func (gen *defaultIDGenerator) NewSpanID() otel.SpanID { func (gen *defaultIDGenerator) NewSpanID() trace.SpanID {
gen.Lock() gen.Lock()
defer gen.Unlock() defer gen.Unlock()
sid := otel.SpanID{} sid := trace.SpanID{}
gen.randSource.Read(sid[:]) gen.randSource.Read(sid[:])
return sid return sid
} }
// NewTraceID returns a non-zero trace ID from a randomly-chosen sequence. // NewTraceID returns a non-zero trace ID from a randomly-chosen sequence.
// mu should be held while this function is called. // mu should be held while this function is called.
func (gen *defaultIDGenerator) NewTraceID() otel.TraceID { func (gen *defaultIDGenerator) NewTraceID() trace.TraceID {
gen.Lock() gen.Lock()
defer gen.Unlock() defer gen.Unlock()
tid := otel.TraceID{} tid := trace.TraceID{}
gen.randSource.Read(tid[:]) gen.randSource.Read(tid[:])
return tid return tid
} }

View File

@ -15,10 +15,10 @@
// Package internal provides trace internals. // Package internal provides trace internals.
package internal package internal
import "go.opentelemetry.io/otel" import "go.opentelemetry.io/otel/trace"
// IDGenerator allows custom generators for TraceId and SpanId. // IDGenerator allows custom generators for TraceId and SpanId.
type IDGenerator interface { type IDGenerator interface {
NewTraceID() otel.TraceID NewTraceID() trace.TraceID
NewSpanID() otel.SpanID NewSpanID() trace.SpanID
} }

View File

@ -19,8 +19,9 @@ import (
"sync" "sync"
"sync/atomic" "sync/atomic"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/global"
"go.opentelemetry.io/otel/trace"
export "go.opentelemetry.io/otel/sdk/export/trace" export "go.opentelemetry.io/otel/sdk/export/trace"
"go.opentelemetry.io/otel/sdk/instrumentation" "go.opentelemetry.io/otel/sdk/instrumentation"
"go.opentelemetry.io/otel/sdk/resource" "go.opentelemetry.io/otel/sdk/resource"
@ -48,7 +49,7 @@ type TracerProvider struct {
config atomic.Value // access atomically config atomic.Value // access atomically
} }
var _ otel.TracerProvider = &TracerProvider{} var _ trace.TracerProvider = &TracerProvider{}
// NewTracerProvider creates an instance of trace provider. Optional // NewTracerProvider creates an instance of trace provider. Optional
// parameter configures the provider with common options applicable // parameter configures the provider with common options applicable
@ -82,8 +83,8 @@ func NewTracerProvider(opts ...TracerProviderOption) *TracerProvider {
// Tracer with the given name. If a tracer for the given name does not exist, // Tracer with the given name. If a tracer for the given name does not exist,
// it is created first. If the name is empty, DefaultTracerName is used. // it is created first. If the name is empty, DefaultTracerName is used.
func (p *TracerProvider) Tracer(name string, opts ...otel.TracerOption) otel.Tracer { func (p *TracerProvider) Tracer(name string, opts ...trace.TracerOption) trace.Tracer {
c := otel.NewTracerConfig(opts...) c := trace.NewTracerConfig(opts...)
p.mu.Lock() p.mu.Lock()
defer p.mu.Unlock() defer p.mu.Unlock()

View File

@ -18,8 +18,8 @@ import (
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
"go.opentelemetry.io/otel/trace"
) )
// Sampler decides whether a trace should be sampled and exported. // Sampler decides whether a trace should be sampled and exported.
@ -30,13 +30,13 @@ type Sampler interface {
// SamplingParameters contains the values passed to a Sampler. // SamplingParameters contains the values passed to a Sampler.
type SamplingParameters struct { type SamplingParameters struct {
ParentContext otel.SpanContext ParentContext trace.SpanContext
TraceID otel.TraceID TraceID trace.TraceID
Name string Name string
HasRemoteParent bool HasRemoteParent bool
Kind otel.SpanKind Kind trace.SpanKind
Attributes []label.KeyValue Attributes []label.KeyValue
Links []otel.Link Links []trace.Link
} }
// SamplingDecision indicates whether a span is dropped, recorded and/or sampled. // SamplingDecision indicates whether a span is dropped, recorded and/or sampled.

View File

@ -21,17 +21,17 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"go.opentelemetry.io/otel" "go.opentelemetry.io/otel/trace"
) )
func TestParentBasedDefaultLocalParentSampled(t *testing.T) { func TestParentBasedDefaultLocalParentSampled(t *testing.T) {
sampler := ParentBased(AlwaysSample()) sampler := ParentBased(AlwaysSample())
traceID, _ := otel.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736") traceID, _ := trace.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736")
spanID, _ := otel.SpanIDFromHex("00f067aa0ba902b7") spanID, _ := trace.SpanIDFromHex("00f067aa0ba902b7")
parentCtx := otel.SpanContext{ parentCtx := trace.SpanContext{
TraceID: traceID, TraceID: traceID,
SpanID: spanID, SpanID: spanID,
TraceFlags: otel.FlagsSampled, TraceFlags: trace.FlagsSampled,
} }
if sampler.ShouldSample(SamplingParameters{ParentContext: parentCtx}).Decision != RecordAndSample { if sampler.ShouldSample(SamplingParameters{ParentContext: parentCtx}).Decision != RecordAndSample {
t.Error("Sampling decision should be RecordAndSample") t.Error("Sampling decision should be RecordAndSample")
@ -40,9 +40,9 @@ func TestParentBasedDefaultLocalParentSampled(t *testing.T) {
func TestParentBasedDefaultLocalParentNotSampled(t *testing.T) { func TestParentBasedDefaultLocalParentNotSampled(t *testing.T) {
sampler := ParentBased(AlwaysSample()) sampler := ParentBased(AlwaysSample())
traceID, _ := otel.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736") traceID, _ := trace.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736")
spanID, _ := otel.SpanIDFromHex("00f067aa0ba902b7") spanID, _ := trace.SpanIDFromHex("00f067aa0ba902b7")
parentCtx := otel.SpanContext{ parentCtx := trace.SpanContext{
TraceID: traceID, TraceID: traceID,
SpanID: spanID, SpanID: spanID,
} }
@ -104,15 +104,15 @@ func TestParentBasedWithSamplerOptions(t *testing.T) {
for _, tc := range testCases { for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
traceID, _ := otel.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736") traceID, _ := trace.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736")
spanID, _ := otel.SpanIDFromHex("00f067aa0ba902b7") spanID, _ := trace.SpanIDFromHex("00f067aa0ba902b7")
parentCtx := otel.SpanContext{ parentCtx := trace.SpanContext{
TraceID: traceID, TraceID: traceID,
SpanID: spanID, SpanID: spanID,
} }
if tc.isParentSampled { if tc.isParentSampled {
parentCtx.TraceFlags = otel.FlagsSampled parentCtx.TraceFlags = trace.FlagsSampled
} }
params := SamplingParameters{ParentContext: parentCtx} params := SamplingParameters{ParentContext: parentCtx}

View File

@ -18,7 +18,8 @@ import (
"context" "context"
"testing" "testing"
"go.opentelemetry.io/otel" "go.opentelemetry.io/otel/trace"
export "go.opentelemetry.io/otel/sdk/export/trace" export "go.opentelemetry.io/otel/sdk/export/trace"
sdktrace "go.opentelemetry.io/otel/sdk/trace" sdktrace "go.opentelemetry.io/otel/sdk/trace"
) )
@ -60,14 +61,14 @@ func TestSimpleSpanProcessorOnEnd(t *testing.T) {
tp.RegisterSpanProcessor(ssp) tp.RegisterSpanProcessor(ssp)
tr := tp.Tracer("SimpleSpanProcessor") tr := tp.Tracer("SimpleSpanProcessor")
tid, _ := otel.TraceIDFromHex("01020304050607080102040810203040") tid, _ := trace.TraceIDFromHex("01020304050607080102040810203040")
sid, _ := otel.SpanIDFromHex("0102040810203040") sid, _ := trace.SpanIDFromHex("0102040810203040")
sc := otel.SpanContext{ sc := trace.SpanContext{
TraceID: tid, TraceID: tid,
SpanID: sid, SpanID: sid,
TraceFlags: 0x1, TraceFlags: 0x1,
} }
ctx := otel.ContextWithRemoteSpanContext(context.Background(), sc) ctx := trace.ContextWithRemoteSpanContext(context.Background(), sc)
_, span := tr.Start(ctx, "OnEnd") _, span := tr.Start(ctx, "OnEnd")
span.End() span.End()

View File

@ -21,10 +21,11 @@ import (
"sync" "sync"
"time" "time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/global"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
"go.opentelemetry.io/otel/trace"
export "go.opentelemetry.io/otel/sdk/export/trace" export "go.opentelemetry.io/otel/sdk/export/trace"
"go.opentelemetry.io/otel/sdk/internal" "go.opentelemetry.io/otel/sdk/internal"
) )
@ -35,7 +36,7 @@ const (
errorEventName = "error" errorEventName = "error"
) )
var emptySpanContext = otel.SpanContext{} var emptySpanContext = trace.SpanContext{}
// span is an implementation of the OpenTelemetry Span API representing the // span is an implementation of the OpenTelemetry Span API representing the
// individual component of a trace. // individual component of a trace.
@ -47,7 +48,7 @@ type span struct {
// SpanContext, so that the trace ID is propagated. // SpanContext, so that the trace ID is propagated.
data *export.SpanData data *export.SpanData
mu sync.Mutex // protects the contents of *data (but not the pointer value.) mu sync.Mutex // protects the contents of *data (but not the pointer value.)
spanContext otel.SpanContext spanContext trace.SpanContext
// attributes are capped at configured limit. When the capacity is reached an oldest entry // attributes are capped at configured limit. When the capacity is reached an oldest entry
// is removed to create room for a new entry. // is removed to create room for a new entry.
@ -67,11 +68,11 @@ type span struct {
tracer *tracer // tracer used to create span. tracer *tracer // tracer used to create span.
} }
var _ otel.Span = &span{} var _ trace.Span = &span{}
func (s *span) SpanContext() otel.SpanContext { func (s *span) SpanContext() trace.SpanContext {
if s == nil { if s == nil {
return otel.SpanContext{} return trace.SpanContext{}
} }
return s.spanContext return s.spanContext
} }
@ -110,7 +111,7 @@ func (s *span) SetAttributes(attributes ...label.KeyValue) {
// //
// If this method is called while panicking an error event is added to the // If this method is called while panicking an error event is added to the
// Span before ending it and the panic is continued. // Span before ending it and the panic is continued.
func (s *span) End(options ...otel.SpanOption) { func (s *span) End(options ...trace.SpanOption) {
if s == nil { if s == nil {
return return
} }
@ -120,7 +121,7 @@ func (s *span) End(options ...otel.SpanOption) {
defer panic(recovered) defer panic(recovered)
s.addEvent( s.addEvent(
errorEventName, errorEventName,
otel.WithAttributes( trace.WithAttributes(
errorTypeKey.String(typeStr(recovered)), errorTypeKey.String(typeStr(recovered)),
errorMessageKey.String(fmt.Sprint(recovered)), errorMessageKey.String(fmt.Sprint(recovered)),
), ),
@ -133,7 +134,7 @@ func (s *span) End(options ...otel.SpanOption) {
if !s.IsRecording() { if !s.IsRecording() {
return return
} }
config := otel.NewSpanConfig(options...) config := trace.NewSpanConfig(options...)
s.endOnce.Do(func() { s.endOnce.Do(func() {
sps, ok := s.tracer.provider.spanProcessors.Load().(spanProcessorStates) sps, ok := s.tracer.provider.spanProcessors.Load().(spanProcessorStates)
mustExportOrProcess := ok && len(sps) > 0 mustExportOrProcess := ok && len(sps) > 0
@ -151,13 +152,13 @@ func (s *span) End(options ...otel.SpanOption) {
}) })
} }
func (s *span) RecordError(err error, opts ...otel.EventOption) { func (s *span) RecordError(err error, opts ...trace.EventOption) {
if s == nil || err == nil || !s.IsRecording() { if s == nil || err == nil || !s.IsRecording() {
return return
} }
s.SetStatus(codes.Error, "") s.SetStatus(codes.Error, "")
opts = append(opts, otel.WithAttributes( opts = append(opts, trace.WithAttributes(
errorTypeKey.String(typeStr(err)), errorTypeKey.String(typeStr(err)),
errorMessageKey.String(err.Error()), errorMessageKey.String(err.Error()),
)) ))
@ -173,19 +174,19 @@ func typeStr(i interface{}) string {
return fmt.Sprintf("%s.%s", t.PkgPath(), t.Name()) return fmt.Sprintf("%s.%s", t.PkgPath(), t.Name())
} }
func (s *span) Tracer() otel.Tracer { func (s *span) Tracer() trace.Tracer {
return s.tracer return s.tracer
} }
func (s *span) AddEvent(name string, o ...otel.EventOption) { func (s *span) AddEvent(name string, o ...trace.EventOption) {
if !s.IsRecording() { if !s.IsRecording() {
return return
} }
s.addEvent(name, o...) s.addEvent(name, o...)
} }
func (s *span) addEvent(name string, o ...otel.EventOption) { func (s *span) addEvent(name string, o ...trace.EventOption) {
c := otel.NewEventConfig(o...) c := trace.NewEventConfig(o...)
s.mu.Lock() s.mu.Lock()
defer s.mu.Unlock() defer s.mu.Unlock()
@ -209,9 +210,9 @@ func (s *span) SetName(name string) {
s.data.Name = name s.data.Name = name
// SAMPLING // SAMPLING
noParent := !s.data.ParentSpanID.IsValid() noParent := !s.data.ParentSpanID.IsValid()
var ctx otel.SpanContext var ctx trace.SpanContext
if noParent { if noParent {
ctx = otel.SpanContext{} ctx = trace.SpanContext{}
} else { } else {
// FIXME: Where do we get the parent context from? // FIXME: Where do we get the parent context from?
// From SpanStore? // From SpanStore?
@ -237,7 +238,7 @@ func (s *span) SetName(name string) {
} }
} }
func (s *span) addLink(link otel.Link) { func (s *span) addLink(link trace.Link) {
if !s.IsRecording() { if !s.IsRecording() {
return return
} }
@ -267,10 +268,10 @@ func (s *span) makeSpanData() *export.SpanData {
return &sd return &sd
} }
func (s *span) interfaceArrayToLinksArray() []otel.Link { func (s *span) interfaceArrayToLinksArray() []trace.Link {
linkArr := make([]otel.Link, 0) linkArr := make([]trace.Link, 0)
for _, value := range s.links.queue { for _, value := range s.links.queue {
linkArr = append(linkArr, value.(otel.Link)) linkArr = append(linkArr, value.(trace.Link))
} }
return linkArr return linkArr
} }
@ -302,7 +303,7 @@ func (s *span) addChild() {
s.mu.Unlock() s.mu.Unlock()
} }
func startSpanInternal(tr *tracer, name string, parent otel.SpanContext, remoteParent bool, o *otel.SpanConfig) *span { func startSpanInternal(tr *tracer, name string, parent trace.SpanContext, remoteParent bool, o *trace.SpanConfig) *span {
var noParent bool var noParent bool
span := &span{} span := &span{}
span.spanContext = parent span.spanContext = parent
@ -340,7 +341,7 @@ func startSpanInternal(tr *tracer, name string, parent otel.SpanContext, remoteP
span.data = &export.SpanData{ span.data = &export.SpanData{
SpanContext: span.spanContext, SpanContext: span.spanContext,
StartTime: startTime, StartTime: startTime,
SpanKind: otel.ValidateSpanKind(o.SpanKind), SpanKind: trace.ValidateSpanKind(o.SpanKind),
Name: name, Name: name,
HasRemoteParent: remoteParent, HasRemoteParent: remoteParent,
Resource: cfg.Resource, Resource: cfg.Resource,
@ -370,13 +371,13 @@ func startSpanInternal(tr *tracer, name string, parent otel.SpanContext, remoteP
type samplingData struct { type samplingData struct {
noParent bool noParent bool
remoteParent bool remoteParent bool
parent otel.SpanContext parent trace.SpanContext
name string name string
cfg *Config cfg *Config
span *span span *span
attributes []label.KeyValue attributes []label.KeyValue
links []otel.Link links []trace.Link
kind otel.SpanKind kind trace.SpanKind
} }
func makeSamplingDecision(data samplingData) SamplingResult { func makeSamplingDecision(data samplingData) SamplingResult {
@ -392,9 +393,9 @@ func makeSamplingDecision(data samplingData) SamplingResult {
Links: data.links, Links: data.links,
}) })
if sampled.Decision == RecordAndSample { if sampled.Decision == RecordAndSample {
spanContext.TraceFlags |= otel.FlagsSampled spanContext.TraceFlags |= trace.FlagsSampled
} else { } else {
spanContext.TraceFlags &^= otel.FlagsSampled spanContext.TraceFlags &^= trace.FlagsSampled
} }
return sampled return sampled
} }

View File

@ -25,11 +25,11 @@ import (
"testing" "testing"
"time" "time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/global"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/label"
"go.opentelemetry.io/otel/oteltest" "go.opentelemetry.io/otel/oteltest"
"go.opentelemetry.io/otel/trace"
"github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -42,8 +42,8 @@ import (
) )
var ( var (
tid otel.TraceID tid trace.TraceID
sid otel.SpanID sid trace.SpanID
) )
type discardHandler struct{} type discardHandler struct{}
@ -51,8 +51,8 @@ type discardHandler struct{}
func (*discardHandler) Handle(_ error) {} func (*discardHandler) Handle(_ error) {}
func init() { func init() {
tid, _ = otel.TraceIDFromHex("01020304050607080102040810203040") tid, _ = trace.TraceIDFromHex("01020304050607080102040810203040")
sid, _ = otel.SpanIDFromHex("0102040810203040") sid, _ = trace.SpanIDFromHex("0102040810203040")
global.SetErrorHandler(new(discardHandler)) global.SetErrorHandler(new(discardHandler))
} }
@ -60,7 +60,7 @@ func init() {
func TestTracerFollowsExpectedAPIBehaviour(t *testing.T) { func TestTracerFollowsExpectedAPIBehaviour(t *testing.T) {
tp := NewTracerProvider(WithConfig(Config{DefaultSampler: TraceIDRatioBased(0)})) tp := NewTracerProvider(WithConfig(Config{DefaultSampler: TraceIDRatioBased(0)}))
harness := oteltest.NewHarness(t) harness := oteltest.NewHarness(t)
subjectFactory := func() otel.Tracer { subjectFactory := func() trace.Tracer {
return tp.Tracer("") return tp.Tracer("")
} }
@ -263,14 +263,14 @@ func TestSampling(t *testing.T) {
for i := 0; i < total; i++ { for i := 0; i < total; i++ {
ctx := context.Background() ctx := context.Background()
if tc.parent { if tc.parent {
psc := otel.SpanContext{ psc := trace.SpanContext{
TraceID: idg.NewTraceID(), TraceID: idg.NewTraceID(),
SpanID: idg.NewSpanID(), SpanID: idg.NewSpanID(),
} }
if tc.sampledParent { if tc.sampledParent {
psc.TraceFlags = otel.FlagsSampled psc.TraceFlags = trace.FlagsSampled
} }
ctx = otel.ContextWithRemoteSpanContext(ctx, psc) ctx = trace.ContextWithRemoteSpanContext(ctx, psc)
} }
_, span := tr.Start(ctx, "test") _, span := tr.Start(ctx, "test")
if span.SpanContext().IsSampled() { if span.SpanContext().IsSampled() {
@ -299,33 +299,33 @@ func TestStartSpanWithParent(t *testing.T) {
tr := tp.Tracer("SpanWithParent") tr := tp.Tracer("SpanWithParent")
ctx := context.Background() ctx := context.Background()
sc1 := otel.SpanContext{ sc1 := trace.SpanContext{
TraceID: tid, TraceID: tid,
SpanID: sid, SpanID: sid,
TraceFlags: 0x1, TraceFlags: 0x1,
} }
_, s1 := tr.Start(otel.ContextWithRemoteSpanContext(ctx, sc1), "span1-unsampled-parent1") _, s1 := tr.Start(trace.ContextWithRemoteSpanContext(ctx, sc1), "span1-unsampled-parent1")
if err := checkChild(sc1, s1); err != nil { if err := checkChild(sc1, s1); err != nil {
t.Error(err) t.Error(err)
} }
_, s2 := tr.Start(otel.ContextWithRemoteSpanContext(ctx, sc1), "span2-unsampled-parent1") _, s2 := tr.Start(trace.ContextWithRemoteSpanContext(ctx, sc1), "span2-unsampled-parent1")
if err := checkChild(sc1, s2); err != nil { if err := checkChild(sc1, s2); err != nil {
t.Error(err) t.Error(err)
} }
sc2 := otel.SpanContext{ sc2 := trace.SpanContext{
TraceID: tid, TraceID: tid,
SpanID: sid, SpanID: sid,
TraceFlags: 0x1, TraceFlags: 0x1,
//Tracestate: testTracestate, //Tracestate: testTracestate,
} }
_, s3 := tr.Start(otel.ContextWithRemoteSpanContext(ctx, sc2), "span3-sampled-parent2") _, s3 := tr.Start(trace.ContextWithRemoteSpanContext(ctx, sc2), "span3-sampled-parent2")
if err := checkChild(sc2, s3); err != nil { if err := checkChild(sc2, s3); err != nil {
t.Error(err) t.Error(err)
} }
ctx2, s4 := tr.Start(otel.ContextWithRemoteSpanContext(ctx, sc2), "span4-sampled-parent2") ctx2, s4 := tr.Start(trace.ContextWithRemoteSpanContext(ctx, sc2), "span4-sampled-parent2")
if err := checkChild(sc2, s4); err != nil { if err := checkChild(sc2, s4); err != nil {
t.Error(err) t.Error(err)
} }
@ -342,8 +342,8 @@ func TestSetSpanAttributesOnStart(t *testing.T) {
tp := NewTracerProvider(WithSyncer(te)) tp := NewTracerProvider(WithSyncer(te))
span := startSpan(tp, span := startSpan(tp,
"StartSpanAttribute", "StartSpanAttribute",
otel.WithAttributes(label.String("key1", "value1")), trace.WithAttributes(label.String("key1", "value1")),
otel.WithAttributes(label.String("key2", "value2")), trace.WithAttributes(label.String("key2", "value2")),
) )
got, err := endSpan(te, span) got, err := endSpan(te, span)
if err != nil { if err != nil {
@ -351,7 +351,7 @@ func TestSetSpanAttributesOnStart(t *testing.T) {
} }
want := &export.SpanData{ want := &export.SpanData{
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: tid, TraceID: tid,
TraceFlags: 0x1, TraceFlags: 0x1,
}, },
@ -361,7 +361,7 @@ func TestSetSpanAttributesOnStart(t *testing.T) {
label.String("key1", "value1"), label.String("key1", "value1"),
label.String("key2", "value2"), label.String("key2", "value2"),
}, },
SpanKind: otel.SpanKindInternal, SpanKind: trace.SpanKindInternal,
HasRemoteParent: true, HasRemoteParent: true,
InstrumentationLibrary: instrumentation.Library{Name: "StartSpanAttribute"}, InstrumentationLibrary: instrumentation.Library{Name: "StartSpanAttribute"},
} }
@ -381,7 +381,7 @@ func TestSetSpanAttributes(t *testing.T) {
} }
want := &export.SpanData{ want := &export.SpanData{
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: tid, TraceID: tid,
TraceFlags: 0x1, TraceFlags: 0x1,
}, },
@ -390,7 +390,7 @@ func TestSetSpanAttributes(t *testing.T) {
Attributes: []label.KeyValue{ Attributes: []label.KeyValue{
label.String("key1", "value1"), label.String("key1", "value1"),
}, },
SpanKind: otel.SpanKindInternal, SpanKind: trace.SpanKindInternal,
HasRemoteParent: true, HasRemoteParent: true,
InstrumentationLibrary: instrumentation.Library{Name: "SpanAttribute"}, InstrumentationLibrary: instrumentation.Library{Name: "SpanAttribute"},
} }
@ -424,36 +424,36 @@ func TestSamplerAttributesLocalChildSpan(t *testing.T) {
checkTime(&got[0].StartTime) checkTime(&got[0].StartTime)
checkTime(&got[0].EndTime) checkTime(&got[0].EndTime)
got[1].SpanContext.SpanID = otel.SpanID{} got[1].SpanContext.SpanID = trace.SpanID{}
got[1].SpanContext.TraceID = tid got[1].SpanContext.TraceID = tid
got[1].ParentSpanID = pid got[1].ParentSpanID = pid
got[0].SpanContext.SpanID = otel.SpanID{} got[0].SpanContext.SpanID = trace.SpanID{}
checkTime(&got[1].StartTime) checkTime(&got[1].StartTime)
checkTime(&got[1].EndTime) checkTime(&got[1].EndTime)
want := []*export.SpanData{ want := []*export.SpanData{
{ {
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: tid, TraceID: tid,
TraceFlags: 0x1, TraceFlags: 0x1,
}, },
ParentSpanID: sid, ParentSpanID: sid,
Name: "span1", Name: "span1",
Attributes: []label.KeyValue{label.Int("callCount", 2)}, Attributes: []label.KeyValue{label.Int("callCount", 2)},
SpanKind: otel.SpanKindInternal, SpanKind: trace.SpanKindInternal,
HasRemoteParent: false, HasRemoteParent: false,
InstrumentationLibrary: instrumentation.Library{Name: "SpanTwo"}, InstrumentationLibrary: instrumentation.Library{Name: "SpanTwo"},
}, },
{ {
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: tid, TraceID: tid,
TraceFlags: 0x1, TraceFlags: 0x1,
}, },
ParentSpanID: pid, ParentSpanID: pid,
Name: "span0", Name: "span0",
Attributes: []label.KeyValue{label.Int("callCount", 1)}, Attributes: []label.KeyValue{label.Int("callCount", 1)},
SpanKind: otel.SpanKindInternal, SpanKind: trace.SpanKindInternal,
HasRemoteParent: false, HasRemoteParent: false,
ChildSpanCount: 1, ChildSpanCount: 1,
InstrumentationLibrary: instrumentation.Library{Name: "SpanOne"}, InstrumentationLibrary: instrumentation.Library{Name: "SpanOne"},
@ -483,7 +483,7 @@ func TestSetSpanAttributesOverLimit(t *testing.T) {
} }
want := &export.SpanData{ want := &export.SpanData{
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: tid, TraceID: tid,
TraceFlags: 0x1, TraceFlags: 0x1,
}, },
@ -493,7 +493,7 @@ func TestSetSpanAttributesOverLimit(t *testing.T) {
label.Bool("key1", false), label.Bool("key1", false),
label.Int64("key4", 4), label.Int64("key4", 4),
}, },
SpanKind: otel.SpanKindInternal, SpanKind: trace.SpanKindInternal,
HasRemoteParent: true, HasRemoteParent: true,
DroppedAttributeCount: 1, DroppedAttributeCount: 1,
InstrumentationLibrary: instrumentation.Library{Name: "SpanAttributesOverLimit"}, InstrumentationLibrary: instrumentation.Library{Name: "SpanAttributesOverLimit"},
@ -512,8 +512,8 @@ func TestEvents(t *testing.T) {
k2v2 := label.Bool("key2", true) k2v2 := label.Bool("key2", true)
k3v3 := label.Int64("key3", 3) k3v3 := label.Int64("key3", 3)
span.AddEvent("foo", otel.WithAttributes(label.String("key1", "value1"))) span.AddEvent("foo", trace.WithAttributes(label.String("key1", "value1")))
span.AddEvent("bar", otel.WithAttributes( span.AddEvent("bar", trace.WithAttributes(
label.Bool("key2", true), label.Bool("key2", true),
label.Int64("key3", 3), label.Int64("key3", 3),
)) ))
@ -529,7 +529,7 @@ func TestEvents(t *testing.T) {
} }
want := &export.SpanData{ want := &export.SpanData{
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: tid, TraceID: tid,
TraceFlags: 0x1, TraceFlags: 0x1,
}, },
@ -540,7 +540,7 @@ func TestEvents(t *testing.T) {
{Name: "foo", Attributes: []label.KeyValue{k1v1}}, {Name: "foo", Attributes: []label.KeyValue{k1v1}},
{Name: "bar", Attributes: []label.KeyValue{k2v2, k3v3}}, {Name: "bar", Attributes: []label.KeyValue{k2v2, k3v3}},
}, },
SpanKind: otel.SpanKindInternal, SpanKind: trace.SpanKindInternal,
InstrumentationLibrary: instrumentation.Library{Name: "Events"}, InstrumentationLibrary: instrumentation.Library{Name: "Events"},
} }
if diff := cmpDiff(got, want); diff != "" { if diff := cmpDiff(got, want); diff != "" {
@ -558,13 +558,13 @@ func TestEventsOverLimit(t *testing.T) {
k2v2 := label.Bool("key2", false) k2v2 := label.Bool("key2", false)
k3v3 := label.String("key3", "value3") k3v3 := label.String("key3", "value3")
span.AddEvent("fooDrop", otel.WithAttributes(label.String("key1", "value1"))) span.AddEvent("fooDrop", trace.WithAttributes(label.String("key1", "value1")))
span.AddEvent("barDrop", otel.WithAttributes( span.AddEvent("barDrop", trace.WithAttributes(
label.Bool("key2", true), label.Bool("key2", true),
label.String("key3", "value3"), label.String("key3", "value3"),
)) ))
span.AddEvent("foo", otel.WithAttributes(label.String("key1", "value1"))) span.AddEvent("foo", trace.WithAttributes(label.String("key1", "value1")))
span.AddEvent("bar", otel.WithAttributes( span.AddEvent("bar", trace.WithAttributes(
label.Bool("key2", false), label.Bool("key2", false),
label.String("key3", "value3"), label.String("key3", "value3"),
)) ))
@ -580,7 +580,7 @@ func TestEventsOverLimit(t *testing.T) {
} }
want := &export.SpanData{ want := &export.SpanData{
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: tid, TraceID: tid,
TraceFlags: 0x1, TraceFlags: 0x1,
}, },
@ -592,7 +592,7 @@ func TestEventsOverLimit(t *testing.T) {
}, },
DroppedMessageEventCount: 2, DroppedMessageEventCount: 2,
HasRemoteParent: true, HasRemoteParent: true,
SpanKind: otel.SpanKindInternal, SpanKind: trace.SpanKindInternal,
InstrumentationLibrary: instrumentation.Library{Name: "EventsOverLimit"}, InstrumentationLibrary: instrumentation.Library{Name: "EventsOverLimit"},
} }
if diff := cmpDiff(got, want); diff != "" { if diff := cmpDiff(got, want); diff != "" {
@ -608,14 +608,14 @@ func TestLinks(t *testing.T) {
k2v2 := label.String("key2", "value2") k2v2 := label.String("key2", "value2")
k3v3 := label.String("key3", "value3") k3v3 := label.String("key3", "value3")
sc1 := otel.SpanContext{TraceID: otel.TraceID([16]byte{1, 1}), SpanID: otel.SpanID{3}} sc1 := trace.SpanContext{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}}
sc2 := otel.SpanContext{TraceID: otel.TraceID([16]byte{1, 1}), SpanID: otel.SpanID{3}} sc2 := trace.SpanContext{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}}
links := []otel.Link{ links := []trace.Link{
{SpanContext: sc1, Attributes: []label.KeyValue{k1v1}}, {SpanContext: sc1, Attributes: []label.KeyValue{k1v1}},
{SpanContext: sc2, Attributes: []label.KeyValue{k2v2, k3v3}}, {SpanContext: sc2, Attributes: []label.KeyValue{k2v2, k3v3}},
} }
span := startSpan(tp, "Links", otel.WithLinks(links...)) span := startSpan(tp, "Links", trace.WithLinks(links...))
got, err := endSpan(te, span) got, err := endSpan(te, span)
if err != nil { if err != nil {
@ -623,7 +623,7 @@ func TestLinks(t *testing.T) {
} }
want := &export.SpanData{ want := &export.SpanData{
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: tid, TraceID: tid,
TraceFlags: 0x1, TraceFlags: 0x1,
}, },
@ -631,7 +631,7 @@ func TestLinks(t *testing.T) {
Name: "span0", Name: "span0",
HasRemoteParent: true, HasRemoteParent: true,
Links: links, Links: links,
SpanKind: otel.SpanKindInternal, SpanKind: trace.SpanKindInternal,
InstrumentationLibrary: instrumentation.Library{Name: "Links"}, InstrumentationLibrary: instrumentation.Library{Name: "Links"},
} }
if diff := cmpDiff(got, want); diff != "" { if diff := cmpDiff(got, want); diff != "" {
@ -643,17 +643,17 @@ func TestLinksOverLimit(t *testing.T) {
te := NewTestExporter() te := NewTestExporter()
cfg := Config{MaxLinksPerSpan: 2} cfg := Config{MaxLinksPerSpan: 2}
sc1 := otel.SpanContext{TraceID: otel.TraceID([16]byte{1, 1}), SpanID: otel.SpanID{3}} sc1 := trace.SpanContext{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}}
sc2 := otel.SpanContext{TraceID: otel.TraceID([16]byte{1, 1}), SpanID: otel.SpanID{3}} sc2 := trace.SpanContext{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}}
sc3 := otel.SpanContext{TraceID: otel.TraceID([16]byte{1, 1}), SpanID: otel.SpanID{3}} sc3 := trace.SpanContext{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}}
tp := NewTracerProvider(WithConfig(cfg), WithSyncer(te)) tp := NewTracerProvider(WithConfig(cfg), WithSyncer(te))
span := startSpan(tp, "LinksOverLimit", span := startSpan(tp, "LinksOverLimit",
otel.WithLinks( trace.WithLinks(
otel.Link{SpanContext: sc1, Attributes: []label.KeyValue{label.String("key1", "value1")}}, trace.Link{SpanContext: sc1, Attributes: []label.KeyValue{label.String("key1", "value1")}},
otel.Link{SpanContext: sc2, Attributes: []label.KeyValue{label.String("key2", "value2")}}, trace.Link{SpanContext: sc2, Attributes: []label.KeyValue{label.String("key2", "value2")}},
otel.Link{SpanContext: sc3, Attributes: []label.KeyValue{label.String("key3", "value3")}}, trace.Link{SpanContext: sc3, Attributes: []label.KeyValue{label.String("key3", "value3")}},
), ),
) )
@ -666,19 +666,19 @@ func TestLinksOverLimit(t *testing.T) {
} }
want := &export.SpanData{ want := &export.SpanData{
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: tid, TraceID: tid,
TraceFlags: 0x1, TraceFlags: 0x1,
}, },
ParentSpanID: sid, ParentSpanID: sid,
Name: "span0", Name: "span0",
Links: []otel.Link{ Links: []trace.Link{
{SpanContext: sc2, Attributes: []label.KeyValue{k2v2}}, {SpanContext: sc2, Attributes: []label.KeyValue{k2v2}},
{SpanContext: sc3, Attributes: []label.KeyValue{k3v3}}, {SpanContext: sc3, Attributes: []label.KeyValue{k3v3}},
}, },
DroppedLinkCount: 1, DroppedLinkCount: 1,
HasRemoteParent: true, HasRemoteParent: true,
SpanKind: otel.SpanKindInternal, SpanKind: trace.SpanKindInternal,
InstrumentationLibrary: instrumentation.Library{Name: "LinksOverLimit"}, InstrumentationLibrary: instrumentation.Library{Name: "LinksOverLimit"},
} }
if diff := cmpDiff(got, want); diff != "" { if diff := cmpDiff(got, want); diff != "" {
@ -692,7 +692,7 @@ func TestSetSpanName(t *testing.T) {
ctx := context.Background() ctx := context.Background()
want := "SpanName-1" want := "SpanName-1"
ctx = otel.ContextWithRemoteSpanContext(ctx, otel.SpanContext{ ctx = trace.ContextWithRemoteSpanContext(ctx, trace.SpanContext{
TraceID: tid, TraceID: tid,
SpanID: sid, SpanID: sid,
TraceFlags: 1, TraceFlags: 1,
@ -720,13 +720,13 @@ func TestSetSpanStatus(t *testing.T) {
} }
want := &export.SpanData{ want := &export.SpanData{
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: tid, TraceID: tid,
TraceFlags: 0x1, TraceFlags: 0x1,
}, },
ParentSpanID: sid, ParentSpanID: sid,
Name: "span0", Name: "span0",
SpanKind: otel.SpanKindInternal, SpanKind: trace.SpanKindInternal,
StatusCode: codes.Error, StatusCode: codes.Error,
StatusMessage: "Error", StatusMessage: "Error",
HasRemoteParent: true, HasRemoteParent: true,
@ -743,8 +743,8 @@ func cmpDiff(x, y interface{}) string {
cmp.AllowUnexported(export.Event{})) cmp.AllowUnexported(export.Event{}))
} }
func remoteSpanContext() otel.SpanContext { func remoteSpanContext() trace.SpanContext {
return otel.SpanContext{ return trace.SpanContext{
TraceID: tid, TraceID: tid,
SpanID: sid, SpanID: sid,
TraceFlags: 1, TraceFlags: 1,
@ -753,7 +753,7 @@ func remoteSpanContext() otel.SpanContext {
// checkChild is test utility function that tests that c has fields set appropriately, // checkChild is test utility function that tests that c has fields set appropriately,
// given that it is a child span of p. // given that it is a child span of p.
func checkChild(p otel.SpanContext, apiSpan otel.Span) error { func checkChild(p trace.SpanContext, apiSpan trace.Span) error {
s := apiSpan.(*span) s := apiSpan.(*span)
if s == nil { if s == nil {
return fmt.Errorf("got nil child span, want non-nil") return fmt.Errorf("got nil child span, want non-nil")
@ -776,7 +776,7 @@ func checkChild(p otel.SpanContext, apiSpan otel.Span) error {
// startSpan starts a span with a name "span0". See startNamedSpan for // startSpan starts a span with a name "span0". See startNamedSpan for
// details. // details.
func startSpan(tp *TracerProvider, trName string, args ...otel.SpanOption) otel.Span { func startSpan(tp *TracerProvider, trName string, args ...trace.SpanOption) trace.Span {
return startNamedSpan(tp, trName, "span0", args...) return startNamedSpan(tp, trName, "span0", args...)
} }
@ -784,10 +784,10 @@ func startSpan(tp *TracerProvider, trName string, args ...otel.SpanOption) otel.
// passed name and with remote span context as parent. The remote span // passed name and with remote span context as parent. The remote span
// context contains TraceFlags with sampled bit set. This allows the // context contains TraceFlags with sampled bit set. This allows the
// span to be automatically sampled. // span to be automatically sampled.
func startNamedSpan(tp *TracerProvider, trName, name string, args ...otel.SpanOption) otel.Span { func startNamedSpan(tp *TracerProvider, trName, name string, args ...trace.SpanOption) trace.Span {
ctx := context.Background() ctx := context.Background()
ctx = otel.ContextWithRemoteSpanContext(ctx, remoteSpanContext()) ctx = trace.ContextWithRemoteSpanContext(ctx, remoteSpanContext())
args = append(args, otel.WithRecord()) args = append(args, trace.WithRecord())
_, span := tp.Tracer(trName).Start( _, span := tp.Tracer(trName).Start(
ctx, ctx,
name, name,
@ -800,8 +800,8 @@ func startNamedSpan(tp *TracerProvider, trName, name string, args ...otel.SpanOp
// passed name and with the passed context. The context is returned // passed name and with the passed context. The context is returned
// along with the span so this parent can be used to create child // along with the span so this parent can be used to create child
// spans. // spans.
func startLocalSpan(tp *TracerProvider, ctx context.Context, trName, name string, args ...otel.SpanOption) (context.Context, otel.Span) { func startLocalSpan(tp *TracerProvider, ctx context.Context, trName, name string, args ...trace.SpanOption) (context.Context, trace.Span) {
args = append(args, otel.WithRecord()) args = append(args, trace.WithRecord())
ctx, span := tp.Tracer(trName).Start( ctx, span := tp.Tracer(trName).Start(
ctx, ctx,
name, name,
@ -819,7 +819,7 @@ func startLocalSpan(tp *TracerProvider, ctx context.Context, trName, name string
// //
// It also does some basic tests on the span. // It also does some basic tests on the span.
// It also clears spanID in the export.SpanData to make the comparison easier. // It also clears spanID in the export.SpanData to make the comparison easier.
func endSpan(te *testExporter, span otel.Span) (*export.SpanData, error) { func endSpan(te *testExporter, span trace.Span) (*export.SpanData, error) {
if !span.IsRecording() { if !span.IsRecording() {
return nil, fmt.Errorf("IsRecording: got false, want true") return nil, fmt.Errorf("IsRecording: got false, want true")
} }
@ -834,7 +834,7 @@ func endSpan(te *testExporter, span otel.Span) (*export.SpanData, error) {
if !got.SpanContext.SpanID.IsValid() { if !got.SpanContext.SpanID.IsValid() {
return nil, fmt.Errorf("exporting span: expected nonzero SpanID") return nil, fmt.Errorf("exporting span: expected nonzero SpanID")
} }
got.SpanContext.SpanID = otel.SpanID{} got.SpanContext.SpanID = trace.SpanID{}
if !checkTime(&got.StartTime) { if !checkTime(&got.StartTime) {
return nil, fmt.Errorf("exporting span: expected nonzero StartTime") return nil, fmt.Errorf("exporting span: expected nonzero StartTime")
} }
@ -871,7 +871,7 @@ func TestStartSpanAfterEnd(t *testing.T) {
ctx := context.Background() ctx := context.Background()
tr := tp.Tracer("SpanAfterEnd") tr := tp.Tracer("SpanAfterEnd")
ctx, span0 := tr.Start(otel.ContextWithRemoteSpanContext(ctx, remoteSpanContext()), "parent") ctx, span0 := tr.Start(trace.ContextWithRemoteSpanContext(ctx, remoteSpanContext()), "parent")
ctx1, span1 := tr.Start(ctx, "span-1") ctx1, span1 := tr.Start(ctx, "span-1")
span1.End() span1.End()
// Start a new span with the context containing span-1 // Start a new span with the context containing span-1
@ -980,12 +980,12 @@ func TestExecutionTracerTaskEnd(t *testing.T) {
s.executionTracerTaskEnd = executionTracerTaskEnd s.executionTracerTaskEnd = executionTracerTaskEnd
spans = append(spans, s) // never sample spans = append(spans, s) // never sample
tID, _ := otel.TraceIDFromHex("0102030405060708090a0b0c0d0e0f") tID, _ := trace.TraceIDFromHex("0102030405060708090a0b0c0d0e0f")
sID, _ := otel.SpanIDFromHex("0001020304050607") sID, _ := trace.SpanIDFromHex("0001020304050607")
ctx := context.Background() ctx := context.Background()
ctx = otel.ContextWithRemoteSpanContext(ctx, ctx = trace.ContextWithRemoteSpanContext(ctx,
otel.SpanContext{ trace.SpanContext{
TraceID: tID, TraceID: tID,
SpanID: sID, SpanID: sID,
TraceFlags: 0, TraceFlags: 0,
@ -1022,9 +1022,9 @@ func TestCustomStartEndTime(t *testing.T) {
_, span := tp.Tracer("Custom Start and End time").Start( _, span := tp.Tracer("Custom Start and End time").Start(
context.Background(), context.Background(),
"testspan", "testspan",
otel.WithTimestamp(startTime), trace.WithTimestamp(startTime),
) )
span.End(otel.WithTimestamp(endTime)) span.End(trace.WithTimestamp(endTime))
if te.Len() != 1 { if te.Len() != 1 {
t.Fatalf("got %d exported spans, want one span", te.Len()) t.Fatalf("got %d exported spans, want one span", te.Len())
@ -1062,7 +1062,7 @@ func TestRecordError(t *testing.T) {
span := startSpan(tp, "RecordError") span := startSpan(tp, "RecordError")
errTime := time.Now() errTime := time.Now()
span.RecordError(s.err, otel.WithTimestamp(errTime)) span.RecordError(s.err, trace.WithTimestamp(errTime))
got, err := endSpan(te, span) got, err := endSpan(te, span)
if err != nil { if err != nil {
@ -1070,14 +1070,14 @@ func TestRecordError(t *testing.T) {
} }
want := &export.SpanData{ want := &export.SpanData{
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: tid, TraceID: tid,
TraceFlags: 0x1, TraceFlags: 0x1,
}, },
ParentSpanID: sid, ParentSpanID: sid,
Name: "span0", Name: "span0",
StatusCode: codes.Error, StatusCode: codes.Error,
SpanKind: otel.SpanKindInternal, SpanKind: trace.SpanKindInternal,
HasRemoteParent: true, HasRemoteParent: true,
MessageEvents: []export.Event{ MessageEvents: []export.Event{
{ {
@ -1110,13 +1110,13 @@ func TestRecordErrorNil(t *testing.T) {
} }
want := &export.SpanData{ want := &export.SpanData{
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: tid, TraceID: tid,
TraceFlags: 0x1, TraceFlags: 0x1,
}, },
ParentSpanID: sid, ParentSpanID: sid,
Name: "span0", Name: "span0",
SpanKind: otel.SpanKindInternal, SpanKind: trace.SpanKindInternal,
HasRemoteParent: true, HasRemoteParent: true,
StatusCode: codes.Unset, StatusCode: codes.Unset,
StatusMessage: "", StatusMessage: "",
@ -1138,22 +1138,22 @@ func TestWithSpanKind(t *testing.T) {
t.Error(err.Error()) t.Error(err.Error())
} }
if spanData.SpanKind != otel.SpanKindInternal { if spanData.SpanKind != trace.SpanKindInternal {
t.Errorf("Default value of Spankind should be Internal: got %+v, want %+v\n", spanData.SpanKind, otel.SpanKindInternal) t.Errorf("Default value of Spankind should be Internal: got %+v, want %+v\n", spanData.SpanKind, trace.SpanKindInternal)
} }
sks := []otel.SpanKind{ sks := []trace.SpanKind{
otel.SpanKindInternal, trace.SpanKindInternal,
otel.SpanKindServer, trace.SpanKindServer,
otel.SpanKindClient, trace.SpanKindClient,
otel.SpanKindProducer, trace.SpanKindProducer,
otel.SpanKindConsumer, trace.SpanKindConsumer,
} }
for _, sk := range sks { for _, sk := range sks {
te.Reset() te.Reset()
_, span := tr.Start(context.Background(), fmt.Sprintf("SpanKind-%v", sk), otel.WithSpanKind(sk)) _, span := tr.Start(context.Background(), fmt.Sprintf("SpanKind-%v", sk), trace.WithSpanKind(sk))
spanData, err := endSpan(te, span) spanData, err := endSpan(te, span)
if err != nil { if err != nil {
t.Error(err.Error()) t.Error(err.Error())
@ -1178,7 +1178,7 @@ func TestWithResource(t *testing.T) {
} }
want := &export.SpanData{ want := &export.SpanData{
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: tid, TraceID: tid,
TraceFlags: 0x1, TraceFlags: 0x1,
}, },
@ -1187,7 +1187,7 @@ func TestWithResource(t *testing.T) {
Attributes: []label.KeyValue{ Attributes: []label.KeyValue{
label.String("key1", "value1"), label.String("key1", "value1"),
}, },
SpanKind: otel.SpanKindInternal, SpanKind: trace.SpanKindInternal,
HasRemoteParent: true, HasRemoteParent: true,
Resource: resource.NewWithAttributes(label.String("rk1", "rv1"), label.Int64("rk2", 5)), Resource: resource.NewWithAttributes(label.String("rk1", "rv1"), label.Int64("rk2", 5)),
InstrumentationLibrary: instrumentation.Library{Name: "WithResource"}, InstrumentationLibrary: instrumentation.Library{Name: "WithResource"},
@ -1202,24 +1202,24 @@ func TestWithInstrumentationVersion(t *testing.T) {
tp := NewTracerProvider(WithSyncer(te)) tp := NewTracerProvider(WithSyncer(te))
ctx := context.Background() ctx := context.Background()
ctx = otel.ContextWithRemoteSpanContext(ctx, remoteSpanContext()) ctx = trace.ContextWithRemoteSpanContext(ctx, remoteSpanContext())
_, span := tp.Tracer( _, span := tp.Tracer(
"WithInstrumentationVersion", "WithInstrumentationVersion",
otel.WithInstrumentationVersion("v0.1.0"), trace.WithInstrumentationVersion("v0.1.0"),
).Start(ctx, "span0", otel.WithRecord()) ).Start(ctx, "span0", trace.WithRecord())
got, err := endSpan(te, span) got, err := endSpan(te, span)
if err != nil { if err != nil {
t.Error(err.Error()) t.Error(err.Error())
} }
want := &export.SpanData{ want := &export.SpanData{
SpanContext: otel.SpanContext{ SpanContext: trace.SpanContext{
TraceID: tid, TraceID: tid,
TraceFlags: 0x1, TraceFlags: 0x1,
}, },
ParentSpanID: sid, ParentSpanID: sid,
Name: "span0", Name: "span0",
SpanKind: otel.SpanKindInternal, SpanKind: trace.SpanKindInternal,
HasRemoteParent: true, HasRemoteParent: true,
InstrumentationLibrary: instrumentation.Library{ InstrumentationLibrary: instrumentation.Library{
Name: "WithInstrumentationVersion", Name: "WithInstrumentationVersion",
@ -1237,7 +1237,7 @@ func TestSpanCapturesPanic(t *testing.T) {
_, span := tp.Tracer("CatchPanic").Start( _, span := tp.Tracer("CatchPanic").Start(
context.Background(), context.Background(),
"span", "span",
otel.WithRecord(), trace.WithRecord(),
) )
f := func() { f := func() {

View File

@ -17,8 +17,9 @@ package trace // import "go.opentelemetry.io/otel/sdk/trace"
import ( import (
"context" "context"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/internal/trace/parent" "go.opentelemetry.io/otel/internal/trace/parent"
"go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/otel/sdk/instrumentation" "go.opentelemetry.io/otel/sdk/instrumentation"
) )
@ -27,7 +28,7 @@ type tracer struct {
instrumentationLibrary instrumentation.Library instrumentationLibrary instrumentation.Library
} }
var _ otel.Tracer = &tracer{} var _ trace.Tracer = &tracer{}
// Start starts a Span and returns it along with a context containing it. // Start starts a Span and returns it along with a context containing it.
// //
@ -35,12 +36,12 @@ var _ otel.Tracer = &tracer{}
// span context found in the passed context. The created Span will be // span context found in the passed context. The created Span will be
// configured appropriately by any SpanOption passed. Any Timestamp option // configured appropriately by any SpanOption passed. Any Timestamp option
// passed will be used as the start time of the Span's life-cycle. // passed will be used as the start time of the Span's life-cycle.
func (tr *tracer) Start(ctx context.Context, name string, options ...otel.SpanOption) (context.Context, otel.Span) { func (tr *tracer) Start(ctx context.Context, name string, options ...trace.SpanOption) (context.Context, trace.Span) {
config := otel.NewSpanConfig(options...) config := trace.NewSpanConfig(options...)
parentSpanContext, remoteParent, links := parent.GetSpanContextAndLinks(ctx, config.NewRoot) parentSpanContext, remoteParent, links := parent.GetSpanContextAndLinks(ctx, config.NewRoot)
if p := otel.SpanFromContext(ctx); p != nil { if p := trace.SpanFromContext(ctx); p != nil {
if sdkSpan, ok := p.(*span); ok { if sdkSpan, ok := p.(*span); ok {
sdkSpan.addChild() sdkSpan.addChild()
} }
@ -66,5 +67,5 @@ func (tr *tracer) Start(ctx context.Context, name string, options ...otel.SpanOp
ctx, end := startExecutionTracerTask(ctx, name) ctx, end := startExecutionTracerTask(ctx, name)
span.executionTracerTaskEnd = end span.executionTracerTaskEnd = end
return otel.ContextWithSpan(ctx, span), span return trace.ContextWithSpan(ctx, span), span
} }

196
trace/config.go Normal file
View File

@ -0,0 +1,196 @@
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package trace
import (
"time"
"go.opentelemetry.io/otel/label"
)
// TracerConfig is a group of options for a Tracer.
type TracerConfig struct {
// InstrumentationVersion is the version of the library providing
// instrumentation.
InstrumentationVersion string
}
// NewTracerConfig applies all the options to a returned TracerConfig.
func NewTracerConfig(options ...TracerOption) *TracerConfig {
config := new(TracerConfig)
for _, option := range options {
option.ApplyTracer(config)
}
return config
}
// TracerOption applies an option to a TracerConfig.
type TracerOption interface {
ApplyTracer(*TracerConfig)
}
// SpanConfig is a group of options for a Span.
type SpanConfig struct {
// Attributes describe the associated qualities of a Span.
Attributes []label.KeyValue
// Timestamp is a time in a Span life-cycle.
Timestamp time.Time
// Links are the associations a Span has with other Spans.
Links []Link
// Record is the recording state of a Span.
Record bool
// NewRoot identifies a Span as the root Span for a new trace. This is
// commonly used when an existing trace crosses trust boundaries and the
// remote parent span context should be ignored for security.
NewRoot bool
// SpanKind is the role a Span has in a trace.
SpanKind SpanKind
}
// NewSpanConfig applies all the options to a returned SpanConfig.
// No validation is performed on the returned SpanConfig (e.g. no uniqueness
// checking or bounding of data), it is left to the SDK to perform this
// action.
func NewSpanConfig(options ...SpanOption) *SpanConfig {
c := new(SpanConfig)
for _, option := range options {
option.ApplySpan(c)
}
return c
}
// SpanOption applies an option to a SpanConfig.
type SpanOption interface {
ApplySpan(*SpanConfig)
}
// NewEventConfig applies all the EventOptions to a returned SpanConfig. If no
// timestamp option is passed, the returned SpanConfig will have a Timestamp
// set to the call time, otherwise no validation is performed on the returned
// SpanConfig.
func NewEventConfig(options ...EventOption) *SpanConfig {
c := new(SpanConfig)
for _, option := range options {
option.ApplyEvent(c)
}
if c.Timestamp.IsZero() {
c.Timestamp = time.Now()
}
return c
}
// EventOption applies span event options to a SpanConfig.
type EventOption interface {
ApplyEvent(*SpanConfig)
}
// LifeCycleOption applies span life-cycle options to a SpanConfig. These
// options set values releated to events in a spans life-cycle like starting,
// ending, experiencing an error and other user defined notable events.
type LifeCycleOption interface {
SpanOption
EventOption
}
type attributeSpanOption []label.KeyValue
func (o attributeSpanOption) ApplySpan(c *SpanConfig) { o.apply(c) }
func (o attributeSpanOption) ApplyEvent(c *SpanConfig) { o.apply(c) }
func (o attributeSpanOption) apply(c *SpanConfig) {
c.Attributes = append(c.Attributes, []label.KeyValue(o)...)
}
// WithAttributes adds the attributes related to a span life-cycle event.
// These attributes are used to describe the work a Span represents when this
// option is provided to a Span's start or end events. Otherwise, these
// attributes provide additional information about the event being recorded
// (e.g. error, state change, processing progress, system event).
//
// If multiple of these options are passed the attributes of each successive
// option will extend the attributes instead of overwriting. There is no
// guarantee of uniqueness in the resulting attributes.
func WithAttributes(attributes ...label.KeyValue) LifeCycleOption {
return attributeSpanOption(attributes)
}
type timestampSpanOption time.Time
func (o timestampSpanOption) ApplySpan(c *SpanConfig) { o.apply(c) }
func (o timestampSpanOption) ApplyEvent(c *SpanConfig) { o.apply(c) }
func (o timestampSpanOption) apply(c *SpanConfig) { c.Timestamp = time.Time(o) }
// WithTimestamp sets the time of a Span life-cycle moment (e.g. started,
// stopped, errored).
func WithTimestamp(t time.Time) LifeCycleOption {
return timestampSpanOption(t)
}
type linksSpanOption []Link
func (o linksSpanOption) ApplySpan(c *SpanConfig) { c.Links = append(c.Links, []Link(o)...) }
// WithLinks adds links to a Span. The links are added to the existing Span
// links, i.e. this does not overwrite.
func WithLinks(links ...Link) SpanOption {
return linksSpanOption(links)
}
type recordSpanOption bool
func (o recordSpanOption) ApplySpan(c *SpanConfig) { c.Record = bool(o) }
// WithRecord specifies that the span should be recorded. It is important to
// note that implementations may override this option, i.e. if the span is a
// child of an un-sampled trace.
func WithRecord() SpanOption {
return recordSpanOption(true)
}
type newRootSpanOption bool
func (o newRootSpanOption) ApplySpan(c *SpanConfig) { c.NewRoot = bool(o) }
// WithNewRoot specifies that the Span should be treated as a root Span. Any
// existing parent span context will be ignored when defining the Span's trace
// identifiers.
func WithNewRoot() SpanOption {
return newRootSpanOption(true)
}
type spanKindSpanOption SpanKind
func (o spanKindSpanOption) ApplySpan(c *SpanConfig) { c.SpanKind = SpanKind(o) }
// WithSpanKind sets the SpanKind of a Span.
func WithSpanKind(kind SpanKind) SpanOption {
return spanKindSpanOption(kind)
}
// InstrumentationOption is an interface for applying instrumentation specific
// options.
type InstrumentationOption interface {
TracerOption
}
// WithInstrumentationVersion sets the instrumentation version.
func WithInstrumentationVersion(version string) InstrumentationOption {
return instrumentationVersionOption(version)
}
type instrumentationVersionOption string
func (i instrumentationVersionOption) ApplyTracer(config *TracerConfig) {
config.InstrumentationVersion = string(i)
}

View File

@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
package otel package trace
import ( import (
"testing" "testing"

View File

@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
package otel // import "go.opentelemetry.io/otel" package trace // import "go.opentelemetry.io/otel/trace"
import ( import (
"bytes" "bytes"
@ -51,6 +51,7 @@ func (e errorConst) Error() string {
} }
// TraceID is a unique identity of a trace. // TraceID is a unique identity of a trace.
// nolint:golint
type TraceID [16]byte type TraceID [16]byte
var nilTraceID TraceID var nilTraceID TraceID
@ -99,6 +100,7 @@ func (s SpanID) String() string {
// TraceIDFromHex returns a TraceID from a hex string if it is compliant with // TraceIDFromHex returns a TraceID from a hex string if it is compliant with
// the W3C trace-context specification. See more at // the W3C trace-context specification. See more at
// https://www.w3.org/TR/trace-context/#trace-id // https://www.w3.org/TR/trace-context/#trace-id
// nolint:golint
func TraceIDFromHex(h string) (TraceID, error) { func TraceIDFromHex(h string) (TraceID, error) {
t := TraceID{} t := TraceID{}
if len(h) != 32 { if len(h) != 32 {

View File

@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
package otel // import "go.opentelemetry.io/otel" package trace // import "go.opentelemetry.io/otel/trace"
import ( import (
"context" "context"

View File

@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
package otel package trace
import ( import (
"context" "context"

View File

@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
package otel package trace
import ( import (
"context" "context"