Skip to content
This repository has been archived by the owner on Mar 6, 2023. It is now read-only.

Commit

Permalink
Merge pull request #29 from opentracing/bhs/span_context_revival
Browse files Browse the repository at this point in the history
Update to support opentracing.SpanContext (and References)
  • Loading branch information
bensigelman authored Jul 6, 2016
2 parents c17acf9 + ffaf3c8 commit 8d298b3
Show file tree
Hide file tree
Showing 13 changed files with 236 additions and 244 deletions.
23 changes: 11 additions & 12 deletions bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func executeOps(sp opentracing.Span, numEvent, numTag, numItems int) {
sp.SetTag(tags[j], nil)
}
for j := 0; j < numItems; j++ {
sp.SetBaggageItem(tags[j], tags[j])
sp.Context().SetBaggageItem(tags[j], tags[j])
}
}

Expand Down Expand Up @@ -108,14 +108,14 @@ func benchmarkInject(b *testing.B, format opentracing.BuiltinFormat, numItems in
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
err := tracer.Inject(sp, format, carrier)
err := tracer.Inject(sp.Context(), format, carrier)
if err != nil {
b.Fatal(err)
}
}
}

func benchmarkJoin(b *testing.B, format opentracing.BuiltinFormat, numItems int) {
func benchmarkExtract(b *testing.B, format opentracing.BuiltinFormat, numItems int) {
var r CountingRecorder
tracer := New(&r)
sp := tracer.StartSpan("testing")
Expand All @@ -129,12 +129,12 @@ func benchmarkJoin(b *testing.B, format opentracing.BuiltinFormat, numItems int)
default:
b.Fatalf("unhandled format %d", format)
}
if err := tracer.Inject(sp, format, carrier); err != nil {
if err := tracer.Inject(sp.Context(), format, carrier); err != nil {
b.Fatal(err)
}

// We create a new bytes.Buffer every time for tracer.Join() to keep this
// benchmark realistic.
// We create a new bytes.Buffer every time for tracer.Extract() to keep
// this benchmark realistic.
var rawBinaryBytes []byte
if format == opentracing.Binary {
rawBinaryBytes = carrier.(*bytes.Buffer).Bytes()
Expand All @@ -144,11 +144,10 @@ func benchmarkJoin(b *testing.B, format opentracing.BuiltinFormat, numItems int)
if format == opentracing.Binary {
carrier = bytes.NewBuffer(rawBinaryBytes)
}
sp, err := tracer.Join("benchmark", format, carrier)
_, err := tracer.Extract(format, carrier)
if err != nil {
b.Fatal(err)
}
sp.Finish() // feed back into buffer pool
}
}

Expand All @@ -169,17 +168,17 @@ func BenchmarkInject_Binary_100BaggageItems(b *testing.B) {
}

func BenchmarkJoin_TextMap_Empty(b *testing.B) {
benchmarkJoin(b, opentracing.TextMap, 0)
benchmarkExtract(b, opentracing.TextMap, 0)
}

func BenchmarkJoin_TextMap_100BaggageItems(b *testing.B) {
benchmarkJoin(b, opentracing.TextMap, 100)
benchmarkExtract(b, opentracing.TextMap, 100)
}

func BenchmarkJoin_Binary_Empty(b *testing.B) {
benchmarkJoin(b, opentracing.Binary, 0)
benchmarkExtract(b, opentracing.Binary, 0)
}

func BenchmarkJoin_Binary_100BaggageItems(b *testing.B) {
benchmarkJoin(b, opentracing.Binary, 100)
benchmarkExtract(b, opentracing.Binary, 100)
}
15 changes: 7 additions & 8 deletions concurrency_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,11 @@ func TestConcurrentUsage(t *testing.T) {
sp := tracer.StartSpan(op)
sp.LogEvent("test event")
sp.SetTag("foo", "bar")
sp.SetBaggageItem("boo", "far")
sp.Context().SetBaggageItem("boo", "far")
sp.SetOperationName("x")
csp := tracer.StartSpanWithOptions(opentracing.StartSpanOptions{
Parent: sp,
})
csp := tracer.StartSpan(
"csp",
opentracing.ChildOf(sp.Context()))
csp.Finish()
defer sp.Finish()
}
Expand All @@ -105,9 +105,8 @@ func TestDisableSpanPool(t *testing.T) {
parent := tracer.StartSpan("parent")
parent.Finish()
// This shouldn't panic.
child := tracer.StartSpanWithOptions(opentracing.StartSpanOptions{
Parent: parent,
OperationName: "child",
})
child := tracer.StartSpan(
"child",
opentracing.ChildOf(parent.Context()))
child.Finish()
}
56 changes: 51 additions & 5 deletions context.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,62 @@
package basictracer

// Context holds the basic Span metadata.
type Context struct {
import (
"sync"

"github.com/opentracing/opentracing-go"
)

// SpanContext holds the basic Span metadata.
type SpanContext struct {
// A probabilistically unique identifier for a [multi-span] trace.
TraceID uint64

// A probabilistically unique identifier for a span.
SpanID uint64

// The SpanID of this Context's parent, or 0 if there is no parent.
ParentSpanID uint64

// Whether the trace is sampled.
Sampled bool

// The span's associated baggage.
baggageLock sync.Mutex
Baggage map[string]string // initialized on first use
}

// BaggageItem belongs to the opentracing.SpanContext interface
func (c *SpanContext) BaggageItem(key string) string {
// TODO: if we want to support onBaggage, need a pointer to the bt.Span.
// s.onBaggage(canonicalKey, val)
// if s.trim() {
// return s
// }

c.baggageLock.Lock()
defer c.baggageLock.Unlock()

if c.Baggage == nil {
return ""
}
return c.Baggage[key]
}

// SetBaggageItem belongs to the opentracing.SpanContext interface
func (c *SpanContext) SetBaggageItem(key, val string) opentracing.SpanContext {
c.baggageLock.Lock()
defer c.baggageLock.Unlock()
if c.Baggage == nil {
c.Baggage = make(map[string]string)
}
c.Baggage[key] = val
return c
}

// ForeachBaggageItem belongs to the opentracing.SpanContext interface
func (c *SpanContext) ForeachBaggageItem(handler func(k, v string) bool) {
c.baggageLock.Lock()
defer c.baggageLock.Unlock()
for k, v := range c.Baggage {
if !handler(k, v) {
break
}
}
}
16 changes: 11 additions & 5 deletions examples/dapperish.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,20 @@ import (
"runtime"
"strings"

"golang.org/x/net/context"

"github.com/opentracing/basictracer-go/examples/dapperish"
opentracing "github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
)

func client() {
reader := bufio.NewReader(os.Stdin)
for {
span := opentracing.StartSpan("getInput")
ctx := opentracing.BackgroundContextWithSpan(span)
ctx := opentracing.ContextWithSpan(context.Background(), span)
// Make sure that global baggage propagation works.
span.SetBaggageItem("User", os.Getenv("USER"))
span.Context().SetBaggageItem("User", os.Getenv("USER"))
span.LogEventWithPayload("ctx", ctx)
fmt.Print("\n\nEnter text (empty string to exit): ")
text, _ := reader.ReadString('\n')
Expand All @@ -36,7 +39,7 @@ func client() {
httpClient := &http.Client{}
httpReq, _ := http.NewRequest("POST", "http://localhost:8080/", bytes.NewReader([]byte(text)))
textCarrier := opentracing.HTTPHeaderTextMapCarrier(httpReq.Header)
err := span.Tracer().Inject(span, opentracing.TextMap, textCarrier)
err := span.Tracer().Inject(span.Context(), opentracing.TextMap, textCarrier)
if err != nil {
panic(err)
}
Expand All @@ -54,11 +57,14 @@ func client() {
func server() {
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
textCarrier := opentracing.HTTPHeaderTextMapCarrier(req.Header)
serverSpan, err := opentracing.GlobalTracer().Join(
"serverSpan", opentracing.TextMap, textCarrier)
wireSpanContext, err := opentracing.GlobalTracer().Extract(
opentracing.TextMap, textCarrier)
if err != nil {
panic(err)
}
serverSpan := opentracing.GlobalTracer().StartSpan(
"serverSpan",
ext.RPCServerOption(wireSpanContext))
serverSpan.SetTag("component", "server")
defer serverSpan.Finish()

Expand Down
2 changes: 1 addition & 1 deletion examples/dapperish/trivialrecorder.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func (t *TrivialRecorder) RecordSpan(span basictracer.RawSpan) {
fmt.Printf(
"RecordSpan: %v[%v, %v us] --> %v logs. std context: %v; baggage: %v\n",
span.Operation, span.Start, span.Duration, len(span.Logs),
span.Context, span.Baggage)
span.SpanContext, span.Baggage)
for i, l := range span.Logs {
fmt.Printf(
" log %v @ %v: %v --> %v\n", i, l.Timestamp, l.Event, reflect.TypeOf(l.Payload))
Expand Down
63 changes: 25 additions & 38 deletions propagation.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
package basictracer

import (
"time"

opentracing "github.com/opentracing/opentracing-go"
)
import opentracing "github.com/opentracing/opentracing-go"

type accessorPropagator struct {
tracer *tracerImpl
Expand All @@ -21,54 +17,45 @@ type DelegatingCarrier interface {
}

func (p *accessorPropagator) Inject(
sp opentracing.Span,
spanContext opentracing.SpanContext,
carrier interface{},
) error {
ac, ok := carrier.(DelegatingCarrier)
if !ok || ac == nil {
dc, ok := carrier.(DelegatingCarrier)
if !ok || dc == nil {
return opentracing.ErrInvalidCarrier
}
si, ok := sp.(*spanImpl)
sc, ok := spanContext.(*SpanContext)
if !ok {
return opentracing.ErrInvalidSpan
return opentracing.ErrInvalidSpanContext
}
meta := si.raw.Context
ac.SetState(meta.TraceID, meta.SpanID, meta.Sampled)
for k, v := range si.raw.Baggage {
ac.SetBaggageItem(k, v)
dc.SetState(sc.TraceID, sc.SpanID, sc.Sampled)
for k, v := range sc.Baggage {
dc.SetBaggageItem(k, v)
}
return nil
}

func (p *accessorPropagator) Join(
operationName string,
func (p *accessorPropagator) Extract(
carrier interface{},
) (opentracing.Span, error) {
ac, ok := carrier.(DelegatingCarrier)
if !ok || ac == nil {
) (opentracing.SpanContext, error) {
dc, ok := carrier.(DelegatingCarrier)
if !ok || dc == nil {
return nil, opentracing.ErrInvalidCarrier
}

sp := p.tracer.getSpan()
ac.GetBaggage(func(k, v string) {
if sp.raw.Baggage == nil {
sp.raw.Baggage = map[string]string{}
traceID, spanID, sampled := dc.State()
sc := &SpanContext{
TraceID: traceID,
SpanID: spanID,
Sampled: sampled,
Baggage: nil,
}
dc.GetBaggage(func(k, v string) {
if sc.Baggage == nil {
sc.Baggage = map[string]string{}
}
sp.raw.Baggage[k] = v
sc.Baggage[k] = v
})

traceID, parentSpanID, sampled := ac.State()
sp.raw.Context = Context{
TraceID: traceID,
SpanID: randomID(),
ParentSpanID: parentSpanID,
Sampled: sampled,
}

return p.tracer.startSpanInternal(
sp,
operationName,
time.Now(),
nil,
), nil
return sc, nil
}
Loading

0 comments on commit 8d298b3

Please sign in to comment.