| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package internal // import "go.opentelemetry.io/otel/bridge/opencensus/internal" |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
"fmt" |
| 9 |
|
| 10 |
octrace "go.opencensus.io/trace" |
| 11 |
|
| 12 |
"go.opentelemetry.io/otel/bridge/opencensus/internal/oc2otel" |
| 13 |
"go.opentelemetry.io/otel/trace" |
| 14 |
) |
| 15 |
|
| 16 |
// Tracer is an OpenCensus Tracer that wraps an OpenTelemetry Tracer. |
| 17 |
type Tracer struct { |
| 18 |
otelTracer trace.Tracer |
| 19 |
} |
| 20 |
|
| 21 |
// NewTracer returns an OpenCensus Tracer that wraps the OpenTelemetry tracer. |
| 22 |
func NewTracer(tracer trace.Tracer) octrace.Tracer { |
| 23 |
return &Tracer{otelTracer: tracer} |
| 24 |
} |
| 25 |
|
| 26 |
// StartSpan starts a new child span of the current span in the context. If |
| 27 |
// there is no span in the context, it creates a new trace and span. |
| 28 |
func (o *Tracer) StartSpan( |
| 29 |
ctx context.Context, |
| 30 |
name string, |
| 31 |
s ...octrace.StartOption, |
| 32 |
) (context.Context, *octrace.Span) { |
| 33 |
otelOpts, err := oc2otel.StartOptions(s) |
| 34 |
if err != nil { |
| 35 |
Handle(fmt.Errorf("starting span %q: %w", name, err)) |
| 36 |
} |
| 37 |
ctx, sp := o.otelTracer.Start(ctx, name, otelOpts...) |
| 38 |
return ctx, NewSpan(sp) |
| 39 |
} |
| 40 |
|
| 41 |
// StartSpanWithRemoteParent starts a new child span of the span from the |
| 42 |
// given parent. |
| 43 |
func (o *Tracer) StartSpanWithRemoteParent( |
| 44 |
ctx context.Context, |
| 45 |
name string, |
| 46 |
parent octrace.SpanContext, |
| 47 |
s ...octrace.StartOption, |
| 48 |
) (context.Context, *octrace.Span) { |
| 49 |
// make sure span context is zeroed out so we use the remote parent |
| 50 |
ctx = trace.ContextWithSpan(ctx, nil) |
| 51 |
ctx = trace.ContextWithRemoteSpanContext(ctx, oc2otel.SpanContext(parent)) |
| 52 |
return o.StartSpan(ctx, name, s...) |
| 53 |
} |
| 54 |
|
| 55 |
// FromContext returns the Span stored in a context. |
| 56 |
func (*Tracer) FromContext(ctx context.Context) *octrace.Span { |
| 57 |
return NewSpan(trace.SpanFromContext(ctx)) |
| 58 |
} |
| 59 |
|
| 60 |
// NewContext returns a new context with the given Span attached. |
| 61 |
func (*Tracer) NewContext(parent context.Context, s *octrace.Span) context.Context { |
| 62 |
if otSpan, ok := s.Internal().(*Span); ok { |
| 63 |
return trace.ContextWithSpan(parent, otSpan.otelSpan) |
| 64 |
} |
| 65 |
Handle( |
| 66 |
fmt.Errorf("unable to create context with span %q, since it was created using a different tracer", s.String()), |
| 67 |
) |
| 68 |
return parent |
| 69 |
} |